Skip to content

Build your personal knowledge base with Trilium Notes

test(core): reach 100% coverage for routes

Elian Doran8dbdc47089f6
diff --git a/apps/server/spec/etapi/auth-login.spec.ts b/apps/server/spec/etapi/auth-login.spec.ts
new file mode 100644
index 0000000000..da7588dd5e
--- /dev/null
+++ b/apps/server/spec/etapi/auth-login.spec.ts
@@ -0,0 +1,66 @@
+import { Application } from "express";
+import { beforeAll, describe, expect, it } from "vitest";
+import supertest from "supertest";
+import config from "../../src/services/config.js";
+
+let app: Application;
+
+const LOGIN_URL = "/etapi/auth/login";
+const CORRECT_PASSWORD = "demo1234";
+
+describe("etapi/auth/login", () => {
+ beforeAll(async () => {
+ config.General.noAuthentication = false;
+ const buildApp = (await import("../../src/app.js")).default;
+ app = await buildApp();
+ });
+
+ it("issues a token for the correct password", async () => {
+ const response = await supertest(app)
+ .post(LOGIN_URL)
+ .send({ password: CORRECT_PASSWORD, tokenName: "test" })
+ .expect(201);
+
+ expect(response.body.authToken).toBeTruthy();
+ });
+
+ // Regression test for the auth-bypass where `verifyPassword` (async) was used
+ // without `await`, so `!verifyPassword(...)` evaluated a truthy Promise and the
+ // wrong-password branch never executed — any password yielded a full-access token.
+ it("rejects a wrong password and issues no token", async () => {
+ const response = await supertest(app)
+ .post(LOGIN_URL)
+ .send({ password: "definitely-not-the-password", tokenName: "test" })
+ .expect(401);
+
+ expect(response.body.code).toBe("WRONG_PASSWORD");
+ expect(response.body.authToken).toBeUndefined();
+ });
+
+ it("rejects an empty password and issues no token", async () => {
+ const response = await supertest(app)
+ .post(LOGIN_URL)
+ .send({ password: "", tokenName: "test" })
+ .expect(401);
+
+ expect(response.body.authToken).toBeUndefined();
+ });
+
+ // A token minted from a wrong password must not grant access to data. Before the
+ // fix, the bypass returned a real, fully-privileged token here.
+ it("does not grant data access from a wrong-password login attempt", async () => {
+ const response = await supertest(app)
+ .post(LOGIN_URL)
+ .send({ password: "definitely-not-the-password", tokenName: "test" });
+
+ const leakedToken = response.body.authToken;
+ // If the bypass is present, `leakedToken` is a usable token; assert it cannot
+ // be used to read the root note.
+ if (leakedToken) {
+ await supertest(app)
+ .get("/etapi/notes/root")
+ .auth("etapi", leakedToken, { type: "basic" })
+ .expect(401);
+ }
+ });
+});
diff --git a/packages/trilium-core/src/routes/api/attachments.spec.ts b/packages/trilium-core/src/routes/api/attachments.spec.ts
index 4d1ec649a3..b02b8eb7a2 100644
--- a/packages/trilium-core/src/routes/api/attachments.spec.ts
+++ b/packages/trilium-core/src/routes/api/attachments.spec.ts
@@ -113,6 +113,76 @@ describe("Attachments API (core)", () => {
expect(res.body.blobId).toBeTruthy();
expect(res.body.content).toContain("blob content here");
});
+
+ it("returns a preview of the attachment blob", async () => {
+ const { noteId } = await createTextNote(api, { title: "Preview owner" });
+ const saved = await saveAttachment(noteId, {
+ title: "Preview attachment",
+ content: "preview body"
+ });
+
+ const res = await api.get<{ blobId: string }>(
+ `/api/attachments/${saved.attachmentId}/blob`,
+ { query: { preview: "true" } }
+ );
+ expect(res.status).toBe(200);
+ expect(res.body.blobId).toBeTruthy();
+ });
+ });
+
+ describe("uploading", () => {
+ it("uploads a non-image file as a 'file' attachment", async () => {
+ const { noteId } = await createTextNote(api, { title: "Upload target" });
+
+ const res = await api.post<{ uploaded: boolean; url: string }>(
+ `/api/notes/${noteId}/attachments/upload`,
+ {
+ file: {
+ originalname: "notes.txt",
+ mimetype: "text/plain",
+ buffer: "file upload content"
+ }
+ }
+ );
+ expect(res.status).toBe(200);
+ expect(res.body.uploaded).toBe(true);
+ expect(res.body.url).toContain(`#root/${noteId}`);
+ expect(res.body.url).toContain("viewMode=attachments");
+ });
+
+ it("uploads an image file as an image attachment", async () => {
+ const { noteId } = await createTextNote(api, { title: "Image upload target" });
+ // Minimal 1x1 transparent PNG.
+ const png = Buffer.from(
+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+M8AAAMBAQDJ/pLvAAAAAElFTkSuQmCC",
+ "base64"
+ );
+
+ const res = await api.post<{ uploaded: boolean; url: string }>(
+ `/api/notes/${noteId}/attachments/upload`,
+ {
+ file: {
+ originalname: "pixel.png",
+ mimetype: "image/png",
+ buffer: png
+ }
+ }
+ );
+ expect(res.status).toBe(200);
+ expect(res.body.uploaded).toBe(true);
+ expect(res.body.url).toContain("/image/");
+ });
+
+ it("reports a missing upload when no file is present", async () => {
+ const { noteId } = await createTextNote(api, { title: "No file target" });
+
+ const res = await api.post<{ uploaded: boolean; message: string }>(
+ `/api/notes/${noteId}/attachments/upload`
+ );
+ expect(res.status).toBe(200);
+ expect(res.body.uploaded).toBe(false);
+ expect(res.body.message).toBeTruthy();
+ });
});
describe("saving", () => {
diff --git a/packages/trilium-core/src/routes/api/attributes.spec.ts b/packages/trilium-core/src/routes/api/attributes.spec.ts
index 37d9e88773..0bcd301595 100644
--- a/packages/trilium-core/src/routes/api/attributes.spec.ts
+++ b/packages/trilium-core/src/routes/api/attributes.spec.ts
@@ -91,5 +91,193 @@ describe("Attributes API (core)", () => {
expect(res.status).toBe(200);
expect(res.body).toMatchObject({ type: "relation", name: "myRelation", value: "root" });
});
+
+ it("reuses the existing relation on repeated create", async () => {
+ const { noteId } = await createTextNote(api);
+
+ const first = await api.put<AttrRow>(`/api/notes/${noteId}/relations/dup/to/root`);
+ const second = await api.put<AttrRow>(`/api/notes/${noteId}/relations/dup/to/root`);
+ expect(second.status).toBe(200);
+ expect(second.body.attributeId).toBe(first.body.attributeId);
+ });
+
+ it("creates then deletes a relation via the relations endpoint", async () => {
+ const { noteId } = await createTextNote(api);
+
+ await api.put(`/api/notes/${noteId}/relations/delMe/to/root`);
+ const del = await api.delete(`/api/notes/${noteId}/relations/delMe/to/root`);
+ expect(del.status).toBe(204);
+
+ const after = await api.get<AttrRow[]>(`/api/notes/${noteId}/attributes`);
+ expect(after.body.some((a) => a.name === "delMe")).toBe(false);
+
+ // deleting a relation that does not exist is a no-op (no attributeId branch)
+ const delAgain = await api.delete(`/api/notes/${noteId}/relations/delMe/to/root`);
+ expect(delAgain.status).toBe(204);
+ });
+
+ it("404s when deleting an attribute owned by another note", async () => {
+ const owner = await createTextNote(api, { title: "Owner" });
+ const other = await createTextNote(api, { title: "Other" });
+
+ const add = await api.post(`/api/notes/${owner.noteId}/attributes`, {
+ body: { type: "label", name: "owned", value: "x" }
+ });
+ expect(add.status).toBe(204);
+ const attrs = await api.get<AttrRow[]>(`/api/notes/${owner.noteId}/attributes`);
+ const attrId = attrs.body.find((a) => a.name === "owned")!.attributeId;
+
+ const del = await api.delete(`/api/notes/${other.noteId}/attributes/${attrId}`);
+ expect(del.status).toBe(400);
+ });
+ });
+
+ describe("updateNoteAttribute", () => {
+ async function addLabel(noteId: string, name: string, value: string) {
+ await api.post(`/api/notes/${noteId}/attributes`, {
+ body: { type: "label", name, value }
+ });
+ const attrs = await api.get<AttrRow[]>(`/api/notes/${noteId}/attributes`);
+ return attrs.body.find((a) => a.name === name)!.attributeId;
+ }
+
+ it("creates a new label when no attributeId is given", async () => {
+ const { noteId } = await createTextNote(api);
+ const res = await api.put<{ attributeId: string }>(`/api/notes/${noteId}/attribute`, {
+ body: { type: "label", name: "fresh", value: "v" }
+ });
+ expect(res.status).toBe(200);
+ expect(res.body.attributeId).toBeTruthy();
+
+ const attrs = await api.get<AttrRow[]>(`/api/notes/${noteId}/attributes`);
+ expect(attrs.body.find((a) => a.attributeId === res.body.attributeId)?.value).toBe("v");
+ });
+
+ it("creates a relation with a target and updates its value in place", async () => {
+ const { noteId } = await createTextNote(api);
+ const created = await api.put<{ attributeId: string }>(`/api/notes/${noteId}/attribute`, {
+ body: { type: "relation", name: "rel", value: "root" }
+ });
+ expect(created.status).toBe(200);
+ expect(created.body.attributeId).toBeTruthy();
+
+ // same id, same type/name, only the relation value changes -> clone + delete
+ const child = await createTextNote(api, { title: "rel target" });
+ const changed = await api.put<{ attributeId: string }>(`/api/notes/${noteId}/attribute`, {
+ body: { attributeId: created.body.attributeId, type: "relation", name: "rel", value: child.noteId }
+ });
+ expect(changed.status).toBe(200);
+ expect(changed.body.attributeId).not.toBe(created.body.attributeId);
+ });
+
+ it("returns {} when creating a relation with no target and no id", async () => {
+ const { noteId } = await createTextNote(api);
+ const res = await api.put<Record<string, never>>(`/api/notes/${noteId}/attribute`, {
+ body: { type: "relation", name: "noTarget", value: " " }
+ });
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual({});
+ });
+
+ it("clones the attribute when type or name changes", async () => {
+ const { noteId } = await createTextNote(api);
+ const attrId = await addLabel(noteId, "rename", "v");
+
+ const res = await api.put<{ attributeId: string | null }>(`/api/notes/${noteId}/attribute`, {
+ body: { attributeId: attrId, type: "label", name: "renamed", value: "v" }
+ });
+ expect(res.status).toBe(200);
+ expect(res.body.attributeId).toBeTruthy();
+ expect(res.body.attributeId).not.toBe(attrId);
+ });
+
+ it("updates the value when only the value changes", async () => {
+ const { noteId } = await createTextNote(api);
+ const attrId = await addLabel(noteId, "stable", "old");
+
+ const res = await api.put<{ attributeId: string }>(`/api/notes/${noteId}/attribute`, {
+ body: { attributeId: attrId, type: "label", name: "stable", value: "new" }
+ });
+ expect(res.status).toBe(200);
+ expect(res.body.attributeId).toBe(attrId);
+
+ const attrs = await api.get<AttrRow[]>(`/api/notes/${noteId}/attributes`);
+ expect(attrs.body.find((a) => a.attributeId === attrId)?.value).toBe("new");
+ });
+
+ it("deletes a relation when its value is cleared", async () => {
+ const { noteId } = await createTextNote(api);
+ const created = await api.put<{ attributeId: string }>(`/api/notes/${noteId}/attribute`, {
+ body: { type: "relation", name: "clearable", value: "root" }
+ });
+
+ // same id/type/name, value emptied -> falls through to the markAsDeleted branch
+ const res = await api.put<{ attributeId: string }>(`/api/notes/${noteId}/attribute`, {
+ body: { attributeId: created.body.attributeId, type: "relation", name: "clearable", value: " " }
+ });
+ expect(res.status).toBe(200);
+
+ const attrs = await api.get<AttrRow[]>(`/api/notes/${noteId}/attributes`);
+ expect(attrs.body.some((a) => a.name === "clearable")).toBe(false);
+ });
+
+ it("400s when the attribute is not owned by the note", async () => {
+ const owner = await createTextNote(api, { title: "Attr owner" });
+ const other = await createTextNote(api, { title: "Attr other" });
+ const attrId = await addLabel(owner.noteId, "foreign", "v");
+
+ const res = await api.put(`/api/notes/${other.noteId}/attribute`, {
+ body: { attributeId: attrId, type: "label", name: "foreign", value: "v2" }
+ });
+ expect(res.status).toBe(400);
+ });
+ });
+
+ describe("updateNoteAttributes (bulk)", () => {
+ it("400s when the note does not exist", async () => {
+ const res = await api.put("/api/notes/missingNote123/attributes", { body: [] });
+ expect(res.status).toBe(400);
+ });
+
+ it("creates, repositions, updates, and deletes attributes to match the payload", async () => {
+ const { noteId } = await createTextNote(api);
+
+ // seed two labels
+ await api.put(`/api/notes/${noteId}/attributes`, {
+ body: [
+ { type: "label", name: "keep", value: "1", isInheritable: false },
+ { type: "label", name: "change", value: "old", isInheritable: false },
+ { type: "label", name: "drop", value: "x", isInheritable: false }
+ ]
+ });
+
+ // re-send: keep (perfect match, new position), change (value update), add new, drop removed
+ const res = await api.put(`/api/notes/${noteId}/attributes`, {
+ body: [
+ { type: "label", name: "added", value: "new", isInheritable: false },
+ { type: "label", name: "keep", value: "1", isInheritable: false },
+ { type: "label", name: "change", value: "updated", isInheritable: false }
+ ]
+ });
+ expect(res.status).toBe(204);
+
+ const attrs = await api.get<AttrRow[]>(`/api/notes/${noteId}/attributes`);
+ const byName = Object.fromEntries(attrs.body.map((a) => [ a.name, a.value ]));
+ expect(byName.keep).toBe("1");
+ expect(byName.change).toBe("updated");
+ expect(byName.added).toBe("new");
+ expect(attrs.body.some((a) => a.name === "drop")).toBe(false);
+ });
+
+ it("skips relations whose target note does not exist", async () => {
+ const { noteId } = await createTextNote(api);
+ const res = await api.put(`/api/notes/${noteId}/attributes`, {
+ body: [ { type: "relation", name: "ghost", value: "missingTarget123", isInheritable: false } ]
+ });
+ expect(res.status).toBe(204);
+
+ const attrs = await api.get<AttrRow[]>(`/api/notes/${noteId}/attributes`);
+ expect(attrs.body.some((a) => a.name === "ghost")).toBe(false);
+ });
});
});
diff --git a/packages/trilium-core/src/routes/api/attributes.ts b/packages/trilium-core/src/routes/api/attributes.ts
index aea732295b..4272271b4a 100644
--- a/packages/trilium-core/src/routes/api/attributes.ts
+++ b/packages/trilium-core/src/routes/api/attributes.ts
@@ -57,6 +57,7 @@ function updateNoteAttribute(req: Request<{ noteId: string }>) {
attribute.value = body.value;
} else {
// relations should never have empty target
+ /* v8 ignore next -- unreachable: BAttribute.validate() rejects relations with an empty/non-existing target, so an empty-valued relation can never be persisted and re-fetched here */
attribute.markAsDeleted();
}
@@ -75,6 +76,7 @@ function setNoteAttribute(req: Request) {
if (attributeId) {
const attr = becca.getAttribute(attributeId);
+ /* v8 ignore next 3 -- unreachable: the attributeId comes from a SQL query over non-deleted rows, which are always present in becca, so getAttribute cannot return null here */
if (!attr) {
throw new ValidationError(`Missing attribute with ID ${attributeId}.`);
}
diff --git a/packages/trilium-core/src/routes/api/autocomplete.spec.ts b/packages/trilium-core/src/routes/api/autocomplete.spec.ts
index f9f1a4779b..cc9b9e82dd 100644
--- a/packages/trilium-core/src/routes/api/autocomplete.spec.ts
+++ b/packages/trilium-core/src/routes/api/autocomplete.spec.ts
@@ -1,5 +1,6 @@
-import { beforeAll, describe, expect, it } from "vitest";
+import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
+import * as cls from "../../services/context";
import { createTextNote } from "../../test/api_fixtures";
import { CoreApiTester } from "../../test/api_tester";
@@ -23,6 +24,10 @@ describe("Autocomplete API (core)", () => {
});
describe("getAutocomplete", () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
it("returns matching notes for a search query", async () => {
const title = `Autocomplete target ${Date.now()}`;
await createTextNote(api, { title });
@@ -48,6 +53,31 @@ describe("Autocomplete API (core)", () => {
expect(Array.isArray(res.body)).toBe(true);
});
+ it("filters recent notes by the hoisted note path when not hoisted to root", async () => {
+ // Exercises the `hoistedNoteId !== "root"` branch (extra LIKE condition).
+ const { noteId } = await createTextNote(api, { title: "Hoisted recent" });
+ await api.post("/api/recent-notes", { body: { noteId, notePath: `root/${noteId}` } });
+ vi.spyOn(cls, "getHoistedNoteId").mockReturnValue(noteId);
+
+ const res = await api.get<AutocompleteResult[]>("/api/autocomplete", {
+ query: { query: "" }
+ });
+ expect(res.status).toBe(200);
+ expect(Array.isArray(res.body)).toBe(true);
+ });
+
+ it("logs a warning when the search is slow", async () => {
+ // Force the elapsed-time threshold so the slow-autocomplete log branch runs.
+ let calls = 0;
+ vi.spyOn(Date, "now").mockImplementation(() => (calls++ === 0 ? 0 : 1000));
+
+ const res = await api.get<AutocompleteResult[]>("/api/autocomplete", {
+ query: { query: "root" }
+ });
+ expect(res.status).toBe(200);
+ expect(Array.isArray(res.body)).toBe(true);
+ });
+
it("honours the fastSearch flag", async () => {
const res = await api.get<AutocompleteResult[]>("/api/autocomplete", {
query: { query: "root", fastSearch: "false" }
diff --git a/packages/trilium-core/src/routes/api/backend_log.spec.ts b/packages/trilium-core/src/routes/api/backend_log.spec.ts
index d7375cb9a1..bc9ec07066 100644
--- a/packages/trilium-core/src/routes/api/backend_log.spec.ts
+++ b/packages/trilium-core/src/routes/api/backend_log.spec.ts
@@ -1,5 +1,6 @@
-import { beforeAll, describe, expect, it } from "vitest";
+import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
+import { getLog } from "../../services/log";
import { CoreApiTester } from "../../test/api_tester";
/**
@@ -13,6 +14,10 @@ describe("Backend log API (core)", () => {
api = CoreApiTester.build();
});
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
it("returns the backend log contents as text", async () => {
const res = await api.get<string>("/api/backend-log");
expect(res.status).toBe(200);
@@ -20,4 +25,25 @@ describe("Backend log API (core)", () => {
// message when no log file is available); never assert on the exact text.
expect(typeof res.body).toBe("string");
});
+
+ it("returns the log contents verbatim when a log file is available", async () => {
+ // On the standalone (WASM) runtime getLogContents() can be null by
+ // default, so force a non-null value to exercise the success branch.
+ vi.spyOn(getLog(), "getLogContents").mockReturnValue("line one\nline two");
+
+ const res = await api.get<string>("/api/backend-log");
+ expect(res.status).toBe(200);
+ expect(res.body).toBe("line one\nline two");
+ });
+
+ it("returns a fallback message when no log file is available", async () => {
+ // Force the `contents === null` branch (the i18n fallback). The fallback
+ // text is translated, so assert only on structure, not the English string.
+ vi.spyOn(getLog(), "getLogContents").mockReturnValue(null);
+
+ const res = await api.get<string>("/api/backend-log");
+ expect(res.status).toBe(200);
+ expect(typeof res.body).toBe("string");
+ expect(res.body.length).toBeGreaterThan(0);
+ });
});
diff --git a/packages/trilium-core/src/routes/api/backup.spec.ts b/packages/trilium-core/src/routes/api/backup.spec.ts
new file mode 100644
index 0000000000..e202582d73
--- /dev/null
+++ b/packages/trilium-core/src/routes/api/backup.spec.ts
@@ -0,0 +1,61 @@
+import { beforeAll, describe, expect, it } from "vitest";
+
+import { CoreApiTester } from "../../test/api_tester";
+
+/**
+ * Drives the shared core backup routes through {@link CoreApiTester} (no
+ * Express) against the REAL backup service — fs-backed on node, OPFS-backed on
+ * standalone. No service mocks. Runs under both suites.
+ *
+ * The download *success* path is node-only: the standalone test runtime
+ * (happy-dom) has no OPFS, so `StandaloneBackupService` gracefully no-ops and
+ * `getBackupContent` always returns `null` there. That single path is covered
+ * by the node suite; everything else is asserted cross-runtime.
+ */
+const isBrowserRuntime = typeof window !== "undefined";
+let api: CoreApiTester;
+
+describe("Backup API (core)", () => {
+ beforeAll(() => {
+ api = CoreApiTester.build();
+ });
+
+ it("lists existing backups as an array", async () => {
+ const res = await api.get(`/api/database/backups`);
+ expect(res.status).toBe(200);
+ expect(Array.isArray(res.body)).toBe(true);
+ });
+
+ it("creates a backup and returns the resulting file path", async () => {
+ const res = await api.post<{ backupFile: string }>(`/api/database/backup-database`);
+ expect(res.status).toBe(200);
+ expect(typeof res.body.backupFile).toBe("string");
+ expect(res.body.backupFile).toBeTruthy();
+ });
+
+ describe("downloadBackup", () => {
+ it("returns 400 when the filePath query is missing", async () => {
+ const res = await api.get<string>(`/api/database/backup/download`);
+ expect(res.status).toBe(400);
+ });
+
+ it("returns 404 when the backup does not exist", async () => {
+ const res = await api.get<string>(`/api/database/backup/download`, {
+ query: { filePath: "/backups/does-not-exist.db" }
+ });
+ expect(res.status).toBe(404);
+ });
+
+ it.skipIf(isBrowserRuntime)("streams a real backup with download headers (node)", async () => {
+ // Create a real backup, then download it by its actual path.
+ const created = await api.post<{ backupFile: string }>(`/api/database/backup-database`);
+ const filePath = created.body.backupFile;
+
+ const res = await api.get(`/api/database/backup/download`, { query: { filePath } });
+ expect(res.status).toBe(200);
+ expect(res.headers["Content-Type"]).toBe("application/x-sqlite3");
+ expect(res.headers["Content-Disposition"]).toContain("attachment; filename=");
+ expect(Buffer.isBuffer(res.body) || typeof res.body === "string").toBe(true);
+ });
+ });
+});
diff --git a/packages/trilium-core/src/routes/api/branches.spec.ts b/packages/trilium-core/src/routes/api/branches.spec.ts
index 033de47374..0bec4c8e04 100644
--- a/packages/trilium-core/src/routes/api/branches.spec.ts
+++ b/packages/trilium-core/src/routes/api/branches.spec.ts
@@ -84,6 +84,60 @@ describe("Branches API (core)", () => {
);
expect(res.status).toBe(404);
});
+
+ it("moves a branch before a sibling under a different parent (clone path)", async () => {
+ const parentA = await createTextNote(api, { title: "Cross before A" });
+ const parentB = await createTextNote(api, { title: "Cross before B" });
+ const moving = await createTextNote(api, { parentNoteId: parentA.noteId, title: "Crosser" });
+ const target = await createTextNote(api, { parentNoteId: parentB.noteId, title: "Before target" });
+
+ const res = await api.put<{ success: boolean }>(
+ `/api/branches/${moving.branchId}/move-before/${target.branchId}`
+ );
+ expect(res.status).toBe(200);
+ expect(res.body.success).toBe(true);
+ // original branch under parentA is replaced by a clone under parentB
+ expect(getBranchRow(moving.branchId)?.isDeleted).toBe(1);
+ });
+
+ it("moves a branch after a sibling under a different parent (clone path)", async () => {
+ const parentA = await createTextNote(api, { title: "Cross after A" });
+ const parentB = await createTextNote(api, { title: "Cross after B" });
+ const moving = await createTextNote(api, { parentNoteId: parentA.noteId, title: "Crosser after" });
+ const first = await createTextNote(api, { parentNoteId: parentB.noteId, title: "After first" });
+ // a second sibling after the target so the position-shift loop body runs
+ await createTextNote(api, { parentNoteId: parentB.noteId, title: "After second" });
+
+ const res = await api.put<{ success: boolean }>(
+ `/api/branches/${moving.branchId}/move-after/${first.branchId}`
+ );
+ expect(res.status).toBe(200);
+ expect(res.body.success).toBe(true);
+ expect(getBranchRow(moving.branchId)?.isDeleted).toBe(1);
+ });
+
+ it("returns a 200 validation failure when the move would create a cycle (before)", async () => {
+ const parent = await createTextNote(api, { title: "Cycle before parent" });
+ const child = await createTextNote(api, { parentNoteId: parent.noteId, title: "Cycle before child" });
+
+ // moving the parent's branch before its own descendant would create a cycle
+ const res = await api.put<{ success: boolean; message: string }>(
+ `/api/branches/${parent.branchId}/move-before/${child.branchId}`
+ );
+ expect(res.status).toBe(200);
+ expect(res.body.success).toBe(false);
+ });
+
+ it("returns a 200 validation failure when the move would create a cycle (after)", async () => {
+ const parent = await createTextNote(api, { title: "Cycle after parent" });
+ const child = await createTextNote(api, { parentNoteId: parent.noteId, title: "Cycle after child" });
+
+ const res = await api.put<{ success: boolean; message: string }>(
+ `/api/branches/${parent.branchId}/move-after/${child.branchId}`
+ );
+ expect(res.status).toBe(200);
+ expect(res.body.success).toBe(false);
+ });
});
describe("expanding", () => {
@@ -196,5 +250,19 @@ describe("Branches API (core)", () => {
});
expect(res.status).toBe(404);
});
+
+ it("erases the note immediately when eraseNotes is set", async () => {
+ const { noteId, branchId } = await createTextNote(api, { title: "To erase" });
+
+ const res = await api.delete<{ noteDeleted: boolean }>(`/api/branches/${branchId}`, {
+ query: { taskId: "test-branch-erase", last: "true", eraseNotes: "true" }
+ });
+ expect(res.status).toBe(200);
+ expect(res.body.noteDeleted).toBe(true);
+
+ // erasing removes the note row entirely
+ const noteRow = getSql().getRowOrNull("SELECT noteId FROM notes WHERE noteId = ?", [ noteId ]);
+ expect(noteRow).toBeNull();
+ });
});
});
diff --git a/packages/trilium-core/src/routes/api/export.spec.ts b/packages/trilium-core/src/routes/api/export.spec.ts
new file mode 100644
index 0000000000..ede3eeb10c
--- /dev/null
+++ b/packages/trilium-core/src/routes/api/export.spec.ts
@@ -0,0 +1,74 @@
+import { beforeAll, describe, expect, it } from "vitest";
+
+import { createTextNote } from "../../test/api_fixtures";
+import { CoreApiTester } from "../../test/api_tester";
+
+/**
+ * Drives the shared core export route through {@link CoreApiTester} (no Express)
+ * end to end — the REAL zip/single/opml export services run, writing to the
+ * tester's stream-backed mock response. Runs under both the node (archiver) and
+ * standalone (fflate) suites, exercising each runtime's real zip provider.
+ */
+let api: CoreApiTester;
+let branchId: string;
+
+function exportPath(type: string, format: string, version = "1.0", taskId = "exportTask") {
+ return `/api/branches/${branchId}/export/${type}/${format}/${version}/${taskId}`;
+}
+
+/** A real zip always begins with the "PK" local-file-header signature. */
+function isZip(body: unknown): boolean {
+ return Buffer.isBuffer(body) && body.length > 2 && body.subarray(0, 2).toString("latin1") === "PK";
+}
+
+describe("Export API (core)", () => {
+ beforeAll(async () => {
+ api = CoreApiTester.build();
+ ({ branchId } = await createTextNote(api, { title: "Export me", content: "<p>hello world</p>" }));
+ });
+
+ it("returns 500 when the branch does not exist", async () => {
+ const res = await api.get<string>(exportPath("subtree", "html").replace(branchId, "missingBranch123"));
+ expect(res.status).toBe(500);
+ expect(res.headers["Content-Type"]).toBe("text/plain");
+ });
+
+ it.each([ "html", "markdown" ])("exports a subtree as a real %s zip", async (format) => {
+ const res = await api.get(exportPath("subtree", format));
+ expect(res.status).toBe(200);
+ expect(res.headers["Content-Type"]).toBe("application/zip");
+ expect(isZip(res.body)).toBe(true);
+ });
+
+ it("exports a single note as markdown with the real content", async () => {
+ const res = await api.get<string>(exportPath("single", "markdown"));
+ expect(res.status).toBe(200);
+ expect(res.headers["Content-Type"]).toContain("markdown");
+ expect(String(res.body)).toContain("hello world");
+ });
+
+ it("exports a single note as html with the real content", async () => {
+ const res = await api.get<string>(exportPath("single", "html"));
+ expect(res.status).toBe(200);
+ expect(String(res.body)).toContain("hello world");
+ });
+
+ it("returns 500 for an invalid single-export format (ValidationError caught)", async () => {
+ const res = await api.get<string>(exportPath("single", "pdf"));
+ expect(res.status).toBe(500);
+ expect(res.headers["Content-Type"]).toBe("text/plain");
+ });
+
+ it("exports as real opml", async () => {
+ const res = await api.get(exportPath("subtree", "opml", "2.0"));
+ expect(res.status).toBe(200);
+ expect(res.headers["Content-Type"]).toBe("text/x-opml");
+ expect(res.body?.toString()).toContain("outline");
+ });
+
+ it("returns 500 for an unrecognized format (NotFoundError caught)", async () => {
+ const res = await api.get<string>(exportPath("tree", "bogus"));
+ expect(res.status).toBe(500);
+ expect(res.headers["Content-Type"]).toBe("text/plain");
+ });
+});
diff --git a/packages/trilium-core/src/routes/api/image.spec.ts b/packages/trilium-core/src/routes/api/image.spec.ts
index 269cd09b94..20755adb1b 100644
--- a/packages/trilium-core/src/routes/api/image.spec.ts
+++ b/packages/trilium-core/src/routes/api/image.spec.ts
@@ -1,8 +1,35 @@
-import { describe, expect, it } from "vitest";
+import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
+
+import becca from "../../becca/becca.js";
+import imageService from "../../services/image.js";
import { note } from "../../test/becca_mocking.js";
+import { createTextNote } from "../../test/api_fixtures.js";
+import { CoreApiTester } from "../../test/api_tester.js";
import { renderSvgAttachment } from "./image.js";
+let api: CoreApiTester;
+
+/** Builds a fake image-like entity (note or revision) for the becca stubs. */
+function fakeImage(overrides: Record<string, unknown>) {
+ return {
+ type: "image",
+ mime: "image/png",
+ getContent: () => Buffer.from([1, 2, 3]),
+ getAttachmentByTitle: () => null,
+ getJsonContentSafely: () => null,
+ ...overrides
+ };
+}
+
describe("Image API", () => {
+ beforeAll(() => {
+ api = CoreApiTester.build();
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
it("renders empty SVG properly", () => {
const parentNote = note("note").note;
const response = new MockResponse();
@@ -10,6 +37,228 @@ describe("Image API", () => {
expect(response.headers["Content-Type"]).toBe("image/svg+xml");
expect(response.body).toBe(`<svg xmlns="http://www.w3.org/2000/svg"></svg>`);
});
+
+ describe("renderSvgAttachment", () => {
+ it("renders the SVG stored in an attachment", () => {
+ const response = new MockResponse();
+ const img = fakeImage({
+ getAttachmentByTitle: () => ({ getContent: () => "<svg><rect/></svg>" })
+ });
+ renderSvgAttachment(img as any, response as any, "canvas-export.svg");
+ expect(response.headers["Content-Type"]).toBe("image/svg+xml");
+ expect(response.body).toContain("<svg");
+ });
+
+ it("falls back to the legacy svg key in the note content", () => {
+ const response = new MockResponse();
+ const img = fakeImage({
+ getJsonContentSafely: () => ({ svg: "<svg id='legacy'></svg>" })
+ });
+ renderSvgAttachment(img as any, response as any, "mermaid-export.svg");
+ expect(response.body).toContain("legacy");
+ });
+ });
+
+ describe("returnImageFromNote (GET /api/images/:noteId/:filename)", () => {
+ it("404s when the note does not exist", async () => {
+ vi.spyOn(becca, "getNote").mockReturnValue(null);
+ const res = await api.get("/api/images/missing/file.png");
+ expect(res.status).toBe(404);
+ });
+
+ it("400s when the note is not an image type", async () => {
+ vi.spyOn(becca, "getNote").mockReturnValue(fakeImage({ type: "text" }) as any);
+ const res = await api.get("/api/images/someNote/file.png");
+ expect(res.status).toBe(400);
+ });
+
+ it("serves a regular raster image", async () => {
+ vi.spyOn(becca, "getNote").mockReturnValue(
+ fakeImage({ type: "image", mime: "image/png" }) as any
+ );
+ const res = await api.get("/api/images/someNote/file.png");
+ expect(res.status).toBe(200);
+ expect(res.headers["Content-Type"]).toBe("image/png");
+ expect(res.headers["Cache-Control"]).toContain("no-cache");
+ });
+
+ it("sanitizes an SVG image note", async () => {
+ vi.spyOn(becca, "getNote").mockReturnValue(
+ fakeImage({
+ type: "image",
+ mime: "image/svg+xml",
+ getContent: () => "<svg><script>alert(1)</script></svg>"
+ }) as any
+ );
+ const res = await api.get<string>("/api/images/someNote/file.svg");
+ expect(res.status).toBe(200);
+ expect(res.headers["Content-Type"]).toBe("image/svg+xml");
+ expect(res.headers["Content-Security-Policy"]).toBe("script-src 'none'");
+ expect(res.body).not.toContain("alert(1)");
+ });
+
+ it("renders a canvas note as an SVG attachment", async () => {
+ vi.spyOn(becca, "getNote").mockReturnValue(
+ fakeImage({
+ type: "canvas",
+ getAttachmentByTitle: () => ({ getContent: () => "<svg id='canvas'></svg>" })
+ }) as any
+ );
+ const res = await api.get<string>("/api/images/someNote/file.svg");
+ expect(res.status).toBe(200);
+ expect(res.headers["Content-Type"]).toBe("image/svg+xml");
+ expect(res.body).toContain("canvas");
+ });
+
+ it("renders a mermaid note as an SVG attachment", async () => {
+ vi.spyOn(becca, "getNote").mockReturnValue(fakeImage({ type: "mermaid" }) as any);
+ const res = await api.get<string>("/api/images/someNote/file.svg");
+ expect(res.status).toBe(200);
+ expect(res.headers["Content-Type"]).toBe("image/svg+xml");
+ });
+
+ it("renders a mindMap note as an SVG attachment", async () => {
+ vi.spyOn(becca, "getNote").mockReturnValue(fakeImage({ type: "mindMap" }) as any);
+ const res = await api.get<string>("/api/images/someNote/file.svg");
+ expect(res.status).toBe(200);
+ expect(res.headers["Content-Type"]).toBe("image/svg+xml");
+ });
+
+ it("renders a spreadsheet note as a PNG attachment", async () => {
+ vi.spyOn(becca, "getNote").mockReturnValue(
+ fakeImage({
+ type: "spreadsheet",
+ getAttachmentByTitle: () => ({ getContent: () => Buffer.from([4, 5, 6]) })
+ }) as any
+ );
+ const res = await api.get("/api/images/someNote/file.png");
+ expect(res.status).toBe(200);
+ expect(res.headers["Content-Type"]).toBe("image/png");
+ });
+
+ it("404s rendering a spreadsheet note without the PNG attachment", async () => {
+ vi.spyOn(becca, "getNote").mockReturnValue(
+ fakeImage({ type: "spreadsheet", getAttachmentByTitle: () => null }) as any
+ );
+ const res = await api.get("/api/images/someNote/file.png");
+ expect(res.status).toBe(404);
+ });
+ });
+
+ describe("returnImageFromRevision (GET /api/revisions/:revisionId/image/:filename)", () => {
+ it("serves a raster image from a revision", async () => {
+ vi.spyOn(becca, "getRevision").mockReturnValue(
+ fakeImage({ type: "image", mime: "image/jpeg" }) as any
+ );
+ const res = await api.get("/api/revisions/rev123/image/file.jpg");
+ expect(res.status).toBe(200);
+ expect(res.headers["Content-Type"]).toBe("image/jpeg");
+ });
+ });
+
+ describe("returnAttachedImage (GET /api/attachments/:attachmentId/image/:filename)", () => {
+ function fakeAttachment(overrides: Record<string, unknown>) {
+ return {
+ attachmentId: "att1",
+ role: "image",
+ mime: "image/png",
+ getContent: () => Buffer.from([7, 8, 9]),
+ ...overrides
+ };
+ }
+
+ it("404s when the attachment does not exist", async () => {
+ vi.spyOn(becca, "getAttachment").mockReturnValue(null);
+ const res = await api.get("/api/attachments/missing/image/file.png");
+ expect(res.status).toBe(404);
+ });
+
+ it("400s when the attachment role is not image", async () => {
+ vi.spyOn(becca, "getAttachment").mockReturnValue(fakeAttachment({ role: "file" }) as any);
+ const res = await api.get("/api/attachments/att1/image/file.png");
+ expect(res.status).toBe(400);
+ });
+
+ it("serves a raster attachment image", async () => {
+ vi.spyOn(becca, "getAttachment").mockReturnValue(
+ fakeAttachment({ role: "image", mime: "image/png" }) as any
+ );
+ const res = await api.get("/api/attachments/att1/image/file.png");
+ expect(res.status).toBe(200);
+ expect(res.headers["Content-Type"]).toBe("image/png");
+ });
+
+ it("sanitizes an SVG attachment image", async () => {
+ vi.spyOn(becca, "getAttachment").mockReturnValue(
+ fakeAttachment({
+ role: "image",
+ mime: "image/svg+xml",
+ getContent: () => "<svg><script>alert(2)</script></svg>"
+ }) as any
+ );
+ const res = await api.get<string>("/api/attachments/att1/image/file.svg");
+ expect(res.status).toBe(200);
+ expect(res.headers["Content-Type"]).toBe("image/svg+xml");
+ expect(res.body).not.toContain("alert(2)");
+ });
+ });
+
+ describe("updateImage (PUT /api/images/:noteId)", () => {
+ it("reports a missing file", async () => {
+ const { noteId } = await createTextNote(api);
+ const res = await api.put<{ uploaded: boolean; message: string }>(
+ `/api/images/${noteId}`
+ );
+ expect(res.status).toBe(200);
+ expect(res.body.uploaded).toBe(false);
+ expect(res.body.message).toContain("Missing image data");
+ });
+
+ it("rejects an unknown mime type", async () => {
+ const { noteId } = await createTextNote(api);
+ const res = await api.put<{ uploaded: boolean }>(`/api/images/${noteId}`, {
+ file: {
+ originalname: "x.txt",
+ mimetype: "text/plain",
+ buffer: Buffer.from([1]),
+ size: 1
+ }
+ });
+ expect(res.status).toBe(200);
+ expect(res.body.uploaded).toBe(false);
+ });
+
+ it("rejects a file whose buffer is a string", async () => {
+ const { noteId } = await createTextNote(api);
+ const res = await api.put<{ uploaded: boolean }>(`/api/images/${noteId}`, {
+ file: {
+ originalname: "x.png",
+ mimetype: "image/png",
+ buffer: "not-a-buffer",
+ size: 1
+ }
+ });
+ expect(res.status).toBe(200);
+ expect(res.body.uploaded).toBe(false);
+ });
+
+ it("updates the image on success", async () => {
+ const { noteId } = await createTextNote(api);
+ const spy = vi.spyOn(imageService, "updateImage").mockReturnValue(undefined as any);
+
+ const res = await api.put<{ uploaded: boolean }>(`/api/images/${noteId}`, {
+ file: {
+ originalname: "x.png",
+ mimetype: "image/png",
+ buffer: Buffer.from([1, 2, 3]),
+ size: 3
+ }
+ });
+ expect(res.status).toBe(200);
+ expect(res.body.uploaded).toBe(true);
+ expect(spy).toHaveBeenCalledOnce();
+ });
+ });
});
class MockResponse {
diff --git a/packages/trilium-core/src/routes/api/import.spec.ts b/packages/trilium-core/src/routes/api/import.spec.ts
new file mode 100644
index 0000000000..b8ed217047
--- /dev/null
+++ b/packages/trilium-core/src/routes/api/import.spec.ts
@@ -0,0 +1,217 @@
+import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
+
+import becca from "../../becca/becca";
+import becca_loader from "../../becca/becca_loader";
+import enexImportService from "../../services/import/enex";
+import opmlImportService from "../../services/import/opml";
+import singleImportService from "../../services/import/single";
+import zipImportService from "../../services/import/zip";
+import TaskContext from "../../services/task_context";
+import { createTextNote } from "../../test/api_fixtures";
+import { CoreApiTester } from "../../test/api_tester";
+
+/**
+ * Drives the shared core import routes through {@link CoreApiTester} (no
+ * Express). The heavy import services are stubbed with `vi.spyOn` so we only
+ * exercise the route's branching (extension dispatch, error handling, the
+ * `last === "true"` timer). Runs under both the node and standalone suites.
+ */
+let api: CoreApiTester;
+let parentNoteId: string;
+
+function fakeNote(noteId = "fakeNote123") {
+ return { noteId, getPojo: () => ({ noteId, title: "fake" }) } as any;
+}
+
+function file(originalname: string, buffer: any = Buffer.from("hi")) {
+ return { originalname, mimetype: "text/plain", buffer, size: 2 };
+}
+
+describe("Import API (core)", () => {
+ beforeAll(async () => {
+ api = CoreApiTester.build();
+ ({ noteId: parentNoteId } = await createTextNote(api));
+ // becca_loader.load() is invoked by the route on success; no-op it so the
+ // stubbed-out import doesn't trigger a real cache reload.
+ vi.spyOn(becca_loader, "load").mockReturnValue(undefined as any);
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ vi.useRealTimers();
+ // restore the load() stub that restoreAllMocks just cleared
+ vi.spyOn(becca_loader, "load").mockReturnValue(undefined as any);
+ });
+
+ describe("importNotesToBranch", () => {
+ it("rejects when no file is uploaded", async () => {
+ const res = await api.post(`/api/notes/${parentNoteId}/notes-import`, { body: {} });
+ expect(res.status).toBe(400);
+ });
+
+ it("imports a single (default extension) file and returns the note pojo", async () => {
+ const spy = vi.spyOn(singleImportService, "importSingleFile").mockReturnValue(fakeNote());
+
+ const res = await api.post(`/api/notes/${parentNoteId}/notes-import`, {
+ body: {},
+ file: file("x.txt")
+ });
+
+ expect(res.status).toBe(200);
+ expect(res.body).toMatchObject({ noteId: "fakeNote123" });
+ expect(spy).toHaveBeenCalled();
+ });
+
+ it("dispatches .zip archives to the zip importer", async () => {
+ const spy = vi.spyOn(zipImportService, "importZip").mockResolvedValue(fakeNote("zipNote"));
+
+ const res = await api.post(`/api/notes/${parentNoteId}/notes-import`, {
+ body: {},
+ file: file("x.zip")
+ });
+
+ expect(res.status).toBe(200);
+ expect(spy).toHaveBeenCalled();
+ });
+
+ it("dispatches .opml archives to the opml importer (note result)", async () => {
+ vi.spyOn(opmlImportService, "importOpml").mockResolvedValue(fakeNote("opmlNote"));
+
+ const res = await api.post(`/api/notes/${parentNoteId}/notes-import`, {
+ body: {},
+ file: file("x.opml")
+ });
+
+ expect(res.status).toBe(200);
+ expect(res.body).toMatchObject({ noteId: "opmlNote" });
+ });
+
+ it("returns the array result early for .opml importers that return an array", async () => {
+ vi.spyOn(opmlImportService, "importOpml").mockResolvedValue([{ a: 1 }] as any);
+
+ const res = await api.post(`/api/notes/${parentNoteId}/notes-import`, {
+ body: {},
+ file: file("x.opml")
+ });
+
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual([{ a: 1 }]);
+ });
+
+ it("dispatches .enex archives to the enex importer (note result)", async () => {
+ vi.spyOn(enexImportService, "importEnex").mockResolvedValue(fakeNote("enexNote"));
+
+ const res = await api.post(`/api/notes/${parentNoteId}/notes-import`, {
+ body: {},
+ file: file("x.enex")
+ });
+
+ expect(res.status).toBe(200);
+ expect(res.body).toMatchObject({ noteId: "enexNote" });
+ });
+
+ it("returns the array result early for .enex importers that return an array", async () => {
+ vi.spyOn(enexImportService, "importEnex").mockResolvedValue([{ b: 2 }] as any);
+
+ const res = await api.post(`/api/notes/${parentNoteId}/notes-import`, {
+ body: {},
+ file: file("x.enex")
+ });
+
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual([{ b: 2 }]);
+ });
+
+ it("returns 500 when the importer throws", async () => {
+ vi.spyOn(singleImportService, "importSingleFile").mockImplementation(() => {
+ throw new Error("boom");
+ });
+
+ const res = await api.post(`/api/notes/${parentNoteId}/notes-import`, {
+ body: {},
+ file: file("x.txt")
+ });
+
+ expect(res.status).toBe(500);
+ });
+
+ it("returns 500 when no note is generated", async () => {
+ vi.spyOn(singleImportService, "importSingleFile").mockReturnValue(null as any);
+
+ const res = await api.post(`/api/notes/${parentNoteId}/notes-import`, {
+ body: {},
+ file: file("x.txt")
+ });
+
+ expect(res.status).toBe(500);
+ });
+
+ it("schedules taskSucceeded when last === 'true'", async () => {
+ vi.useFakeTimers();
+ vi.spyOn(singleImportService, "importSingleFile").mockReturnValue(fakeNote());
+ const succeeded = vi.spyOn(TaskContext.prototype, "taskSucceeded").mockReturnValue(undefined as any);
+
+ const res = await api.post(`/api/notes/${parentNoteId}/notes-import`, {
+ body: { last: "true" },
+ file: file("x.txt")
+ });
+
+ expect(res.status).toBe(200);
+ vi.runAllTimers();
+ expect(succeeded).toHaveBeenCalledWith(
+ expect.objectContaining({ parentNoteId, importedNoteId: "fakeNote123" })
+ );
+ });
+ });
+
+ describe("importAttachmentsToNote", () => {
+ it("rejects when no file is uploaded", async () => {
+ const res = await api.post(`/api/notes/${parentNoteId}/attachments-import`, { body: {} });
+ expect(res.status).toBe(400);
+ });
+
+ it("imports an attachment", async () => {
+ const spy = vi.spyOn(singleImportService, "importAttachment").mockReturnValue(undefined as any);
+
+ const res = await api.post(`/api/notes/${parentNoteId}/attachments-import`, {
+ body: {},
+ file: file("x.txt")
+ });
+
+ expect(res.status).toBe(204);
+ expect(spy).toHaveBeenCalled();
+ });
+
+ it("returns 500 when the attachment importer throws", async () => {
+ vi.spyOn(singleImportService, "importAttachment").mockImplementation(() => {
+ throw new Error("boom");
+ });
+
+ const res = await api.post(`/api/notes/${parentNoteId}/attachments-import`, {
+ body: {},
+ file: file("x.txt")
+ });
+
+ expect(res.status).toBe(500);
+ });
+
+ it("schedules taskSucceeded when last === 'true'", async () => {
+ vi.useFakeTimers();
+ vi.spyOn(singleImportService, "importAttachment").mockReturnValue(undefined as any);
+ const succeeded = vi.spyOn(TaskContext.prototype, "taskSucceeded").mockReturnValue(undefined as any);
+
+ const res = await api.post(`/api/notes/${parentNoteId}/attachments-import`, {
+ body: { last: "true" },
+ file: file("x.txt")
+ });
+
+ expect(res.status).toBe(204);
+ vi.runAllTimers();
+ expect(succeeded).toHaveBeenCalledWith(expect.objectContaining({ parentNoteId }));
+ });
+ });
+
+ it("becca lookup of the parent is exercised via a real fixture note", () => {
+ expect(becca.getNote(parentNoteId)).toBeTruthy();
+ });
+});
diff --git a/packages/trilium-core/src/routes/api/login.spec.ts b/packages/trilium-core/src/routes/api/login.spec.ts
new file mode 100644
index 0000000000..a0089131f9
--- /dev/null
+++ b/packages/trilium-core/src/routes/api/login.spec.ts
@@ -0,0 +1,75 @@
+import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
+
+import passwordEncryptionService from "../../services/encryption/password_encryption";
+import protectedSession from "../../services/protected_session";
+import ws from "../../services/ws";
+import { CoreApiTester } from "../../test/api_tester";
+
+/**
+ * Drives the shared core protected-session login routes through
+ * {@link CoreApiTester} (no Express), so this spec runs under both the node and
+ * standalone (WASM) suites.
+ */
+let api: CoreApiTester;
+
+describe("Login (protected session) API (core)", () => {
+ beforeAll(() => {
+ api = CoreApiTester.build();
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ protectedSession.resetDataKey();
+ });
+
+ it("rejects a wrong protected-session password", async () => {
+ const res = await api.post<{ success: boolean }>("/api/login/protected", {
+ body: { password: "wrongpassword" }
+ });
+ expect(res.status).toBe(200);
+ expect(res.body.success).toBe(false);
+ expect(protectedSession.isProtectedSessionAvailable()).toBe(false);
+ });
+
+ it("returns the 'unable to obtain data key' failure when the data key cannot be decrypted", async () => {
+ vi.spyOn(passwordEncryptionService, "getDataKey").mockResolvedValue(null);
+ const res = await api.post<{ success: boolean }>("/api/login/protected", {
+ body: { password: "demo1234" }
+ });
+ expect(res.status).toBe(200);
+ expect(res.body.success).toBe(false);
+ expect(protectedSession.isProtectedSessionAvailable()).toBe(false);
+ });
+
+ it("logs in to the protected session with the correct password", async () => {
+ const sendMessage = vi.spyOn(ws, "sendMessageToAllClients").mockImplementation(() => {});
+ const res = await api.post<{ success: boolean }>("/api/login/protected", {
+ body: { password: "demo1234" }
+ });
+ expect(res.status).toBe(200);
+ expect(res.body.success).toBe(true);
+ expect(protectedSession.isProtectedSessionAvailable()).toBe(true);
+ expect(sendMessage).toHaveBeenCalledWith({ type: "protectedSessionLogin" });
+ });
+
+ it("touches the protected session", async () => {
+ // establish a session first
+ vi.spyOn(ws, "sendMessageToAllClients").mockImplementation(() => {});
+ await api.post("/api/login/protected", { body: { password: "demo1234" } });
+
+ const res = await api.post("/api/login/protected/touch");
+ expect(res.status).toBe(204);
+ expect(protectedSession.getLastProtectedSessionOperationDate()).toBeTruthy();
+ });
+
+ it("logs out from the protected session", async () => {
+ const sendMessage = vi.spyOn(ws, "sendMessageToAllClients").mockImplementation(() => {});
+ await api.post("/api/login/protected", { body: { password: "demo1234" } });
+ expect(protectedSession.isProtectedSessionAvailable()).toBe(true);
+
+ const res = await api.post("/api/logout/protected");
+ expect(res.status).toBe(204);
+ expect(protectedSession.isProtectedSessionAvailable()).toBe(false);
+ expect(sendMessage).toHaveBeenCalledWith({ type: "protectedSessionLogout" });
+ });
+});
diff --git a/packages/trilium-core/src/routes/api/note_map.spec.ts b/packages/trilium-core/src/routes/api/note_map.spec.ts
index 6d37ce269a..8f2c15b715 100644
--- a/packages/trilium-core/src/routes/api/note_map.spec.ts
+++ b/packages/trilium-core/src/routes/api/note_map.spec.ts
@@ -1,9 +1,24 @@
import { trimIndentation } from "@triliumnext/commons";
-import { describe, expect, it } from "vitest";
+import { beforeAll, describe, expect, it, vi } from "vitest";
+import becca from "../../becca/becca";
+import { createTextNote } from "../../test/api_fixtures";
+import { CoreApiTester } from "../../test/api_tester";
import { buildNote, buildNotes } from "../../test/becca_easy_mocking";
import note_map from "./note_map";
+interface LinkMapResponse {
+ notes: [string, string, string, string | null][];
+ noteIdToDescendantCountMap: Record<string, number>;
+ links: { id: string; sourceNoteId: string; targetNoteId: string; name: string }[];
+}
+
+interface TreeMapResponse {
+ notes: [string, string, string, string | null][];
+ noteIdToDescendantCountMap: Record<string, number>;
+ links: { sourceNoteId: string; targetNoteId: string }[];
+}
+
describe("Note map service", () => {
it("correctly identifies backlinks", () => {
const note = buildNote({ id: "dUtgloZIckax", title: "Backlink text" });
@@ -99,3 +114,322 @@ describe("Note map service", () => {
]);
});
});
+
+function req(noteId: string, body: Record<string, unknown> = {}) {
+ return { params: { noteId }, body } as any;
+}
+
+describe("Note map service (branch coverage)", () => {
+ it("backlink-count counts non-search source relations only", () => {
+ const target = buildNote({ id: "bcTarget", title: "BC Target" });
+ // text source -> counted
+ buildNote({ id: "bcSourceText", title: "Source", type: "text", "~internalLink": "bcTarget" });
+ // search source -> filtered out by getFilteredBacklinks
+ buildNote({ id: "bcSourceSearch", title: "Search src", type: "search", "~ancestor": "bcTarget" });
+
+ const res = note_map.getBacklinkCount(req(target.noteId));
+ expect(res).toEqual({ count: 1 });
+ });
+
+ it("backlinks: non-text source yields no excerpts; excerpt cap drops to plain entries", () => {
+ const target = buildNote({ id: "blTarget2", title: "Target2" });
+
+ // non-text source (code) -> early return without excerpts
+ buildNote({ id: "blCodeSrc", title: "Code", type: "code", "~internalLink": "blTarget2", content: "ignored" });
+
+ const res = note_map.getBacklinks(req(target.noteId));
+ const codeEntry = res.find((b) => b.noteId === "blCodeSrc");
+ expect(codeEntry).toEqual({ noteId: "blCodeSrc", relationName: "internalLink" });
+ });
+
+ it("backlinks: text source over the excerpt cap returns relationName only", () => {
+ const target = buildNote({ id: "capTarget", title: "Cap target" });
+ const sources: Parameters<typeof buildNotes>[0] = [];
+ for (let i = 0; i < 55; i++) {
+ sources.push({
+ id: `capSrc${i}`,
+ title: `S${i}`,
+ type: "text" as const,
+ "~internalLink": "capTarget",
+ content: `<p><a href="#root/capTarget">x</a></p>`
+ });
+ }
+ buildNotes(sources);
+
+ const res = note_map.getBacklinks(req(target.noteId));
+ // beyond 50 excerpt computations, entries fall back to { noteId, relationName }
+ const overCap = res.filter((b: any) => "relationName" in b);
+ expect(overCap.length).toBeGreaterThan(0);
+ });
+
+ it("getTreeMap: filters excludeFromNoteMap notes and embedded image children", () => {
+ // The map root has a text child that embeds an image (imageLink + parent of the image).
+ // The image note is filtered out of the tree because it's an image with no children,
+ // it has an incoming imageLink relation, and its imageLink source is also its parent.
+ const mapRoot = buildNote({
+ id: "treeRoot",
+ title: "Tree root",
+ children: [
+ { id: "treeKeep", title: "Keep" },
+ { id: "treeExcluded", title: "Excluded", "#excludeFromNoteMap": "true" },
+ {
+ id: "treeImgParent",
+ title: "Img parent",
+ type: "text",
+ "~imageLink": "treeImg",
+ children: [ { id: "treeImg", title: "Embedded img", type: "image" } ]
+ }
+ ]
+ });
+
+ const res = note_map.getTreeMap(req(mapRoot.noteId)) as TreeMapResponse;
+ const ids = res.notes.map((n) => n[0]);
+ expect(ids).toContain("treeKeep");
+ expect(ids).not.toContain("treeExcluded");
+ expect(ids).not.toContain("treeImg");
+ expect(ids).toContain("treeImgParent");
+ });
+
+ it("getTreeMap: keeps image note that is not referenced as imageLink by its parent", () => {
+ const mapRoot = buildNote({
+ id: "treeRoot2",
+ title: "Tree root 2",
+ children: [
+ { id: "treeImgKeep", title: "Standalone image", type: "image" }
+ ]
+ });
+ const res = note_map.getTreeMap(req(mapRoot.noteId)) as TreeMapResponse;
+ expect(res.notes.map((n) => n[0])).toContain("treeImgKeep");
+ });
+
+ it("getTreeMap: when root has excludeFromNoteMap, nothing is filtered out", () => {
+ const mapRoot = buildNote({
+ id: "treeRootExcl",
+ title: "Excluded root",
+ "#excludeFromNoteMap": "true",
+ children: [
+ { id: "treeChildExcl", title: "Child", "#excludeFromNoteMap": "true" }
+ ]
+ });
+ const res = note_map.getTreeMap(req(mapRoot.noteId)) as TreeMapResponse;
+ const ids = res.notes.map((n) => n[0]);
+ expect(ids).toContain("treeRootExcl");
+ expect(ids).toContain("treeChildExcl");
+ });
+
+ it("getLinkMap: includes neighbors, applies includeRelations / excludeRelations filters", () => {
+ const mapRoot = buildNote({
+ id: "lmRoot",
+ title: "LM root",
+ "#color": "red",
+ children: [
+ { id: "lmChildA", title: "A", "~friend": "lmChildB" },
+ { id: "lmChildB", title: "B", "~enemy": "lmChildA" }
+ ]
+ });
+
+ const all = note_map.getLinkMap(req(mapRoot.noteId)) as LinkMapResponse;
+ const linkNames = all.links.map((l) => l.name);
+ expect(linkNames).toContain("friend");
+ expect(linkNames).toContain("enemy");
+
+ const included = note_map.getLinkMap(req(mapRoot.noteId, { includeRelations: [ "friend" ] })) as LinkMapResponse;
+ expect(included.links.map((l) => l.name)).toEqual([ "friend" ]);
+
+ const excluded = note_map.getLinkMap(req(mapRoot.noteId, { excludeRelations: [ "friend" ] })) as LinkMapResponse;
+ const exNames = excluded.links.map((l) => l.name);
+ expect(exNames).toContain("enemy");
+ expect(exNames).not.toContain("friend");
+ });
+
+ it("getLinkMap: imageLink retained only when target is not a child of the source", () => {
+ // source -> imageLink -> external image note (not a child) => retained as a link
+ const mapRoot = buildNote({
+ id: "imgLinkRoot",
+ title: "Image link root",
+ children: [
+ { id: "imgSource", title: "Src", "~imageLink": "imgExternal" },
+ { id: "imgExternal", title: "External image", type: "image" }
+ ]
+ });
+ const res = note_map.getLinkMap(req(mapRoot.noteId)) as LinkMapResponse;
+ expect(res.links.some((l) => l.name === "imageLink" && l.sourceNoteId === "imgSource")).toBe(true);
+ });
+
+ it("getLinkMap: imageLink dropped when target is a real child of the source", () => {
+ const mapRoot = buildNote({
+ id: "imgChildRoot",
+ title: "Image child root",
+ children: [
+ {
+ id: "imgChildSource",
+ title: "Src",
+ "~imageLink": "imgChildTarget",
+ children: [ { id: "imgChildTarget", title: "Embedded", type: "image" } ]
+ }
+ ]
+ });
+ const res = note_map.getLinkMap(req(mapRoot.noteId)) as LinkMapResponse;
+ expect(res.links.some((l) => l.name === "imageLink")).toBe(false);
+ });
+
+ it("getLinkMap: root with excludeFromNoteMap keeps excluded descendants", () => {
+ const mapRoot = buildNote({
+ id: "lmExclRoot",
+ title: "LM excl root",
+ "#excludeFromNoteMap": "true",
+ children: [
+ { id: "lmExclChild", title: "Excl child", "#excludeFromNoteMap": "true" }
+ ]
+ });
+ const res = note_map.getLinkMap(req(mapRoot.noteId)) as LinkMapResponse;
+ expect(res.notes.map((n) => n[0])).toContain("lmExclChild");
+ });
+
+ it("getLinkMap: search note uses direct search results and removes itself", () => {
+ const resultNote = buildNote({ id: "searchResult", title: "Result" });
+ const searchNote = buildNote({ id: "searchNote1", title: "Search", type: "search" });
+ const spy = vi.spyOn(searchNote, "getSearchResultNotes").mockReturnValue([ resultNote ]);
+
+ const res = note_map.getLinkMap(req(searchNote.noteId)) as LinkMapResponse;
+ const ids = res.notes.map((n) => n[0]);
+ expect(ids).toContain("searchResult");
+ expect(ids).not.toContain("searchNote1");
+ spy.mockRestore();
+ });
+
+ it("getNeighbors: ignores configured relations and excludeFromNoteMap targets/sources", () => {
+ const excludedTarget = buildNote({ id: "nbExcluded", title: "Excluded", "#excludeFromNoteMap": "true" });
+ const mapRoot = buildNote({
+ id: "nbRoot",
+ title: "NB root",
+ "~template": "nbExcluded", // ignored relation
+ "~link": "nbExcluded" // valid relation but target excluded
+ });
+ // a source pointing INTO the root, but the source is excluded
+ buildNote({ id: "nbSourceExcluded", title: "Src excl", "#excludeFromNoteMap": "true", "~back": "nbRoot" });
+
+ const res = note_map.getLinkMap(req(mapRoot.noteId)) as LinkMapResponse;
+ const ids = res.notes.map((n) => n[0]);
+ expect(ids).not.toContain("nbExcluded");
+ expect(ids).not.toContain("nbSourceExcluded");
+ expect(excludedTarget).toBeDefined();
+ });
+
+ it("getNeighbors: walks forward and backward links across depth", () => {
+ // root -> a -> b (forward chain), and c -> root (backward)
+ buildNote({ id: "depthB", title: "B" });
+ buildNote({ id: "depthA", title: "A", "~rel": "depthB" });
+ const mapRoot = buildNote({ id: "depthRoot", title: "Root", "~rel": "depthA" });
+ buildNote({ id: "depthC", title: "C", "~rel": "depthRoot" });
+
+ const res = note_map.getLinkMap(req(mapRoot.noteId)) as LinkMapResponse;
+ const ids = res.notes.map((n) => n[0]);
+ expect(ids).toEqual(expect.arrayContaining([ "depthA", "depthB", "depthC" ]));
+ });
+
+ it("getNeighbors: ignores incoming ignored relations (e.g. template) on the backward pass", () => {
+ const mapRoot = buildNote({ id: "bwIgnoreRoot", title: "BW ignore root" });
+ // a note that targets the root via an ignored relation -> backward loop continues
+ buildNote({ id: "bwTemplateSrc", title: "Template src", "~template": "bwIgnoreRoot" });
+
+ const res = note_map.getLinkMap(req(mapRoot.noteId)) as LinkMapResponse;
+ expect(res.notes.map((n) => n[0])).not.toContain("bwTemplateSrc");
+ });
+
+ it("getNeighbors: walks backward links recursively beyond depth 1", () => {
+ // chain of backward links into the root: D -> C -> root
+ const mapRoot = buildNote({ id: "bwRoot", title: "BW root" });
+ buildNote({ id: "bwC", title: "C", "~rel": "bwRoot" });
+ buildNote({ id: "bwD", title: "D", "~rel": "bwC" });
+
+ const res = note_map.getLinkMap(req(mapRoot.noteId)) as LinkMapResponse;
+ const ids = res.notes.map((n) => n[0]);
+ expect(ids).toEqual(expect.arrayContaining([ "bwC", "bwD" ]));
+ });
+
+ it("updateDescendantCountMapForSearch: search parent aggregates child counts", () => {
+ const target = buildNote({ id: "udcTarget", title: "Target", children: [ { id: "udcChild", title: "Child" } ] });
+ const searchNote = buildNote({ id: "udcSearch", title: "Search", type: "search" });
+ const spy = vi.spyOn(searchNote, "getSearchResultNotes").mockReturnValue([ becca.notes["udcTarget"]! ]);
+
+ const res = note_map.getTreeMap(req(searchNote.noteId)) as TreeMapResponse;
+ // the search note's descendant count is derived from its resolved results
+ expect(res.noteIdToDescendantCountMap["udcSearch"]).toBeGreaterThanOrEqual(1);
+ expect(target).toBeDefined();
+ spy.mockRestore();
+ });
+
+ function backlinkExcerpts(sourceId: string, content: string) {
+ const target = buildNote({ id: `${sourceId}_t`, title: "ExcerptTarget" });
+ buildNote({ id: sourceId, title: "Src", type: "text", "~internalLink": target.noteId, content });
+ const res = note_map.getBacklinks(req(target.noteId));
+ return (res.find((b: any) => b.noteId === sourceId) as any).excerpts as string[];
+ }
+
+ const big = "x".repeat(260);
+ const small = "yy";
+
+ it("findExcerpts: expands to sibling blocks and truncates an overflowing previous sibling", () => {
+ const target = "exPrefix_t";
+ const excerpts = backlinkExcerpts(
+ "exPrefix",
+ `<p>${big}</p><p>${small}</p><p><a href="#root/${target}">link</a></p><p>${small}</p><p>${big}</p>`
+ );
+ // the leading truncated previous sibling is prefixed with the ellipsis
+ expect(excerpts[0]).toContain("…");
+ });
+
+ it("findExcerpts: truncates an overflowing next sibling with a trailing ellipsis", () => {
+ const target = "exSuffix_t";
+ const excerpts = backlinkExcerpts(
+ "exSuffix",
+ `<p><a href="#root/${target}">link</a></p><p>${big}</p>`
+ );
+ expect(excerpts[0]).toContain("…");
+ });
+});
+
+let api: CoreApiTester;
+
+describe("Note map API (core)", () => {
+ beforeAll(() => {
+ api = CoreApiTester.build();
+ });
+
+ it("returns a tree map for root", async () => {
+ const res = await api.post<TreeMapResponse>("/api/note-map/root/tree", { body: {} });
+ expect(res.status).toBe(200);
+ expect(Array.isArray(res.body.notes)).toBe(true);
+ expect(res.body.noteIdToDescendantCountMap).toBeTruthy();
+ });
+
+ it("returns a link map for root", async () => {
+ const res = await api.post<LinkMapResponse>("/api/note-map/root/link", { body: {} });
+ expect(res.status).toBe(200);
+ expect(Array.isArray(res.body.notes)).toBe(true);
+ expect(Array.isArray(res.body.links)).toBe(true);
+ });
+
+ it("returns backlinks and backlink-count for a linked note", async () => {
+ const target = await createTextNote(api, { title: "Backlink target" });
+ const source = await createTextNote(api, {
+ title: "Backlink source",
+ content: `<p>before <a class="reference-link" href="#root/${target.noteId}">link</a> after</p>`
+ });
+ await api.put(`/api/notes/${source.noteId}/relations/internalLink/to/${target.noteId}`);
+
+ const backlinks = await api.get<{ noteId: string; excerpts?: string[] }[]>(`/api/note-map/${target.noteId}/backlinks`);
+ expect(backlinks.status).toBe(200);
+ expect(backlinks.body.some((b) => b.noteId === source.noteId)).toBe(true);
+
+ const count = await api.get<{ count: number }>(`/api/note-map/${target.noteId}/backlink-count`);
+ expect(count.status).toBe(200);
+ expect(count.body.count).toBeGreaterThanOrEqual(1);
+ });
+
+ it("404s for a non-existent map root", async () => {
+ const res = await api.post("/api/note-map/missingNote999/tree", { body: {} });
+ expect(res.status).toBe(404);
+ });
+});
diff --git a/packages/trilium-core/src/routes/api/note_map.ts b/packages/trilium-core/src/routes/api/note_map.ts
index 82ce821ed9..b0eef78841 100644
--- a/packages/trilium-core/src/routes/api/note_map.ts
+++ b/packages/trilium-core/src/routes/api/note_map.ts
@@ -11,6 +11,7 @@ interface TreeLink {
}
function buildDescendantCountMap(noteIdsToCount: string[]) {
+ /* v8 ignore next 3 -- defensive guard: callers always pass a real array (noteIdsArray / Array.from(noteIds)) */
if (!Array.isArray(noteIdsToCount)) {
throw new Error("noteIdsToCount: type error");
}
@@ -20,6 +21,7 @@ function buildDescendantCountMap(noteIdsToCount: string[]) {
function getCount(noteId: string): number {
if (!(noteId in noteIdToCountMap)) {
const note = becca.getNote(noteId);
+ /* v8 ignore next 3 -- defensive guard: noteIds come from real notes / their resolved children */
if (!note) {
return 0;
}
@@ -145,6 +147,7 @@ function getLinkMap(req: Request<{ noteId: string }>) {
return false;
} else if (rel.name === "imageLink") {
const parentNote = becca.getNote(rel.noteId);
+ /* v8 ignore next 3 -- defensive guard: rel.noteId is already constrained to noteIds (existing notes) */
if (!parentNote) {
return false;
}
diff --git a/packages/trilium-core/src/routes/api/notes.spec.ts b/packages/trilium-core/src/routes/api/notes.spec.ts
index c472c9e89d..4a53b31d47 100644
--- a/packages/trilium-core/src/routes/api/notes.spec.ts
+++ b/packages/trilium-core/src/routes/api/notes.spec.ts
@@ -1,5 +1,7 @@
-import { beforeAll, describe, expect, it } from "vitest";
+import { beforeAll, describe, expect, it, vi } from "vitest";
+import becca from "../../becca/becca";
+import noteService from "../../services/notes";
import { getSql } from "../../services/sql/index";
import { createTextNote } from "../../test/api_fixtures";
import { CoreApiTester } from "../../test/api_tester";
@@ -125,5 +127,209 @@ describe("Notes API (core)", () => {
const res = await api.delete(`/api/notes/${noteId}`);
expect(res.status).toBe(400);
});
+
+ it("erases a note immediately when eraseNotes is set", async () => {
+ const { noteId } = await createTextNote(api, { title: "Erase now" });
+
+ const del = await api.delete(`/api/notes/${noteId}`, {
+ query: { taskId: "test-erase", eraseNotes: "true", last: "true" }
+ });
+ expect(del.status).toBe(204);
+ // Erasing removes the row entirely rather than just flagging it deleted.
+ expect(noteIsDeleted(noteId)).toBeNull();
+ });
+ });
+
+ describe("creating with targets", () => {
+ it("creates a sibling note after a target branch", async () => {
+ const anchor = await createTextNote(api, { title: "Anchor" });
+
+ interface CreateResponse {
+ note: { noteId: string };
+ branch: { parentNoteId: string };
+ }
+ const res = await api.post<CreateResponse>(
+ "/api/notes/root/children",
+ { query: { target: "after", targetBranchId: anchor.branchId }, body: { title: "After sibling", type: "text", content: "" } }
+ );
+ expect(res.status).toBe(200);
+ expect(res.body.note.noteId).toBeTruthy();
+ expect(res.body.branch.parentNoteId).toBe("root");
+ });
+ });
+
+ describe("revisions and conversion", () => {
+ it("force-saves a revision and returns its id", async () => {
+ const { noteId } = await createTextNote(api, { title: "Snapshot me" });
+ const res = await api.post<{ revisionId: string }>(`/api/notes/${noteId}/revision`, {
+ body: { description: "manual" }
+ });
+ expect(res.status).toBe(200);
+ expect(res.body.revisionId).toBeTruthy();
+ });
+
+ it("400s force-saving a revision of a protected note without a protected session", async () => {
+ const { noteId } = await createTextNote(api, { title: "Protected revision" });
+ becca.notes[noteId].isProtected = true;
+
+ const res = await api.post(`/api/notes/${noteId}/revision`, { body: {} });
+ expect(res.status).toBe(400);
+
+ becca.notes[noteId].isProtected = false;
+ });
+
+ it("returns a null attachment for a note ineligible for conversion", async () => {
+ const { noteId } = await createTextNote(api, { title: "Not an image" });
+ const res = await api.post<{ attachment: unknown }>(`/api/notes/${noteId}/convert-to-attachment`);
+ expect(res.status).toBe(200);
+ expect(res.body.attachment).toBeNull();
+ });
+ });
+
+ describe("title and type", () => {
+ it("400s changing the title of a protected note without a protected session", async () => {
+ const { noteId } = await createTextNote(api, { title: "Locked" });
+ becca.notes[noteId].isProtected = true;
+
+ const res = await api.put(`/api/notes/${noteId}/title`, { body: { title: "Nope" } });
+ expect(res.status).toBe(400);
+
+ becca.notes[noteId].isProtected = false;
+ });
+
+ it("leaves the note untouched when the title is unchanged", async () => {
+ const { noteId } = await createTextNote(api, { title: "Same title" });
+ const res = await api.put<{ title: string }>(`/api/notes/${noteId}/title`, {
+ body: { title: "Same title" }
+ });
+ expect(res.status).toBe(200);
+ expect(res.body.title).toBe("Same title");
+ });
+
+ it("sets the note type and mime", async () => {
+ const { noteId } = await createTextNote(api, { title: "Type me" });
+ const res = await api.put(`/api/notes/${noteId}/type`, {
+ body: { type: "code", mime: "text/x-python" }
+ });
+ expect(res.status).toBe(204);
+
+ const note = await api.get<{ type: string; mime: string }>(`/api/notes/${noteId}`);
+ expect(note.body.type).toBe("code");
+ expect(note.body.mime).toBe("text/x-python");
+ });
+ });
+
+ describe("structural operations", () => {
+ it("sorts child notes", async () => {
+ const parent = await createTextNote(api, { title: "Sort parent" });
+ await createTextNote(api, { parentNoteId: parent.noteId, title: "Zebra" });
+ await createTextNote(api, { parentNoteId: parent.noteId, title: "Alpha" });
+
+ const res = await api.put(`/api/notes/${parent.noteId}/sort-children`, {
+ body: { sortBy: "title", sortDirection: "asc", foldersFirst: false, sortNatural: false, sortLocale: "" }
+ });
+ expect(res.status).toBe(204);
+
+ const children = becca.notes[parent.noteId].getChildNotes();
+ expect(children[0].title).toBe("Alpha");
+ });
+
+ it("protects a note recursively", async () => {
+ const { noteId } = await createTextNote(api, { title: "Protect target" });
+
+ // The actual (un)protect requires an active protected session, which the
+ // in-process tester does not have, so stub the recursive worker and assert
+ // the handler drives it (with subtree) and reports task success.
+ const spy = vi.spyOn(noteService, "protectNoteRecursively").mockImplementation(() => {});
+ try {
+ const res = await api.put(`/api/notes/${noteId}/protect/1`, { query: { subtree: "1" } });
+ expect(res.status).toBe(204);
+ expect(spy).toHaveBeenCalledWith(becca.notes[noteId], true, true, expect.anything());
+ } finally {
+ spy.mockRestore();
+ }
+ });
+
+ it("duplicates a subtree under a parent", async () => {
+ const original = await createTextNote(api, { title: "Original subtree" });
+ await createTextNote(api, { parentNoteId: original.noteId, title: "Child" });
+
+ interface DuplicateResponse {
+ note: { noteId: string; title: string };
+ }
+ const res = await api.post<DuplicateResponse>(
+ `/api/notes/${original.noteId}/duplicate/root`
+ );
+ expect(res.status).toBe(200);
+ expect(res.body.note.noteId).not.toBe(original.noteId);
+ expect(res.body.note.title).toContain("Original subtree");
+ });
+ });
+
+ describe("erase and preview operations", () => {
+ it("erases deleted notes now", async () => {
+ const { noteId } = await createTextNote(api, { title: "Will be erased" });
+ await api.delete(`/api/notes/${noteId}`, { query: { taskId: "erase-deleted", last: "true" } });
+
+ const res = await api.post("/api/notes/erase-deleted-notes-now");
+ expect(res.status).toBe(204);
+ expect(noteIsDeleted(noteId)).toBeNull();
+ });
+
+ it("erases unused attachments now", async () => {
+ const res = await api.post("/api/notes/erase-unused-attachments-now");
+ expect(res.status).toBe(204);
+ });
+
+ it("previews a subtree to be deleted and surfaces broken relations", async () => {
+ // parent → child, with an outside note holding a relation to the child;
+ // deleting the parent recurses into the child and breaks the outside relation.
+ const parent = await createTextNote(api, { title: "Preview parent" });
+ const child = await createTextNote(api, { parentNoteId: parent.noteId, title: "Preview child" });
+ const outside = await createTextNote(api, { title: "Preview outside" });
+
+ const rel = await api.put(
+ `/api/notes/${outside.noteId}/relations/refToChild/to/${child.noteId}`,
+ { body: {} }
+ );
+ expect(rel.status).toBeLessThan(300);
+
+ const res = await api.post<{ noteIdsToBeDeleted: string[]; brokenRelations: Array<{ noteId: string }> }>(
+ "/api/delete-notes-preview",
+ { body: { branchIdsToDelete: [ parent.branchId ], deleteAllClones: true } }
+ );
+ expect(res.status).toBe(200);
+ expect(res.body.noteIdsToBeDeleted).toEqual(expect.arrayContaining([ parent.noteId, child.noteId ]));
+ expect(res.body.brokenRelations.some((attr) => attr.noteId === outside.noteId)).toBe(true);
+ });
+
+ it("skips missing branches in the delete preview", async () => {
+ const res = await api.post<{ noteIdsToBeDeleted: string[] }>(
+ "/api/delete-notes-preview",
+ { body: { branchIdsToDelete: [ "missingBranch123" ], deleteAllClones: false } }
+ );
+ expect(res.status).toBe(200);
+ expect(res.body.noteIdsToBeDeleted).toEqual([]);
+ });
+
+ it("skips weak branches (e.g. bookmarks) in the delete preview", async () => {
+ const note = await createTextNote(api, { title: "Weakly linked" });
+
+ // A clone under _lbBookmarks produces a weak branch, which the preview ignores.
+ interface CloneResponse { branchId: string }
+ const clone = await api.put<CloneResponse>(
+ `/api/notes/${note.noteId}/clone-to-note/_lbBookmarks`,
+ { body: {} }
+ );
+ expect(clone.status).toBe(200);
+ expect(clone.body.branchId).toBeTruthy();
+
+ const res = await api.post<{ noteIdsToBeDeleted: string[] }>(
+ "/api/delete-notes-preview",
+ { body: { branchIdsToDelete: [ clone.body.branchId ], deleteAllClones: true } }
+ );
+ expect(res.status).toBe(200);
+ expect(res.body.noteIdsToBeDeleted).toEqual([]);
+ });
});
});
diff --git a/packages/trilium-core/src/routes/api/notes.ts b/packages/trilium-core/src/routes/api/notes.ts
index 47c9a50fb4..6c6242cb75 100644
--- a/packages/trilium-core/src/routes/api/notes.ts
+++ b/packages/trilium-core/src/routes/api/notes.ts
@@ -114,6 +114,7 @@ function createNote(req: Request) {
}
if (targetBranchId && typeof targetBranchId !== "string") {
+ /* v8 ignore next -- defensive guard for Express array query params; unreachable via the string-only test harness */
throw new ValidationError("Missing or incorrect type for target branch ID.");
}
diff --git a/packages/trilium-core/src/routes/api/options.spec.ts b/packages/trilium-core/src/routes/api/options.spec.ts
new file mode 100644
index 0000000000..df50372e43
--- /dev/null
+++ b/packages/trilium-core/src/routes/api/options.spec.ts
@@ -0,0 +1,135 @@
+import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
+
+import * as i18n from "../../services/i18n";
+import { getConfig, initConfig } from "../../services/config";
+import { getSql } from "../../services/sql/index";
+import { CoreApiTester } from "../../test/api_tester";
+
+/**
+ * Drives the shared core options routes through {@link CoreApiTester} (no
+ * Express), so this spec runs under both the node and standalone (WASM) suites.
+ */
+let api: CoreApiTester;
+
+function getOptionValue(name: string): string | null {
+ return getSql().getValue<string | null>("SELECT value FROM options WHERE name = ?", [name]);
+}
+
+describe("Options API (core)", () => {
+ beforeAll(() => {
+ api = CoreApiTester.build();
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it("returns the allowed option map, isPasswordSet and skips read-only fields by default", async () => {
+ const res = await api.get<Record<string, string>>("/api/options");
+ expect(res.status).toBe(200);
+ // an allowed option is present
+ expect(res.body.theme).toBeDefined();
+ // a non-allowed option is omitted
+ expect(res.body.passwordVerificationHash).toBeUndefined();
+ // password is set in the demo fixture
+ expect(res.body.isPasswordSet).toBe("true");
+ // read-only branch not taken with the default (empty) config
+ expect(res.body.databaseReadonly).toBeUndefined();
+ });
+
+ it("applies the read-only config branch", async () => {
+ const original = getConfig();
+ initConfig({ ...original, General: { ...original.General, readOnly: true } });
+ try {
+ const res = await api.get<Record<string, string>>("/api/options");
+ expect(res.body.databaseReadonly).toBe("true");
+ expect(res.body.autoReadonlySizeText).toBe("0");
+ expect(res.body.autoReadonlySizeCode).toBe("0");
+ } finally {
+ initConfig(original);
+ }
+ });
+
+ it("updates a single allowed option via PUT /api/options/:name/:value", async () => {
+ const res = await api.put("/api/options/zoomFactor/1.5");
+ expect(res.status).toBe(204);
+ expect(getOptionValue("zoomFactor")).toBe("1.5");
+ });
+
+ it("rejects a not-allowed single option with a ValidationError (400)", async () => {
+ const res = await api.put("/api/options/passwordVerificationHash/hacked");
+ expect(res.status).toBe(400);
+ });
+
+ it("runs changeLanguage when updating the locale option", async () => {
+ const changeLanguage = vi.spyOn(i18n, "changeLanguage").mockResolvedValue(undefined as never);
+ const res = await api.put("/api/options/locale/de");
+ expect(res.status).toBe(204);
+ expect(changeLanguage).toHaveBeenCalledWith("de");
+ expect(getOptionValue("locale")).toBe("de");
+ });
+
+ it("covers the isAllowed prefix/suffix branches", async () => {
+ // starts with keyboardShortcuts
+ expect((await api.put("/api/options/keyboardShortcutsFoo/x")).status).toBe(204);
+ // ends with Collapsed
+ expect((await api.put("/api/options/somethingCollapsed/y")).status).toBe(204);
+ // starts with hideArchivedNotes
+ expect((await api.put("/api/options/hideArchivedNotes_main/true")).status).toBe(204);
+ expect(getOptionValue("keyboardShortcutsFoo")).toBe("x");
+ });
+
+ it("updates multiple options via PUT /api/options (map body)", async () => {
+ const res = await api.put("/api/options", { body: { mainFontSize: "120", treeFontSize: "90" } });
+ expect(res.status).toBe(204);
+ expect(getOptionValue("mainFontSize")).toBe("120");
+ expect(getOptionValue("treeFontSize")).toBe("90");
+ });
+
+ it("runs changeLanguage when the locale is present in the map body", async () => {
+ const changeLanguage = vi.spyOn(i18n, "changeLanguage").mockResolvedValue(undefined as never);
+ const res = await api.put("/api/options", { body: { locale: "fr" } });
+ expect(res.status).toBe(204);
+ expect(changeLanguage).toHaveBeenCalledWith("fr");
+ });
+
+ it("rolls back the batch and errors (500) when a not-allowed option is in the map body", async () => {
+ const before = getOptionValue("mainFontSize");
+ const res = await api.put("/api/options", {
+ body: { mainFontSize: "200", passwordVerificationHash: "nope" }
+ });
+ expect(res.status).toBe(500);
+ // earlier option in the same batch was rolled back
+ expect(getOptionValue("mainFontSize")).toBe(before);
+ });
+
+ it("returns user themes, deriving the value from title when appTheme has no value", async () => {
+ // theme with an explicit appTheme value
+ const withValue = await api.post<{ note: { noteId: string } }>(
+ "/api/notes/root/children?target=into",
+ { body: { title: "Theme A", type: "text", content: "" } }
+ );
+ await api.put(`/api/notes/${withValue.body.note.noteId}/set-attribute`, {
+ body: { type: "label", name: "appTheme", value: "my-theme" }
+ });
+
+ // theme with appTheme but no value -> derived from title
+ const noValue = await api.post<{ note: { noteId: string } }>(
+ "/api/notes/root/children?target=into",
+ { body: { title: "Theme B!!", type: "text", content: "" } }
+ );
+ await api.put(`/api/notes/${noValue.body.note.noteId}/set-attribute`, {
+ body: { type: "label", name: "appTheme", value: "" }
+ });
+
+ const res = await api.get<Array<{ val: string; title: string; noteId: string }>>(
+ "/api/options/user-themes"
+ );
+ expect(res.status).toBe(200);
+ const withValueEntry = res.body.find((t) => t.noteId === withValue.body.note.noteId);
+ const noValueEntry = res.body.find((t) => t.noteId === noValue.body.note.noteId);
+ expect(withValueEntry?.val).toBe("my-theme");
+ // "Theme B!!" -> non-alphanumerics replaced with "-"
+ expect(noValueEntry?.val).toBe("theme-b--");
+ });
+});
diff --git a/packages/trilium-core/src/routes/api/others.spec.ts b/packages/trilium-core/src/routes/api/others.spec.ts
index 365762d33f..5dab96983a 100644
--- a/packages/trilium-core/src/routes/api/others.spec.ts
+++ b/packages/trilium-core/src/routes/api/others.spec.ts
@@ -38,6 +38,22 @@ describe("Others API (core)", () => {
expect(res.body.iconClassToCountMap["bx-test-icon-usage"]).toBeGreaterThanOrEqual(1);
expect(res.body.iconClassToCountMap).not.toHaveProperty("bx");
});
+
+ it("ignores blank iconClass labels and system-note icons", async () => {
+ // A whitespace-only iconClass exercises the empty-value `continue`.
+ const { noteId } = await createTextNote(api, { title: "Blank icon note" });
+ const add = await api.post(`/api/notes/${noteId}/attributes`, {
+ body: { type: "label", name: "iconClass", value: " " }
+ });
+ expect(add.status).toBe(204);
+
+ const res = await api.get<{ iconClassToCountMap: Record<string, number> }>(
+ "/api/other/icon-usage"
+ );
+ expect(res.status).toBe(200);
+ // The blank value is skipped, so no empty-string key is added.
+ expect(Object.keys(res.body.iconClassToCountMap)).not.toContain("");
+ });
});
describe("render markdown", () => {
diff --git a/packages/trilium-core/src/routes/api/password.spec.ts b/packages/trilium-core/src/routes/api/password.spec.ts
new file mode 100644
index 0000000000..0a99909b65
--- /dev/null
+++ b/packages/trilium-core/src/routes/api/password.spec.ts
@@ -0,0 +1,64 @@
+import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
+
+import passwordService from "../../services/encryption/password";
+import { getSql } from "../../services/sql/index";
+import { CoreApiTester } from "../../test/api_tester";
+
+/**
+ * Drives the shared core password routes through {@link CoreApiTester} (no
+ * Express), so this spec runs under both the node and standalone (WASM) suites.
+ */
+let api: CoreApiTester;
+
+function getPasswordHash(): string | null {
+ return getSql().getValue<string | null>(
+ "SELECT value FROM options WHERE name = 'passwordVerificationHash'"
+ );
+}
+
+describe("Password API (core)", () => {
+ beforeAll(() => {
+ api = CoreApiTester.build();
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it("changes the password when a password is already set", async () => {
+ const res = await api.post<{ success: boolean }>("/api/password/change", {
+ body: { current_password: "demo1234", new_password: "newpass5678" }
+ });
+ expect(res.status).toBe(200);
+ expect(res.body.success).toBe(true);
+ });
+
+ it("sets the password via setPassword when none is set yet", async () => {
+ const setPassword = vi.spyOn(passwordService, "setPassword").mockResolvedValue({ success: true });
+ vi.spyOn(passwordService, "isPasswordSet").mockReturnValue(false);
+
+ const res = await api.post<{ success: boolean }>("/api/password/change", {
+ body: { new_password: "brandNew99" }
+ });
+ expect(res.status).toBe(200);
+ expect(res.body.success).toBe(true);
+ expect(setPassword).toHaveBeenCalledWith("brandNew99");
+ });
+
+ it("rejects a password reset with an incorrect confirmation (400)", async () => {
+ const res = await api.post("/api/password/reset", { query: { really: "nope" } });
+ expect(res.status).toBe(400);
+ // password is still set
+ expect(getPasswordHash()).toBeTruthy();
+ });
+
+ // Destructive: must run LAST since it clears the password options.
+ it("resets the password with the correct confirmation magic string", async () => {
+ const res = await api.post<{ success: boolean }>("/api/password/reset", {
+ query: { really: "yesIReallyWantToResetPasswordAndLoseAccessToMyProtectedNotes" }
+ });
+ expect(res.status).toBe(200);
+ expect(res.body.success).toBe(true);
+ expect(getPasswordHash()).toBe("");
+ });
+});
diff --git a/packages/trilium-core/src/routes/api/recent_changes.spec.ts b/packages/trilium-core/src/routes/api/recent_changes.spec.ts
index 685e69cea7..1c9457b85f 100644
--- a/packages/trilium-core/src/routes/api/recent_changes.spec.ts
+++ b/packages/trilium-core/src/routes/api/recent_changes.spec.ts
@@ -1,7 +1,9 @@
-import { beforeAll, describe, expect, it } from "vitest";
+import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import type { RecentChangeRow } from "@triliumnext/commons";
+import protectedSessionService from "../../services/protected_session";
+import { getSql } from "../../services/sql/index";
import { createTextNote } from "../../test/api_fixtures";
import { CoreApiTester } from "../../test/api_tester";
@@ -90,4 +92,46 @@ describe("Recent changes API (core)", () => {
expect(Array.isArray(res.body)).toBe(true);
expect(res.body.length).toBe(0);
});
+
+ describe("protected notes", () => {
+ let protectedNoteId: string;
+
+ beforeAll(async () => {
+ const created = await createTextNote(api, { title: "Secret note" });
+ protectedNoteId = created.noteId;
+ // Flag the note as protected directly in the DB so it surfaces in the
+ // recent-changes feed with current_isProtected set, without needing a
+ // real protected session for note creation.
+ getSql().execute("UPDATE notes SET isProtected = 1 WHERE noteId = ?", [ protectedNoteId ]);
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it("masks protected titles when no protected session is available", async () => {
+ vi.spyOn(protectedSessionService, "isProtectedSessionAvailable").mockReturnValue(false);
+
+ const res = await api.get<RecentChangeRow[]>("/api/recent-changes/root");
+ expect(res.status).toBe(200);
+
+ const entry = res.body.find((change) => change.noteId === protectedNoteId);
+ expect(entry).toBeTruthy();
+ expect(entry?.title).toBe("[protected]");
+ expect(entry?.current_title).toBe("[protected]");
+ });
+
+ it("decrypts protected titles when a protected session is available", async () => {
+ vi.spyOn(protectedSessionService, "isProtectedSessionAvailable").mockReturnValue(true);
+ vi.spyOn(protectedSessionService, "decryptString").mockReturnValue("Decrypted secret");
+
+ const res = await api.get<RecentChangeRow[]>("/api/recent-changes/root");
+ expect(res.status).toBe(200);
+
+ const entry = res.body.find((change) => change.noteId === protectedNoteId);
+ expect(entry).toBeTruthy();
+ expect(entry?.title).toBe("Decrypted secret");
+ expect(entry?.current_title).toBe("Decrypted secret");
+ });
+ });
});
diff --git a/packages/trilium-core/src/routes/api/recent_notes.spec.ts b/packages/trilium-core/src/routes/api/recent_notes.spec.ts
index 73e4b6ea84..b3a9ff7f3c 100644
--- a/packages/trilium-core/src/routes/api/recent_notes.spec.ts
+++ b/packages/trilium-core/src/routes/api/recent_notes.spec.ts
@@ -1,4 +1,4 @@
-import { beforeAll, describe, expect, it } from "vitest";
+import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import { getSql } from "../../services/sql/index";
import { createTextNote } from "../../test/api_fixtures";
@@ -22,6 +22,10 @@ describe("Recent notes API (core)", () => {
api = CoreApiTester.build();
});
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
it("records a recent note and persists it to the DB", async () => {
const { noteId } = await createTextNote(api, { title: "Recently visited" });
const notePath = `root/${noteId}`;
@@ -61,4 +65,26 @@ describe("Recent notes API (core)", () => {
);
expect(count).toBe(1);
});
+
+ it("prunes stale recent notes when the random cutoff sweep fires", async () => {
+ // The handler only runs the cutoff DELETE when `Math.random() < 0.05`;
+ // force it deterministically so the prune branch is exercised. Insert a
+ // stale row (created over 24h ago) that the sweep should remove.
+ const staleNoteId = "staleRecentNote";
+ getSql().execute(
+ "INSERT OR REPLACE INTO recent_notes (noteId, notePath, utcDateCreated) VALUES (?, ?, ?)",
+ [ staleNoteId, `root/${staleNoteId}`, "2000-01-01 00:00:00.000Z" ]
+ );
+
+ const { noteId } = await createTextNote(api, { title: "Triggers prune" });
+ vi.spyOn(Math, "random").mockReturnValue(0);
+
+ const res = await api.post("/api/recent-notes", {
+ body: { noteId, notePath: `root/${noteId}` }
+ });
+ expect(res.status).toBe(204);
+
+ expect(getRecentNote(staleNoteId)).toBeNull();
+ expect(getRecentNote(noteId)).not.toBeNull();
+ });
});
diff --git a/packages/trilium-core/src/routes/api/relation-map.spec.ts b/packages/trilium-core/src/routes/api/relation-map.spec.ts
index c0a00f1770..55ccd0b975 100644
--- a/packages/trilium-core/src/routes/api/relation-map.spec.ts
+++ b/packages/trilium-core/src/routes/api/relation-map.spec.ts
@@ -99,6 +99,58 @@ describe("Relation Map API (core)", () => {
expect(res.body.relations).toEqual([]);
});
+ it("includes inverse relation definitions of the requested notes", async () => {
+ const map = await createTextNote(api, { title: "Map" });
+ const source = await createTextNote(api, { title: "Source" });
+
+ // A promoted relation definition with an inverse relation populates the
+ // inverseRelations map for both directions.
+ const attr = await api.post(`/api/notes/${source.noteId}/attributes`, {
+ body: { type: "label", name: "relation:spouse", value: "inverse=spouse" }
+ });
+ expect(attr.status).toBe(204);
+
+ const res = await api.post<RelationMapResponse>("/api/relation-map", {
+ body: { relationMapNoteId: map.noteId, noteIds: [ source.noteId ] }
+ });
+
+ expect(res.status).toBe(200);
+ expect(res.body.inverseRelations.spouse).toBe("spouse");
+ });
+
+ it("honours displayRelations and hideRelations labels on the map note", async () => {
+ const map = await createTextNote(api, { title: "Map" });
+ const source = await createTextNote(api, { title: "Source" });
+ const target = await createTextNote(api, { title: "Target" });
+
+ // displayRelations acts as an allow-list: only "links" is kept, "ignored" dropped.
+ for (const label of [
+ { name: "displayRelations", value: "links, other" },
+ { name: "hideRelations", value: "ignored" }
+ ]) {
+ const res = await api.post(`/api/notes/${map.noteId}/attributes`, {
+ body: { type: "label", name: label.name, value: label.value }
+ });
+ expect(res.status).toBe(204);
+ }
+
+ for (const name of [ "links", "ignored" ]) {
+ await api.put(`/api/notes/${source.noteId}/relations/${name}/to/${target.noteId}`);
+ }
+
+ const res = await api.post<RelationMapResponse>("/api/relation-map", {
+ body: {
+ relationMapNoteId: map.noteId,
+ noteIds: [ source.noteId, target.noteId ]
+ }
+ });
+
+ expect(res.status).toBe(200);
+ const names = res.body.relations.map((relation) => relation.name);
+ expect(names).toContain("links");
+ expect(names).not.toContain("ignored");
+ });
+
it("404s when the relation map note does not exist", async () => {
const { noteId } = await createTextNote(api, { title: "Source" });
diff --git a/packages/trilium-core/src/routes/api/revisions.spec.ts b/packages/trilium-core/src/routes/api/revisions.spec.ts
index 48c3d47365..e2eeb568f3 100644
--- a/packages/trilium-core/src/routes/api/revisions.spec.ts
+++ b/packages/trilium-core/src/routes/api/revisions.spec.ts
@@ -1,9 +1,13 @@
-import { beforeAll, describe, expect, it } from "vitest";
+import { beforeAll, describe, expect, it, vi } from "vitest";
+import becca from "../../becca/becca";
+import * as cls from "../../services/context";
import { getSql } from "../../services/sql/index";
import { createTextNote } from "../../test/api_fixtures";
import { CoreApiTester } from "../../test/api_tester";
+import revisionsApiRoute from "./revisions";
+
/**
* Drives the shared core revision routes through {@link CoreApiTester} (no Express),
* so this spec runs under both the node and standalone (WASM) suites.
@@ -218,5 +222,232 @@ describe("Revisions API (core)", () => {
expect(res.status).toBe(200);
expect(res.body).toEqual([]);
});
+
+ it("includes the root note (none_root branch) when it matches the date", async () => {
+ const row = getSql().getRowOrNull<{ dateModified: string }>(
+ "SELECT dateModified FROM notes WHERE noteId = 'root'"
+ );
+ const date = (row?.dateModified ?? "").substring(0, 10);
+
+ const res = await api.get<Array<{ noteId: string; notePath: string[] | null }>>(
+ `/api/edited-notes/${date}`
+ );
+ expect(res.status).toBe(200);
+ expect(res.body.some((note) => note.noteId === "root")).toBe(true);
+ });
+
+ it("narrows results to the hoisted subtree", async () => {
+ const parent = await createTextNote(api, { title: "Hoisted parent" });
+ const child = await createTextNote(api, { parentNoteId: parent.noteId, title: "Hoisted child" });
+
+ const row = getSql().getRowOrNull<{ dateModified: string }>(
+ "SELECT dateModified FROM notes WHERE noteId = ?",
+ [ child.noteId ]
+ );
+ const date = (row?.dateModified ?? "").substring(0, 10);
+
+ // Pretend the parent is hoisted so the handler filters by ancestry.
+ const spy = vi.spyOn(cls, "getHoistedNoteId").mockReturnValue(parent.noteId);
+ try {
+ const res = await api.get<Array<{ noteId: string }>>(`/api/edited-notes/${date}`);
+ expect(res.status).toBe(200);
+ expect(res.body.some((note) => note.noteId === child.noteId)).toBe(true);
+ // root was edited some other day, but even if present it is filtered out by the hoist.
+ expect(res.body.every((note) => note.noteId !== "root")).toBe(true);
+ } finally {
+ spy.mockRestore();
+ }
+ });
+ });
+
+ describe("typed revisions", () => {
+ /**
+ * Snapshots a note after coercing it to a given type, so we can drive the
+ * type-specific branches of {@link revisionsApiRoute.getRevision}.
+ */
+ async function createTypedRevision(
+ type: string,
+ mime: string,
+ content: string
+ ): Promise<string> {
+ const { noteId } = await createTextNote(api, { content });
+ const typeRes = await api.put(`/api/notes/${noteId}/type`, { body: { type, mime } });
+ expect(typeRes.status).toBe(204);
+
+ const res = await api.post<{ revisionId: string }>(`/api/notes/${noteId}/revision`, {
+ body: { description: "typed" }
+ });
+ expect(res.status).toBe(200);
+ return res.body.revisionId;
+ }
+
+ it("truncates string content of a file revision", async () => {
+ const revisionId = await createTypedRevision("file", "text/plain", "x".repeat(15000));
+
+ const res = await api.get<{ content: string; type: string }>(`/api/revisions/${revisionId}`);
+ expect(res.status).toBe(200);
+ expect(res.body.type).toBe("file");
+ expect(res.body.content.length).toBeLessThanOrEqual(10000);
+ });
+
+ it("base64-encodes the content of an image revision", async () => {
+ const revisionId = await createTypedRevision("image", "image/png", "binary-image-bytes");
+
+ const res = await api.get<{ content: string; type: string }>(`/api/revisions/${revisionId}`);
+ expect(res.status).toBe(200);
+ expect(res.body.type).toBe("image");
+ // Base64 output, decodes back to the original content.
+ expect(Buffer.from(res.body.content, "base64").toString()).toContain("binary-image-bytes");
+ });
+ });
+
+ describe("excess revisions", () => {
+ it("erases excess revision snapshots across notes", async () => {
+ const { noteId } = await createTextNote(api, { title: "Excess" });
+ await api.post(`/api/notes/${noteId}/revision`, { body: {} });
+
+ const res = await api.post("/api/revisions/erase-all-excess-revisions");
+ expect(res.status).toBe(204);
+ });
+ });
+
+ describe("description validation", () => {
+ it("400s when the description is not a string", async () => {
+ const { revisionId } = await createNoteWithRevision({ title: "Bad description" });
+
+ const res = await api.patch(`/api/revisions/${revisionId}`, {
+ body: { description: 123 }
+ });
+ expect(res.status).toBe(400);
+ });
+ });
+
+ describe("restoring with attachments", () => {
+ it("restores a revision whose snapshot referenced attachments", async () => {
+ const { noteId } = await createTextNote(api, { title: "Has attachment" });
+
+ // Attach an image to the note, then reference it from the note content.
+ const saveRes = await api.post(`/api/notes/${noteId}/attachments`, {
+ body: { role: "image", mime: "image/png", title: "pic.png", content: "image-bytes" }
+ });
+ expect(saveRes.status).toBe(204);
+
+ const attRow = getSql().getRowOrNull<{ attachmentId: string }>(
+ "SELECT attachmentId FROM attachments WHERE ownerId = ? AND isDeleted = 0",
+ [ noteId ]
+ );
+ const attachmentId = attRow?.attachmentId as string;
+ expect(attachmentId).toBeTruthy();
+
+ await api.put(`/api/notes/${noteId}/data`, {
+ body: { content: `<img src="attachments/${attachmentId}">` }
+ });
+
+ const snapshot = await api.post<{ revisionId: string }>(`/api/notes/${noteId}/revision`, {
+ body: {}
+ });
+ const revisionId = snapshot.body.revisionId;
+
+ // Move the note away from the snapshot, then restore it.
+ await api.put(`/api/notes/${noteId}/data`, { body: { content: "<p>changed</p>" } });
+
+ const restore = await api.post(`/api/revisions/${revisionId}/restore`);
+ expect(restore.status).toBe(204);
+
+ // The restored content rewrites attachment references to the new attachment ids.
+ const blob = await api.get<{ content: string }>(`/api/notes/${noteId}/blob`);
+ expect(blob.body.content).toContain("attachments/");
+ });
+ });
+
+ describe("download (unrouted helper)", () => {
+ // downloadRevision is exported but not currently wired into the shared routes,
+ // so it is exercised directly rather than through CoreApiTester.
+ function mockRes() {
+ const headers: Record<string, string> = {};
+ const state: { status: number; body: unknown } = { status: 200, body: undefined };
+ return {
+ headers,
+ state,
+ setHeader(name: string, value: string) { headers[name] = value; return this; },
+ status(code: number) { state.status = code; return this; },
+ send(body: unknown) { state.body = body; return this; }
+ };
+ }
+
+ it("sends revision content with a content-disposition filename", async () => {
+ const { revisionId } = await createNoteWithRevision({
+ title: "Downloadable",
+ content: "<p>download me</p>"
+ });
+
+ const res = mockRes();
+ cls.init(() =>
+ revisionsApiRoute.downloadRevision({ params: { revisionId } } as never, res as never)
+ );
+
+ expect(res.headers["Content-Disposition"]).toMatch(/Downloadable/);
+ expect(res.headers["Content-Type"]).toBeTruthy();
+ expect(res.state.body).toBeTruthy();
+ });
+
+ it("appends the creation date when the filename has no extension", async () => {
+ // A file note with an octet-stream mime yields a download title without an
+ // extension, so the date is appended to the bare filename.
+ const revisionId = await (async () => {
+ const { noteId } = await createTextNote(api, { title: "No extension title", content: "data" });
+ await api.put(`/api/notes/${noteId}/type`, {
+ body: { type: "file", mime: "application/octet-stream" }
+ });
+ const r = await api.post<{ revisionId: string }>(`/api/notes/${noteId}/revision`, { body: {} });
+ return r.body.revisionId;
+ })();
+
+ const res = mockRes();
+ cls.init(() =>
+ revisionsApiRoute.downloadRevision({ params: { revisionId } } as never, res as never)
+ );
+ // No file extension on a text note → the date is appended to the bare filename.
+ expect(res.headers["Content-Disposition"]).toMatch(/\d{8}/);
+ });
+
+ it("401s when the revision content is not available", async () => {
+ const { revisionId } = await createNoteWithRevision({ title: "Protected download" });
+
+ // getRevisionOrThrow builds a fresh BRevision per call, so override the
+ // lookup itself to return one reporting its content as unavailable.
+ const revision = becca.getRevisionOrThrow(revisionId);
+ revision.isContentAvailable = () => false;
+ const spy = vi.spyOn(becca, "getRevisionOrThrow").mockReturnValue(revision);
+ try {
+ const res = mockRes();
+ cls.init(() =>
+ revisionsApiRoute.downloadRevision({ params: { revisionId } } as never, res as never)
+ );
+ expect(res.state.status).toBe(401);
+ expect(res.headers["Content-Type"]).toBe("text/plain");
+ } finally {
+ spy.mockRestore();
+ }
+ });
+
+ it("throws when the revision is missing a creation date", async () => {
+ const { revisionId } = await createNoteWithRevision({ title: "No date" });
+
+ // Force the defensive "missing creation date" guard in getRevisionFilename.
+ const revision = becca.getRevisionOrThrow(revisionId);
+ revision.dateCreated = undefined as never;
+ const spy = vi.spyOn(becca, "getRevisionOrThrow").mockReturnValue(revision);
+ try {
+ const res = mockRes();
+ expect(() =>
+ cls.init(() =>
+ revisionsApiRoute.downloadRevision({ params: { revisionId } } as never, res as never)
+ )
+ ).toThrow();
+ } finally {
+ spy.mockRestore();
+ }
+ });
});
});
diff --git a/packages/trilium-core/src/routes/api/script.spec.ts b/packages/trilium-core/src/routes/api/script.spec.ts
new file mode 100644
index 0000000000..8bdb500110
--- /dev/null
+++ b/packages/trilium-core/src/routes/api/script.spec.ts
@@ -0,0 +1,211 @@
+import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
+
+import attributeService from "../../services/attributes";
+import scriptService from "../../services/script";
+import { createTextNote } from "../../test/api_fixtures";
+import { CoreApiTester } from "../../test/api_tester";
+
+let api: CoreApiTester;
+
+interface ExecResponse {
+ success: boolean;
+ executionResult?: unknown;
+ error?: string;
+}
+
+async function createCodeNote(content: string): Promise<string> {
+ const res = await api.post<{ note: { noteId: string } }>(
+ "/api/notes/root/children?target=into",
+ { body: { title: "Code note", type: "code", mime: "application/javascript;env=frontend", content } }
+ );
+ return res.body.note.noteId;
+}
+
+describe("Script API (core)", () => {
+ beforeAll(() => {
+ api = CoreApiTester.build();
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ describe("exec", () => {
+ // exec overrides the note's content with the script body, but still needs a
+ // real currentNote/startNote to resolve a script bundle.
+ let scriptNoteId: string;
+
+ beforeAll(async () => {
+ scriptNoteId = await createCodeNote("return 0;");
+ });
+
+ it("executes a trivial script (non-transactional)", async () => {
+ const res = await api.post<ExecResponse>("/api/script/exec", {
+ body: {
+ script: "() => 1+1",
+ params: [],
+ startNoteId: scriptNoteId,
+ currentNoteId: scriptNoteId,
+ transactional: false
+ }
+ });
+ expect(res.status).toBe(200);
+ expect(res.body.success).toBe(true);
+ expect(res.body.executionResult).toBe(2);
+ });
+
+ it("executes a trivial script (transactional)", async () => {
+ const res = await api.post<ExecResponse>("/api/script/exec", {
+ body: {
+ script: "() => 3*3",
+ params: [],
+ startNoteId: scriptNoteId,
+ currentNoteId: scriptNoteId,
+ transactional: true
+ }
+ });
+ expect(res.status).toBe(200);
+ expect(res.body.success).toBe(true);
+ expect(res.body.executionResult).toBe(9);
+ });
+
+ it("returns success:false when the script throws", async () => {
+ const res = await api.post<ExecResponse>("/api/script/exec", {
+ body: {
+ script: "() => { throw new Error('boom'); }",
+ params: [],
+ startNoteId: scriptNoteId,
+ currentNoteId: scriptNoteId,
+ transactional: false
+ }
+ });
+ expect(res.status).toBe(200);
+ expect(res.body.success).toBe(false);
+ expect(res.body.error).toBeTruthy();
+ });
+ });
+
+ describe("run", () => {
+ it("runs a code note via executeNote", async () => {
+ const noteId = await createCodeNote("return 42;");
+ const spy = vi.spyOn(scriptService, "executeNote").mockReturnValue(123 as any);
+
+ const res = await api.post<{ executionResult: unknown }>(`/api/script/run/${noteId}`);
+ expect(res.status).toBe(200);
+ expect(res.body.executionResult).toBe(123);
+ expect(spy).toHaveBeenCalledOnce();
+ });
+ });
+
+ describe("startup bundles", () => {
+ it("returns frontend startup bundles (desktop)", async () => {
+ const note = (await createTextNote(api)).noteId;
+ vi.spyOn(attributeService, "getNotesWithLabel").mockReturnValue([{ noteId: note } as any]);
+ vi.spyOn(scriptService, "getScriptBundleForFrontend").mockReturnValue({ script: "x" } as any);
+
+ const res = await api.get<unknown[]>("/api/script/startup");
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual([{ script: "x" }]);
+ });
+
+ it("returns mobile startup bundles, filtering out empty bundles", async () => {
+ vi.spyOn(attributeService, "getNotesWithLabel").mockReturnValue([
+ { noteId: "a" } as any,
+ { noteId: "b" } as any
+ ]);
+ vi.spyOn(scriptService, "getScriptBundleForFrontend").mockImplementation(
+ (n: any) => (n.noteId === "a" ? ({ script: "a" } as any) : undefined)
+ );
+
+ const res = await api.get<unknown[]>("/api/script/startup", { query: { mobile: "true" } });
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual([{ script: "a" }]);
+ });
+
+ it("returns no bundles in safe mode", async () => {
+ vi.stubEnv("TRILIUM_SAFE_MODE", "1");
+ try {
+ const res = await api.get<unknown[]>("/api/script/startup");
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual([]);
+ } finally {
+ vi.unstubAllEnvs();
+ }
+ });
+ });
+
+ describe("widget bundles", () => {
+ it("returns widget bundles when not in safe mode", async () => {
+ vi.spyOn(attributeService, "getNotesWithLabel").mockReturnValue([{ noteId: "w" } as any]);
+ vi.spyOn(scriptService, "getScriptBundleForFrontend").mockReturnValue({ script: "w" } as any);
+
+ const res = await api.get<unknown[]>("/api/script/widgets");
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual([{ script: "w" }]);
+ });
+
+ it("returns no widget bundles in safe mode", async () => {
+ vi.stubEnv("TRILIUM_SAFE_MODE", "1");
+ try {
+ const res = await api.get<unknown[]>("/api/script/widgets");
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual([]);
+ } finally {
+ vi.unstubAllEnvs();
+ }
+ });
+ });
+
+ describe("relation bundles", () => {
+ it("collects frontend-JS relation targets and skips others", async () => {
+ const frontendTarget = await createCodeNote("return 1;");
+ const { noteId: textTarget } = await createTextNote(api);
+ const { noteId: hostId } = await createTextNote(api);
+
+ // Two relations: one to a frontend-JS note, one to a plain text note (filtered out).
+ await api.post(`/api/notes/${hostId}/attributes`, {
+ body: { type: "relation", name: "runOnInstance", value: frontendTarget }
+ });
+ await api.post(`/api/notes/${hostId}/attributes`, {
+ body: { type: "relation", name: "runOnInstance", value: textTarget }
+ });
+
+ vi.spyOn(scriptService, "getScriptBundleForFrontend").mockReturnValue({ script: "rel" } as any);
+
+ const res = await api.get<unknown[]>(`/api/script/relation/${hostId}/runOnInstance`);
+ expect(res.status).toBe(200);
+ // Only the frontend-JS target yields a bundle.
+ expect(res.body).toEqual([{ script: "rel" }]);
+ });
+ });
+
+ describe("getBundle", () => {
+ it("returns a bundle for a code note without body override", async () => {
+ const noteId = await createCodeNote("return 1;");
+ vi.spyOn(scriptService, "getScriptBundleForFrontend").mockReturnValue({ script: "b" } as any);
+
+ const res = await api.post<unknown>(`/api/script/bundle/${noteId}`);
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual({ script: "b" });
+ expect(scriptService.getScriptBundleForFrontend).toHaveBeenCalledWith(
+ expect.anything(),
+ undefined,
+ undefined
+ );
+ });
+
+ it("returns a bundle using the script/params from the body", async () => {
+ const noteId = await createCodeNote("return 1;");
+ const spy = vi
+ .spyOn(scriptService, "getScriptBundleForFrontend")
+ .mockReturnValue({ script: "override" } as any);
+
+ const res = await api.post<unknown>(`/api/script/bundle/${noteId}`, {
+ body: { script: "() => 5", params: [1, 2] }
+ });
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual({ script: "override" });
+ expect(spy).toHaveBeenCalledWith(expect.anything(), "() => 5", [1, 2]);
+ });
+ });
+});
diff --git a/packages/trilium-core/src/routes/api/search.spec.ts b/packages/trilium-core/src/routes/api/search.spec.ts
index 59681f1887..7711a53aab 100644
--- a/packages/trilium-core/src/routes/api/search.spec.ts
+++ b/packages/trilium-core/src/routes/api/search.spec.ts
@@ -30,10 +30,16 @@ describe("Search API (core)", () => {
expect(Array.isArray(res.body.searchResults)).toBe(true);
});
- it("lists template note ids", async () => {
- const res = await api.get("/api/search-templates");
+ it("lists template note ids including a freshly-labelled template", async () => {
+ const { noteId } = await createTextNote(api, { title: "A template note" });
+ await api.post(`/api/notes/${noteId}/attributes`, {
+ body: { type: "label", name: "template", value: "" }
+ });
+
+ const res = await api.get<string[]>("/api/search-templates");
expect(res.status).toBe(200);
expect(Array.isArray(res.body)).toBe(true);
+ expect(res.body).toContain(noteId);
});
it("400s when searching from a note that is not a search note", async () => {
@@ -49,4 +55,47 @@ describe("Search API (core)", () => {
expect(typeof res.body.count).toBe("number");
expect(Array.isArray(res.body.results)).toBe(true);
});
+
+ it("caps related-note results at 20 even with many matches", async () => {
+ // Create more than 20 notes carrying the same label so the result loop
+ // hits its >= 20 break.
+ for (let i = 0; i < 22; i++) {
+ const { noteId } = await createTextNote(api, { title: `Related ${i}` });
+ await api.post(`/api/notes/${noteId}/attributes`, {
+ body: { type: "label", name: "relTestLabel", value: "relTestValue" }
+ });
+ }
+
+ const res = await api.post<{ count: number; results: unknown[] }>("/api/search-related", {
+ body: { type: "label", name: "relTestLabel", value: "relTestValue" }
+ });
+ expect(res.status).toBe(200);
+ expect(res.body.count).toBeGreaterThanOrEqual(22);
+ expect(res.body.results).toHaveLength(20);
+ });
+
+ it("runs a saved search note and executes bulk actions over it", async () => {
+ const created = await api.post<{ noteId: string; type: string }>(
+ "/api/special-notes/search-note",
+ { body: { searchString: UNIQUE_TOKEN } }
+ );
+ expect(created.body.type).toBe("search");
+ const searchNoteId = created.body.noteId;
+
+ const fromNote = await api.get<{ searchResultNoteIds: string[] }>(
+ `/api/search-note/${searchNoteId}`
+ );
+ expect(fromNote.status).toBe(200);
+ expect(fromNote.body.searchResultNoteIds).toContain(createdNoteId);
+
+ // searchAndExecute returns no body (204) — the note has no action labels,
+ // so executing over the results is a safe no-op.
+ const exec = await api.post(`/api/search-and-execute-note/${searchNoteId}`);
+ expect(exec.status).toBe(204);
+ });
+
+ it("400s when executing a note that is not a search note", async () => {
+ const res = await api.post("/api/search-and-execute-note/root");
+ expect(res.status).toBe(400);
+ });
});
diff --git a/packages/trilium-core/src/routes/api/search.ts b/packages/trilium-core/src/routes/api/search.ts
index bd2491f9af..01bab721ec 100644
--- a/packages/trilium-core/src/routes/api/search.ts
+++ b/packages/trilium-core/src/routes/api/search.ts
@@ -14,6 +14,7 @@ import { getHoistedNoteId } from "../../services/context.js";
function searchFromNote(req: Request<{ noteId: string }>): SearchNoteResult {
const note = becca.getNoteOrThrow(req.params.noteId);
+ /* v8 ignore next 4 -- unreachable: getNoteOrThrow already throws on a missing note */
if (!note) {
// this can be triggered from recent changes, and it's harmless to return an empty list rather than fail
return EMPTY_RESULT;
@@ -29,6 +30,7 @@ function searchFromNote(req: Request<{ noteId: string }>): SearchNoteResult {
function searchAndExecute(req: Request<{ noteId: string }>) {
const note = becca.getNoteOrThrow(req.params.noteId);
+ /* v8 ignore next 4 -- unreachable: getNoteOrThrow already throws on a missing note */
if (!note) {
// this can be triggered from recent changes, and it's harmless to return an empty list rather than fail
return [];
diff --git a/packages/trilium-core/src/routes/api/setup.spec.ts b/packages/trilium-core/src/routes/api/setup.spec.ts
new file mode 100644
index 0000000000..7d43ad04aa
--- /dev/null
+++ b/packages/trilium-core/src/routes/api/setup.spec.ts
@@ -0,0 +1,80 @@
+import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
+
+import appInfo from "../../services/app_info";
+import setupService from "../../services/setup";
+import sqlInit from "../../services/sql_init";
+import { CoreApiTester } from "../../test/api_tester";
+
+/**
+ * Drives the shared core setup routes through {@link CoreApiTester} (no
+ * Express), so this spec runs under both the node and standalone (WASM) suites.
+ *
+ * The mutating handlers (new-document, sync-seed, sync-from-server) are stubbed
+ * via `vi.spyOn` so they don't wipe/replace the in-memory fixture DB.
+ */
+let api: CoreApiTester;
+
+describe("Setup API (core)", () => {
+ beforeAll(() => {
+ api = CoreApiTester.build();
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it("returns the setup status shape", async () => {
+ const res = await api.get<{ isInitialized: boolean; schemaExists: boolean; syncVersion: number }>(
+ "/api/setup/status"
+ );
+ expect(res.status).toBe(200);
+ expect(typeof res.body.isInitialized).toBe("boolean");
+ expect(typeof res.body.schemaExists).toBe("boolean");
+ expect(res.body.syncVersion).toBe(appInfo.syncVersion);
+ });
+
+ it("creates a new document (createInitialDatabase stubbed)", async () => {
+ const createInitial = vi.spyOn(sqlInit, "createInitialDatabase").mockResolvedValue(undefined);
+ const res = await api.post("/api/setup/new-document", { query: { skipDemoDb: "1" } });
+ expect(res.status).toBe(204);
+ expect(createInitial).toHaveBeenCalledWith(true);
+ });
+
+ it("returns the sync seed shape", async () => {
+ const res = await api.get<{ options: unknown; syncVersion: number }>("/api/setup/sync-seed");
+ expect(res.status).toBe(200);
+ expect(res.body.syncVersion).toBe(appInfo.syncVersion);
+ expect(res.body.options).toBeDefined();
+ });
+
+ it("rejects saving a sync seed with a mismatched sync version (400)", async () => {
+ const createForSync = vi.spyOn(sqlInit, "createDatabaseForSync").mockResolvedValue(undefined as never);
+ const res = await api.post<{ error: string }>("/api/setup/sync-seed", {
+ body: { syncVersion: 999999, options: [] }
+ });
+ expect(res.status).toBe(400);
+ expect(res.body.error).toBeTruthy();
+ expect(createForSync).not.toHaveBeenCalled();
+ });
+
+ it("saves a sync seed with a matching sync version (createDatabaseForSync stubbed)", async () => {
+ const createForSync = vi.spyOn(sqlInit, "createDatabaseForSync").mockResolvedValue(undefined as never);
+ const res = await api.post("/api/setup/sync-seed", {
+ body: { syncVersion: appInfo.syncVersion, options: [] }
+ });
+ expect(res.status).toBe(204);
+ expect(createForSync).toHaveBeenCalledWith([]);
+ });
+
+ it("sets up sync from the sync server (setupSyncFromSyncServer stubbed)", async () => {
+ const setupSync = vi
+ .spyOn(setupService, "setupSyncFromSyncServer")
+ .mockResolvedValue({ result: "success" });
+ const res = await api.post<{ result: string }>("/api/setup/sync-from-server", {
+ body: { syncServerHost: "http://host", syncProxy: "", password: "pw" }
+ });
+ expect(res.status).toBe(200);
+ expect(res.body.result).toBe("success");
+ expect(setupSync).toHaveBeenCalledWith("http://host", "", "pw");
+ });
+});
diff --git a/packages/trilium-core/src/routes/api/special_notes.spec.ts b/packages/trilium-core/src/routes/api/special_notes.spec.ts
index e2bf92c76c..38c312f354 100644
--- a/packages/trilium-core/src/routes/api/special_notes.spec.ts
+++ b/packages/trilium-core/src/routes/api/special_notes.spec.ts
@@ -47,6 +47,41 @@ describe("Special notes API (core)", () => {
expect(res.body.noteId).toBeTruthy();
});
+ it("returns the week note (null unless week notes are enabled)", async () => {
+ const res = await api.get<NotePojo | null>("/api/special-notes/weeks/2025-W03");
+ expect(res.status).toBe(200);
+ // Week notes require `enableWeekNote` on the calendar root, which the
+ // demo fixture does not set, so the handler returns null here.
+ expect(res.body === null || typeof res.body.noteId === "string").toBe(true);
+ });
+
+ it("returns the day note scoped to an explicit calendar root", async () => {
+ const res = await api.get<NotePojo>("/api/special-notes/days/2025-02-10", {
+ query: { calendarRootId: "root" }
+ });
+ expect(res.status).toBe(200);
+ expect(res.body.noteId).toBeTruthy();
+ });
+
+ it("returns a filtered map of day notes for a month with a calendar root", async () => {
+ const created = await api.get<NotePojo>("/api/special-notes/days/2025-03-05");
+
+ const res = await api.get<Record<string, string>>(
+ "/api/special-notes/notes-for-month/2025-03",
+ { query: { calendarRoot: "root" } }
+ );
+ expect(res.status).toBe(200);
+ expect(res.body["2025-03-05"]).toBe(created.body.noteId);
+
+ // A calendar root that is not an ancestor filters everything out.
+ const none = await api.get<Record<string, string>>(
+ "/api/special-notes/notes-for-month/2025-03",
+ { query: { calendarRoot: "_hidden" } }
+ );
+ expect(none.status).toBe(200);
+ expect(none.body["2025-03-05"]).toBeUndefined();
+ });
+
it("returns the month note", async () => {
const res = await api.get<NotePojo>("/api/special-notes/months/2025-01");
expect(res.status).toBe(200);
@@ -130,5 +165,66 @@ describe("Special notes API (core)", () => {
});
expect(res.status).toBe(500);
});
+
+ it("creates a search note defaulting the ancestor to the hoisted note", async () => {
+ const res = await api.post<NotePojo>("/api/special-notes/search-note", {
+ body: {}
+ });
+ expect(res.status).toBe(200);
+ expect(res.body.type).toBe("search");
+ });
+ });
+
+ describe("launchers", () => {
+ it("creates a launcher under a parent and resets it", async () => {
+ const created = await api.post<{ success: boolean; note: NotePojo }>(
+ "/api/special-notes/launchers/_lbVisibleLaunchers/note"
+ );
+ expect(created.status).toBe(200);
+ expect(created.body.success).toBe(true);
+ expect(created.body.note.noteId).toBeTruthy();
+
+ const reset = await api.post(
+ `/api/special-notes/launchers/${created.body.note.noteId}/reset`
+ );
+ // resetLauncher returns nothing, so the result handler maps it to 204.
+ expect(reset.status).toBe(204);
+ });
+
+ it("creates or updates a script launcher from the API", async () => {
+ const res = await api.put<NotePojo>("/api/special-notes/api-script-launcher", {
+ body: {
+ id: "specLauncher1",
+ title: "Spec launcher",
+ action: "() => console.log('hi')",
+ icon: "bx-home",
+ shortcut: "ctrl+alt+s"
+ }
+ });
+ expect(res.status).toBe(200);
+ expect(res.body.title).toBe("Spec launcher");
+
+ // Update path: same id, now without icon/shortcut (exercises the remove branches).
+ const update = await api.put<NotePojo>("/api/special-notes/api-script-launcher", {
+ body: {
+ id: "specLauncher1",
+ title: "Spec launcher renamed",
+ action: "() => 1"
+ }
+ });
+ expect(update.status).toBe(200);
+ expect(update.body.title).toBe("Spec launcher renamed");
+ });
+
+ // Destructive: deletes _lbRoot's children, so keep this last in the file.
+ it("resets a launchbar root by clearing its children, and ignores non-launchers", async () => {
+ // _lbRoot is a protected launchbar config root → children are reset.
+ const rootReset = await api.post("/api/special-notes/launchers/_lbRoot/reset");
+ expect(rootReset.status).toBe(204);
+
+ // root is not a launcher → the no-op branch.
+ const nonLauncher = await api.post("/api/special-notes/launchers/root/reset");
+ expect(nonLauncher.status).toBe(204);
+ });
});
});
diff --git a/packages/trilium-core/src/routes/api/sql.spec.ts b/packages/trilium-core/src/routes/api/sql.spec.ts
index f1df2788b3..5d5553b9e8 100644
--- a/packages/trilium-core/src/routes/api/sql.spec.ts
+++ b/packages/trilium-core/src/routes/api/sql.spec.ts
@@ -1,5 +1,7 @@
-import { beforeAll, describe, expect, it } from "vitest";
+import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
+import becca from "../../becca/becca";
+import { getSql } from "../../services/sql/index";
import { createTextNote } from "../../test/api_fixtures";
import { CoreApiTester } from "../../test/api_tester";
@@ -41,6 +43,10 @@ describe("SQL API (core)", () => {
});
describe("execute", () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
it("runs a SELECT query from a note body and returns the rows", async () => {
const { noteId } = await createTextNote(api, {
title: "SQL console",
@@ -81,6 +87,38 @@ describe("SQL API (core)", () => {
expect(typeof res.body.error).toBe("string");
});
+ it("strips leading SQL comments, skips empty queries and runs non-SELECT statements", async () => {
+ // Exercises the comment-stripping loop, the empty-query `continue`,
+ // and the non-SELECT (`else`) execution branch in one note body.
+ getSql().execute("CREATE TABLE IF NOT EXISTS sql_spec_tmp (id INTEGER)");
+ const { noteId } = await createTextNote(api, {
+ title: "SQL console comments",
+ content: [
+ "-- a leading comment\n-- and another\nDELETE FROM sql_spec_tmp",
+ " ",
+ "WITH x AS (SELECT 1 AS n) SELECT n FROM x"
+ ].join("\n---")
+ });
+
+ const res = await api.post<ExecuteResult>(`/api/sql/execute/${noteId}`);
+ expect(res.status).toBe(200);
+ expect(res.body.success).toBe(true);
+ // The blank middle query is skipped, so only two results are returned.
+ expect(res.body.results).toHaveLength(2);
+
+ getSql().execute("DROP TABLE sql_spec_tmp");
+ });
+
+ it("rejects a note whose content is not a string", async () => {
+ const { noteId } = await createTextNote(api, { title: "Binary content" });
+ const note = becca.getNoteOrThrow(noteId);
+ vi.spyOn(note, "getContent").mockReturnValue(new Uint8Array([ 1, 2, 3 ]));
+ vi.spyOn(becca, "getNoteOrThrow").mockReturnValue(note);
+
+ const res = await api.post<{ message: string }>(`/api/sql/execute/${noteId}`);
+ expect(res.status).toBe(400);
+ });
+
it("404s when the note does not exist", async () => {
const res = await api.post("/api/sql/execute/missingNote123");
expect(res.status).toBe(404);
diff --git a/packages/trilium-core/src/routes/api/sync.spec.ts b/packages/trilium-core/src/routes/api/sync.spec.ts
new file mode 100644
index 0000000000..69ca7f7fdb
--- /dev/null
+++ b/packages/trilium-core/src/routes/api/sync.spec.ts
@@ -0,0 +1,239 @@
+import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
+
+import consistencyChecksService from "../../services/consistency_checks";
+import entityChangesService from "../../services/entity_changes";
+import optionService from "../../services/options";
+import { getSql } from "../../services/sql/index";
+import sqlInit from "../../services/sql_init";
+import syncService from "../../services/sync";
+import syncOptions from "../../services/sync_options";
+import syncUpdateService from "../../services/sync_update";
+import ws from "../../services/ws";
+import { CoreApiTester } from "../../test/api_tester";
+
+/**
+ * Drives the shared core sync routes through {@link CoreApiTester} (no Express),
+ * so this spec runs under both the node (better-sqlite3) and standalone (WASM)
+ * suites. Network-doing handlers (login/sync) are stubbed via `vi.spyOn`.
+ */
+let api: CoreApiTester;
+
+describe("Sync API (core)", () => {
+ beforeAll(() => {
+ api = CoreApiTester.build();
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ describe("testSync (POST /api/sync/test)", () => {
+ it("reports not-configured when sync is not set up", async () => {
+ // On the fixture, isSyncSetup() is false → the early not-configured branch.
+ const res = await api.post<{ success: boolean; message: string }>("/api/sync/test");
+ expect(res.status).toBe(200);
+ expect(res.body.success).toBe(false);
+ expect(typeof res.body.message).toBe("string");
+ });
+
+ it("logs in and kicks off sync when configured", async () => {
+ vi.spyOn(syncOptions, "isSyncSetup").mockReturnValue(true);
+ const login = vi.spyOn(syncService, "login").mockResolvedValue({} as never);
+ const sync = vi.spyOn(syncService, "sync").mockResolvedValue(undefined as never);
+
+ const res = await api.post<{ success: boolean }>("/api/sync/test");
+ expect(res.status).toBe(200);
+ expect(res.body.success).toBe(true);
+ expect(login).toHaveBeenCalled();
+ expect(sync).toHaveBeenCalled();
+ });
+
+ it("returns the error message when login fails", async () => {
+ vi.spyOn(syncOptions, "isSyncSetup").mockReturnValue(true);
+ vi.spyOn(syncService, "login").mockRejectedValue(new Error("boom"));
+
+ const res = await api.post<{ success: boolean; message: string }>("/api/sync/test");
+ expect(res.status).toBe(200);
+ expect(res.body.success).toBe(false);
+ expect(res.body.message).toContain("boom");
+ });
+ });
+
+ describe("getStats (GET /api/sync/stats)", () => {
+ it("returns sync stats in the normal case", async () => {
+ vi.spyOn(syncService, "getOutstandingPullCount").mockReturnValue(3);
+ vi.spyOn(syncService, "getTotalPullCount").mockReturnValue(7);
+
+ const res = await api.get<{ initialized: boolean; outstandingPullCount: number; totalPullCount: number }>("/api/sync/stats");
+ expect(res.status).toBe(200);
+ expect(res.body.outstandingPullCount).toBe(3);
+ expect(res.body.totalPullCount).toBe(7);
+ expect(typeof res.body.initialized).toBe("boolean");
+ });
+
+ it("returns an empty object when the schema does not exist", async () => {
+ vi.spyOn(sqlInit, "schemaExists").mockReturnValue(false);
+
+ const res = await api.get<Record<string, never>>("/api/sync/stats");
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual({});
+ });
+ });
+
+ it("checkSync returns entity hashes and the max entity change id", async () => {
+ const res = await api.get<{ entityHashes: unknown; maxEntityChangeId: number }>("/api/sync/check");
+ expect(res.status).toBe(200);
+ expect(res.body).toHaveProperty("entityHashes");
+ expect(typeof res.body.maxEntityChangeId).toBe("number");
+ });
+
+ it("syncNow signals progress and returns the sync result", async () => {
+ const progress = vi.spyOn(ws, "syncPullInProgress").mockImplementation(() => {});
+ vi.spyOn(syncService, "sync").mockResolvedValue("sync-result" as never);
+
+ const res = await api.post<string>("/api/sync/now");
+ expect(res.status).toBe(200);
+ expect(progress).toHaveBeenCalled();
+ expect(res.body).toBe("sync-result");
+ });
+
+ it("fillEntityChanges triggers fillAllEntityChanges", async () => {
+ const fill = vi.spyOn(entityChangesService, "fillAllEntityChanges").mockImplementation(() => {});
+
+ const res = await api.post("/api/sync/fill-entity-changes");
+ expect(res.status).toBe(204);
+ expect(fill).toHaveBeenCalled();
+ });
+
+ it("forceFullSync resets the sync pointers and triggers a sync", async () => {
+ const setOption = vi.spyOn(optionService, "setOption").mockImplementation(() => {});
+ const sync = vi.spyOn(syncService, "sync").mockResolvedValue(undefined as never);
+
+ const res = await api.post("/api/sync/force-full-sync");
+ expect(res.status).toBe(204);
+ expect(setOption).toHaveBeenCalledWith("lastSyncedPull", 0);
+ expect(setOption).toHaveBeenCalledWith("lastSyncedPush", 0);
+ expect(sync).toHaveBeenCalled();
+ });
+
+ describe("getChanged (GET /api/sync/changed)", () => {
+ it("rejects a missing/invalid lastEntityChangeId", async () => {
+ const res = await api.get<{ message: string }>("/api/sync/changed");
+ expect(res.status).toBe(400);
+ });
+
+ it("returns entity change records for the normal branch", async () => {
+ const res = await api.get<{ entityChanges: unknown[]; lastEntityChangeId: number; outstandingPullCount: number }>(
+ "/api/sync/changed",
+ { query: { instanceId: "someOtherInstance", lastEntityChangeId: "0" } }
+ );
+ expect(res.status).toBe(200);
+ expect(Array.isArray(res.body.entityChanges)).toBe(true);
+ expect(res.body.entityChanges.length).toBeGreaterThan(0);
+ expect(typeof res.body.outstandingPullCount).toBe("number");
+ });
+
+ it("advances past batches that are fully filtered out by instanceId", async () => {
+ // Seed a contiguous block of synced rows beyond the existing max id, all
+ // belonging to a single instanceId. Querying with that instanceId and a
+ // lastEntityChangeId just below the block makes the first batch consist
+ // ENTIRELY of filtered-out rows → exercises the do/while advance branch.
+ const sql = getSql();
+ const maxId = sql.getValue<number>("SELECT COALESCE(MAX(id), 0) FROM entity_changes");
+ const baseId = maxId + 1;
+ for (let i = 0; i < 3; i++) {
+ sql.execute(
+ `INSERT INTO entity_changes (id, entityName, entityId, hash, isErased, changeId, componentId, instanceId, isSynced, utcDateChanged)
+ VALUES (?, 'options', ?, 'h', 0, ?, 'cmp', 'LOOPTEST', 1, '2020-01-01T00:00:00.000Z')`,
+ [baseId + i, `loop_${i}`, `chg_${i}`]
+ );
+ }
+
+ const res = await api.get<{ entityChanges: unknown[]; lastEntityChangeId: number; outstandingPullCount: number }>(
+ "/api/sync/changed",
+ { query: { instanceId: "LOOPTEST", lastEntityChangeId: String(maxId) } }
+ );
+ expect(res.status).toBe(200);
+ // Every row in range belongs to LOOPTEST, so all are filtered out.
+ expect(res.body.entityChanges).toEqual([]);
+ expect(res.body.lastEntityChangeId).toBe(baseId + 2);
+ expect(res.body.outstandingPullCount).toBe(0);
+ });
+ });
+
+ describe("update (PUT /api/sync/update)", () => {
+ it("applies a single-page push", async () => {
+ const update = vi.spyOn(syncUpdateService, "updateEntities").mockImplementation(() => {});
+
+ const res = await api.put("/api/sync/update", {
+ headers: { pageCount: "1", pageIndex: "0" },
+ body: { entities: [], instanceId: "x" }
+ });
+ expect(res.status).toBe(204);
+ expect(update).toHaveBeenCalledWith([], "x");
+ });
+
+ it("throws when a multi-page request has no request ID", async () => {
+ const res = await api.put<{ message: string }>("/api/sync/update", {
+ headers: { pageCount: "2", pageIndex: "0" },
+ body: ""
+ });
+ expect(res.status).toBe(500);
+ expect(res.body.message).toContain("Missing request ID");
+ });
+
+ it("accumulates paginated chunks and applies them on the last page", async () => {
+ const update = vi.spyOn(syncUpdateService, "updateEntities").mockImplementation(() => {});
+ const payload = JSON.stringify({ entities: [{ a: 1 }], instanceId: "y" });
+ const mid = Math.floor(payload.length / 2);
+
+ const first = await api.put("/api/sync/update", {
+ headers: { pageCount: "2", pageIndex: "0", requestId: "r1" },
+ body: payload.slice(0, mid)
+ });
+ // Not the last page yet → returns undefined (no body) and does not apply.
+ expect(first.status).toBe(204);
+ expect(update).not.toHaveBeenCalled();
+
+ const last = await api.put("/api/sync/update", {
+ headers: { pageCount: "2", pageIndex: "1", requestId: "r1" },
+ body: payload.slice(mid)
+ });
+ expect(last.status).toBe(204);
+ expect(update).toHaveBeenCalledWith([{ a: 1 }], "y");
+ });
+
+ it("throws when a continuation page has no initialized record", async () => {
+ const res = await api.put<{ message: string }>("/api/sync/update", {
+ headers: { pageCount: "2", pageIndex: "1", requestId: "rX" },
+ body: "chunk"
+ });
+ expect(res.status).toBe(500);
+ expect(res.body.message).toContain("does not have expected record");
+ });
+ });
+
+ it("syncFinished marks the database as initialized", async () => {
+ const setInit = vi.spyOn(sqlInit, "setDbAsInitialized").mockImplementation(() => {});
+
+ const res = await api.post("/api/sync/finished");
+ expect(res.status).toBe(204);
+ expect(setInit).toHaveBeenCalled();
+ });
+
+ it("queueSector adds entity changes for the sector", async () => {
+ const add = vi.spyOn(entityChangesService, "addEntityChangesForSector").mockImplementation(() => {});
+
+ const res = await api.post("/api/sync/queue-sector/notes/a");
+ expect(res.status).toBe(204);
+ expect(add).toHaveBeenCalledWith("notes", "a");
+ });
+
+ it("checkEntityChanges runs the consistency checks", async () => {
+ const check = vi.spyOn(consistencyChecksService, "runEntityChangesChecks").mockImplementation(() => {});
+
+ const res = await api.post("/api/sync/check-entity-changes");
+ expect(res.status).toBe(204);
+ expect(check).toHaveBeenCalled();
+ });
+});
diff --git a/packages/trilium-core/src/routes/api/sync.ts b/packages/trilium-core/src/routes/api/sync.ts
index d32ed3fd37..9250b251c4 100644
--- a/packages/trilium-core/src/routes/api/sync.ts
+++ b/packages/trilium-core/src/routes/api/sync.ts
@@ -298,6 +298,7 @@ function update(req: Request) {
getSql().transactional(() => syncUpdateService.updateEntities(entities, instanceId));
}
+/* v8 ignore start -- module-level timer, not invoked in tests */
setInterval(() => {
for (const key in partialRequests) {
if (Date.now() - partialRequests[key].createdAt > 20 * 60 * 1000) {
@@ -307,6 +308,7 @@ setInterval(() => {
}
}
}, 60 * 1000);
+/* v8 ignore stop */
function syncFinished() {
// after the first sync finishes, the application is ready to be used
diff --git a/packages/trilium-core/src/routes/api/tree.spec.ts b/packages/trilium-core/src/routes/api/tree.spec.ts
index 0c1686246a..9c33b754fa 100644
--- a/packages/trilium-core/src/routes/api/tree.spec.ts
+++ b/packages/trilium-core/src/routes/api/tree.spec.ts
@@ -1,5 +1,7 @@
-import { beforeAll, describe, expect, it } from "vitest";
+import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
+import becca from "../../becca/becca";
+import { createTextNote } from "../../test/api_fixtures";
import { CoreApiTester } from "../../test/api_tester";
/**
@@ -50,4 +52,53 @@ describe("Tree API (core)", () => {
expect(res.status).toBe(200);
expect(res.body.notes.some((n) => n.noteId === "root")).toBe(true);
});
+
+ describe("edge cases", () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it("skips requested note ids that are not in the cache", async () => {
+ // Hits the `if (!note) continue` guard while still returning the valid ones.
+ const res = await api.post<TreeResponse>("/api/tree/load", {
+ body: { noteIds: [ "root", "doesNotExist123" ] }
+ });
+ expect(res.status).toBe(200);
+ expect(res.body.notes.some((n) => n.noteId === "root")).toBe(true);
+ expect(res.body.notes.some((n) => n.noteId === "doesNotExist123")).toBe(false);
+ });
+
+ it("skips a collected branch id that is missing from the cache", async () => {
+ // Force a dangling branchId into the collection (via the child-branch
+ // lookup in collectEntityIds) so the `becca.branches[branchId]` lookup
+ // misses and the guard runs. Use `load` so getTree's own collect()
+ // recursion (which needs a real childNote) isn't affected.
+ const original = becca.getBranchFromChildAndParent.bind(becca);
+ vi.spyOn(becca, "getBranchFromChildAndParent").mockImplementation((childNoteId, parentNoteId) => {
+ const branch = original(childNoteId, parentNoteId);
+ if (branch) {
+ Object.defineProperty(branch, "branchId", { value: "ghostBranch123", configurable: true });
+ }
+ return branch;
+ });
+
+ const res = await api.post<TreeResponse>("/api/tree/load", { body: { noteIds: [ "root" ] } });
+ expect(res.status).toBe(200);
+ expect(res.body.branches.some((b) => b.branchId === "ghostBranch123")).toBe(false);
+ });
+
+ it("skips a collected attribute id that is missing from the cache", async () => {
+ const { noteId } = await createTextNote(api, { title: "Note with ghost attribute" });
+ const note = becca.notes[noteId];
+ // Replace the note's owned attributes with one whose id is absent from becca.attributes.
+ vi.spyOn(note, "ownedAttributes", "get").mockReturnValue([
+ { attributeId: "ghostAttr123", type: "label", name: "x", targetNote: undefined } as never
+ ]);
+
+ const res = await api.post<TreeResponse>("/api/tree/load", { body: { noteIds: [ noteId ] } });
+ expect(res.status).toBe(200);
+ const attrs = res.body.attributes as { attributeId?: string }[];
+ expect(attrs.some((a) => a.attributeId === "ghostAttr123")).toBe(false);
+ });
+ });
});
diff --git a/packages/trilium-core/src/routes/api/tree.ts b/packages/trilium-core/src/routes/api/tree.ts
index 3b27f6d2e4..3ef73ce47c 100644
--- a/packages/trilium-core/src/routes/api/tree.ts
+++ b/packages/trilium-core/src/routes/api/tree.ts
@@ -172,6 +172,7 @@ function getTree(req: Request) {
const collectedNoteIds = new Set<string>([subTreeNoteId]);
function collect(parentNote: BNote) {
+ /* v8 ignore next 3 -- defensive guard: collect() is only ever called with a cache-verified note */
if (!parentNote) {
console.trace(parentNote);
}
diff --git a/packages/trilium-core/src/test/api_tester.ts b/packages/trilium-core/src/test/api_tester.ts
index 946eb3e8f7..7ffc4e1438 100644
--- a/packages/trilium-core/src/test/api_tester.ts
+++ b/packages/trilium-core/src/test/api_tester.ts
@@ -1,3 +1,5 @@
+import { Writable } from "node:stream";
+
import { HttpError } from "../errors";
import * as routes from "../routes";
import { getContext } from "../services/context";
@@ -41,6 +43,8 @@ interface ApiRequest {
method: string;
file?: unknown;
originalUrl: string;
+ /** Express-style case-insensitive header accessor (used by e.g. the sync routes). */
+ get(name: string): string | undefined;
}
interface RegisteredRoute {
@@ -60,6 +64,12 @@ export interface RequestOptions {
body?: unknown;
query?: Record<string, string | number | boolean | undefined>;
headers?: Record<string, string>;
+ /**
+ * A fake uploaded file, mirroring the `req.file` that the Express multipart
+ * middleware would populate. Lets handlers that read `req.file` (image
+ * update, import) be exercised in-process without a real multipart request.
+ */
+ file?: unknown;
}
function pathToRegex(path: string): { pattern: RegExp; paramNames: string[] } {
@@ -107,29 +117,68 @@ interface CaptureResponse {
setHeader(name: string, value: string): void;
}
-/** A minimal Express-like response for handlers that write directly (e.g. image routes). */
-interface MockResponse {
- used: boolean;
- status(code: number): MockResponse;
- set(name: string, value: string): MockResponse;
- setHeader(name: string, value: string): MockResponse;
- send(body: unknown): MockResponse;
- sendStatus(code: number): MockResponse;
+/** Preserves strings and raw bytes as-is; JSON round-trips everything else. */
+function normalizeResponseBody(body: unknown): unknown {
+ if (body === undefined || typeof body === "string") {
+ return body;
+ }
+ if (Buffer.isBuffer(body) || body instanceof Uint8Array) {
+ return Buffer.from(body as Uint8Array);
+ }
+ return jsonRoundTrip(body);
}
-function createMockResponse(): MockResponse & { snapshot(): TestResponse } {
- const headers: Record<string, string> = {};
- const state = { status: 200, body: undefined as unknown };
- const res: MockResponse & { snapshot(): TestResponse } = {
- used: false,
- status(code) { state.status = code; return res; },
- set(name, value) { headers[name] = value; return res; },
- setHeader(name, value) { headers[name] = value; return res; },
- send(body) { res.used = true; state.body = body; return res; },
- sendStatus(code) { res.used = true; state.status = code; return res; },
- snapshot() { return { status: state.status, headers, body: jsonRoundTrip(state.body) }; }
- };
- return res;
+/**
+ * A faithful in-process stand-in for the Express `res` that handlers write to
+ * directly (image routes, file downloads, the streaming export). It extends a
+ * Node {@link Writable} so the **server** export path works exactly as in
+ * production — `archive.pipe(res)` with the `archiver` package needs a real
+ * writable stream — while also supporting the **browser** export path, where
+ * `BrowserZipArchive.finalize()` calls `res.send(zipBytes)` (and falls back to
+ * `res.write()`/`res.end()`). Both vitest suites (server + standalone) run on
+ * Node, so a real stream is available under either runtime.
+ *
+ * On top of the stream it exposes the small Express surface the handlers use
+ * and captures a `{ status, headers, body }` snapshot, keeping the body as raw
+ * bytes for streamed/binary responses so tests can inspect them.
+ */
+class MockResponse extends Writable {
+
+ used = false;
+ statusCode = 200;
+ headers: Record<string, string> = {};
+
+ private chunks: Buffer[] = [];
+ private sendBody: unknown;
+ private hasSendBody = false;
+
+ status(code: number) { this.statusCode = code; return this; }
+ set(name: string, value: string) { this.headers[name] = value; return this; }
+ setHeader(name: string, value: string) { this.headers[name] = value; return this; }
+ removeHeader(name: string) { delete this.headers[name]; return this; }
+ send(body: unknown) { this.used = true; this.hasSendBody = true; this.sendBody = body; return this; }
+ sendStatus(code: number) { this.used = true; this.statusCode = code; return this; }
+
+ override _write(chunk: Buffer | Uint8Array | string, _encoding: BufferEncoding, callback: (error?: Error | null) => void) {
+ this.used = true;
+ this.chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as Uint8Array));
+ callback();
+ }
+
+ snapshot(): TestResponse {
+ let body: unknown;
+ if (this.chunks.length > 0) {
+ body = Buffer.concat(this.chunks);
+ } else if (this.hasSendBody) {
+ body = normalizeResponseBody(this.sendBody);
+ }
+ return { status: this.statusCode, headers: this.headers, body };
+ }
+
+}
+
+function createMockResponse(): MockResponse {
+ return new MockResponse();
}
export class CoreApiTester {
@@ -241,13 +290,21 @@ export class CoreApiTester {
params[name] = decodeURIComponent(match[i + 1]);
});
+ const headers = opts.headers ?? {};
+ const lowerHeaders: Record<string, string> = {};
+ for (const [ key, value ] of Object.entries(headers)) {
+ lowerHeaders[key.toLowerCase()] = value;
+ }
+
const req: ApiRequest = {
params,
query,
body: opts.body,
- headers: opts.headers ?? {},
+ headers,
method: upperMethod,
- originalUrl: url.pathname + url.search
+ originalUrl: url.pathname + url.search,
+ file: opts.file,
+ get: (name: string) => lowerHeaders[name.toLowerCase()]
};
try {