Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
refactor(core): integrate server-side tests
Elian Doranc3584143a8f3
diff --git a/apps/server/src/routes/api/attributes.spec.ts b/apps/server/src/routes/api/attributes.spec.tsdeleted file mode 100644index dec66bd0af..0000000000--- a/apps/server/src/routes/api/attributes.spec.ts+++ /dev/null@@ -1,104 +0,0 @@-import { beforeAll, describe, expect, it } from "vitest";--import {- type ApiTestContext,- bootLoggedInApp,- createTextNote } from "../../../spec/support/internal_api.js";--let ctx: ApiTestContext;--interface AttrRow {- attributeId: string;- type: string;- name: string;- value: string;-}--describe("Attributes API", () => {- beforeAll(async () => {- ctx = await bootLoggedInApp();- });-- describe("reading", () => {- it("returns the effective attributes of a note", async () => {- const res = await ctx.agent.get("/api/notes/_hidden/attributes").expect(200);- const attrs = res.body as AttrRow[];- expect(Array.isArray(attrs)).toBe(true);- expect(attrs.some((a) => a.name === "docName")).toBe(true);- });-- it("returns attribute names filtered by type and query", async () => {- const res = await ctx.agent- .get("/api/attribute-names")- .query({ type: "label", query: "" })- .expect(200);- expect(Array.isArray(res.body)).toBe(true);- });-- it("400s when type/query params are missing", async () => {- await ctx.agent.get("/api/attribute-names").expect(400);- });-- it("returns distinct values for an attribute name", async () => {- const res = await ctx.agent.get("/api/attribute-values/docName").expect(200);- expect(Array.isArray(res.body)).toBe(true);- });- });-- describe("writing", () => {- it("adds a label, reads it back, then deletes it", async () => {- const { noteId } = await createTextNote(ctx);-- await ctx.agent- .post(`/api/notes/${noteId}/attributes`)- .set("x-csrf-token", ctx.csrfToken)- .send({ type: "label", name: "myLabel", value: "myValue" })- .expect(204);-- const afterAdd = await ctx.agent.get(`/api/notes/${noteId}/attributes`).expect(200);- const added = (afterAdd.body as AttrRow[]).find((a) => a.name === "myLabel");- expect(added).toMatchObject({ type: "label", value: "myValue" });-- await ctx.agent- .delete(`/api/notes/${noteId}/attributes/${added!.attributeId}`)- .set("x-csrf-token", ctx.csrfToken)- .expect(204);-- const afterDelete = await ctx.agent.get(`/api/notes/${noteId}/attributes`).expect(200);- const remainingIds = (afterDelete.body as AttrRow[]).map((a) => a.attributeId);- expect(remainingIds).not.toContain(added!.attributeId);- });-- it("sets an attribute idempotently via set-attribute", async () => {- const { noteId } = await createTextNote(ctx);-- await ctx.agent- .put(`/api/notes/${noteId}/set-attribute`)- .set("x-csrf-token", ctx.csrfToken)- .send({ type: "label", name: "color", value: "red" })- .expect(204);-- await ctx.agent- .put(`/api/notes/${noteId}/set-attribute`)- .set("x-csrf-token", ctx.csrfToken)- .send({ type: "label", name: "color", value: "blue" })- .expect(204);-- const res = await ctx.agent.get(`/api/notes/${noteId}/attributes`).expect(200);- const colors = (res.body as AttrRow[]).filter((a) => a.name === "color");- expect(colors).toHaveLength(1);- expect(colors[0].value).toBe("blue");- });-- it("creates a relation between two notes", async () => {- const { noteId } = await createTextNote(ctx);-- const res = await ctx.agent- .put(`/api/notes/${noteId}/relations/myRelation/to/root`)- .set("x-csrf-token", ctx.csrfToken)- .expect(200);-- expect(res.body).toMatchObject({ type: "relation", name: "myRelation", value: "root" });- });- });-});diff --git a/apps/server/src/routes/api/core_routes_http.spec.ts b/apps/server/src/routes/api/core_routes_http.spec.tsnew file mode 100644index 0000000000..abe7ac681d--- /dev/null+++ b/apps/server/src/routes/api/core_routes_http.spec.ts@@ -0,0 +1,40 @@+import { beforeAll, describe, expect, it } from "vitest";++import {+ type ApiTestContext,+ bootLoggedInApp,+ createTextNote } from "../../../spec/support/internal_api.js";++/**+ * Thin Express-transport layer for the shared **core** API routes.+ *+ * Per-route behaviour (handlers, serialization, status/error mapping) is covered+ * cross-runtime by the `CoreApiTester` specs in `packages/trilium-core/src/routes/api/`.+ * This spec only asserts the things that exist *because of Express* and the+ * server middleware — and therefore can't be exercised by the in-process core+ * driver: CSRF enforcement, and that core routes are actually wired into the+ * Express app end to end. (Auth-required can't be asserted here because the test+ * fixture's config.ini sets `noAuthentication=true`.)+ */+let ctx: ApiTestContext;++describe("Core routes over Express", () => {+ beforeAll(async () => {+ ctx = await bootLoggedInApp();+ });++ it("rejects a mutating request without a CSRF token (403)", async () => {+ await ctx.agent.post("/api/tree/load").send({ noteIds: [ "root" ] }).expect(403);+ });++ it("serves a core GET route end to end once authenticated", async () => {+ const res = await ctx.agent.get("/api/tree").expect(200);+ expect(res.body.notes.some((n: { noteId: string }) => n.noteId === "root")).toBe(true);+ });++ it("runs a core mutating route end to end with a CSRF token", async () => {+ const { noteId } = await createTextNote(ctx, { title: "Via Express" });+ const res = await ctx.agent.get(`/api/notes/${noteId}`).expect(200);+ expect(res.body.title).toBe("Via Express");+ });+});diff --git a/apps/server/src/routes/api/notes.spec.ts b/apps/server/src/routes/api/notes.spec.tsdeleted file mode 100644index 4f06ade15c..0000000000--- a/apps/server/src/routes/api/notes.spec.ts+++ /dev/null@@ -1,128 +0,0 @@-import { getSql } from "@triliumnext/core";-import { beforeAll, describe, expect, it } from "vitest";--import {- type ApiTestContext,- bootLoggedInApp,- createTextNote } from "../../../spec/support/internal_api.js";--let ctx: ApiTestContext;--function noteIsDeleted(noteId: string): number | null {- const row = getSql().getRowOrNull<{ isDeleted: number }>(- "SELECT isDeleted FROM notes WHERE noteId = ?",- [ noteId ]- );- return row ? row.isDeleted : null;-}--describe("Notes API", () => {- beforeAll(async () => {- ctx = await bootLoggedInApp();- });-- describe("reading", () => {- it("returns note metadata for an existing note", async () => {- const res = await ctx.agent.get("/api/notes/root").expect(200);- expect(res.body.noteId).toBe("root");- expect(res.body.type).toBeTruthy();- });-- it("returns timestamp metadata", async () => {- const res = await ctx.agent.get("/api/notes/root/metadata").expect(200);- expect(res.body).toMatchObject({- dateCreated: expect.any(String),- utcDateCreated: expect.any(String),- dateModified: expect.any(String),- utcDateModified: expect.any(String)- });- });-- it("returns the note blob", async () => {- const res = await ctx.agent.get("/api/notes/root/blob").expect(200);- expect(res.body.blobId).toBeTruthy();- expect(typeof res.body.content).toBe("string");- });-- it("404s for a missing note", async () => {- await ctx.agent.get("/api/notes/missingNote123").expect(404);- });- });-- describe("creating", () => {- it("creates a child note under root", async () => {- const res = await ctx.agent- .post("/api/notes/root/children?target=into")- .set("x-csrf-token", ctx.csrfToken)- .send({ title: "Created via API", type: "text", content: "<p>body</p>" })- .expect(200);-- expect(res.body.note.noteId).toBeTruthy();- expect(res.body.note.title).toBe("Created via API");- expect(res.body.branch.parentNoteId).toBe("root");- });-- it("400s when the target query param is invalid", async () => {- await ctx.agent- .post("/api/notes/root/children")- .set("x-csrf-token", ctx.csrfToken)- .send({ title: "no target", type: "text" })- .expect(400);- });- });-- describe("updating", () => {- it("changes a note title and returns the updated note", async () => {- const { noteId } = await createTextNote(ctx, { title: "Before" });-- const res = await ctx.agent- .put(`/api/notes/${noteId}/title`)- .set("x-csrf-token", ctx.csrfToken)- .send({ title: "After" })- .expect(200);-- expect(res.body.title).toBe("After");- });-- it("updates note content", async () => {- const { noteId } = await createTextNote(ctx, { content: "<p>old</p>" });-- await ctx.agent- .put(`/api/notes/${noteId}/data`)- .set("x-csrf-token", ctx.csrfToken)- .send({ content: "<p>new</p>" })- .expect(204);-- const blob = await ctx.agent.get(`/api/notes/${noteId}/blob`).expect(200);- expect(blob.body.content).toContain("new");- });- });-- describe("deleting and undeleting", () => {- it("soft-deletes a note, then undeletes it", async () => {- const { noteId } = await createTextNote(ctx, { title: "To delete" });- expect(noteIsDeleted(noteId)).toBe(0);-- await ctx.agent- .delete(`/api/notes/${noteId}`)- .query({ taskId: "test-delete", last: "true" })- .set("x-csrf-token", ctx.csrfToken)- .expect(204);- expect(noteIsDeleted(noteId)).toBe(1);-- await ctx.agent- .put(`/api/notes/${noteId}/undelete`)- .set("x-csrf-token", ctx.csrfToken)- .expect(204);- expect(noteIsDeleted(noteId)).toBe(0);- });-- it("400s when deleting without a taskId", async () => {- const { noteId } = await createTextNote(ctx, { title: "Needs taskId" });- await ctx.agent- .delete(`/api/notes/${noteId}`)- .set("x-csrf-token", ctx.csrfToken)- .expect(400);- });- });-});diff --git a/apps/server/src/routes/api/tree.spec.ts b/apps/server/src/routes/api/tree.spec.tsdeleted file mode 100644index d871871716..0000000000--- a/apps/server/src/routes/api/tree.spec.ts+++ /dev/null@@ -1,57 +0,0 @@-import { beforeAll, describe, expect, it } from "vitest";--import { type ApiTestContext,bootLoggedInApp } from "../../../spec/support/internal_api.js";--let ctx: ApiTestContext;--interface TreeResponse {- notes: { noteId: string }[];- branches: { branchId: string }[];- attributes: unknown[];-}--describe("Tree API", () => {- beforeAll(async () => {- ctx = await bootLoggedInApp();- });-- it("returns notes, branches and attributes rooted at root", async () => {- const res = await ctx.agent.get("/api/tree").expect(200);- const body = res.body as TreeResponse;-- expect(Array.isArray(body.notes)).toBe(true);- expect(Array.isArray(body.branches)).toBe(true);- expect(Array.isArray(body.attributes)).toBe(true);- expect(body.notes.some((n) => n.noteId === "root")).toBe(true);- // root always gets the synthetic `none_root` branch (parentNoteId "none").- expect(body.branches.some((b) => b.branchId === "none_root")).toBe(true);- });-- it("scopes the tree to a subtree via subTreeNoteId", async () => {- const res = await ctx.agent- .get("/api/tree")- .query({ subTreeNoteId: "_hidden" })- .expect(200);- const body = res.body as TreeResponse;- expect(body.notes.some((n) => n.noteId === "_hidden")).toBe(true);- });-- it("404s for an unknown subtree note", async () => {- await ctx.agent.get("/api/tree").query({ subTreeNoteId: "doesNotExist123" }).expect(404);- });-- it("loads an explicit set of note ids", async () => {- const res = await ctx.agent- .post("/api/tree/load")- .set("x-csrf-token", ctx.csrfToken)- .send({ noteIds: [ "root" ] })- .expect(200);- const body = res.body as TreeResponse;-- expect(body.notes.some((n) => n.noteId === "root")).toBe(true);- });-- it("rejects a mutating request without a CSRF token", async () => {- await ctx.agent.post("/api/tree/load").send({ noteIds: [ "root" ] }).expect(403);- });-});diff --git a/packages/trilium-core/src/routes/api/attributes.spec.ts b/packages/trilium-core/src/routes/api/attributes.spec.tsnew file mode 100644index 0000000000..37d9e88773--- /dev/null+++ b/packages/trilium-core/src/routes/api/attributes.spec.ts@@ -0,0 +1,95 @@+import { beforeAll, describe, expect, it } from "vitest";++import { createTextNote } from "../../test/api_fixtures";+import { CoreApiTester } from "../../test/api_tester";++let api: CoreApiTester;++interface AttrRow {+ attributeId: string;+ type: string;+ name: string;+ value: string;+}++describe("Attributes API (core)", () => {+ beforeAll(() => {+ api = CoreApiTester.build();+ });++ describe("reading", () => {+ it("returns the effective attributes of a note", async () => {+ const res = await api.get<AttrRow[]>("/api/notes/_hidden/attributes");+ expect(res.status).toBe(200);+ expect(Array.isArray(res.body)).toBe(true);+ expect(res.body.some((a) => a.name === "docName")).toBe(true);+ });++ it("returns attribute names filtered by type and query", async () => {+ const res = await api.get("/api/attribute-names", {+ query: { type: "label", query: "" }+ });+ expect(res.status).toBe(200);+ expect(Array.isArray(res.body)).toBe(true);+ });++ it("400s when type/query params are missing", async () => {+ const res = await api.get("/api/attribute-names");+ expect(res.status).toBe(400);+ });++ it("returns distinct values for an attribute name", async () => {+ const res = await api.get("/api/attribute-values/docName");+ expect(res.status).toBe(200);+ expect(Array.isArray(res.body)).toBe(true);+ });+ });++ describe("writing", () => {+ it("adds a label, reads it back, then deletes it", async () => {+ const { noteId } = await createTextNote(api);++ const add = await api.post(`/api/notes/${noteId}/attributes`, {+ body: { type: "label", name: "myLabel", value: "myValue" }+ });+ expect(add.status).toBe(204);++ const afterAdd = await api.get<AttrRow[]>(`/api/notes/${noteId}/attributes`);+ const added = afterAdd.body.find((a) => a.name === "myLabel");+ expect(added).toMatchObject({ type: "label", value: "myValue" });++ const del = await api.delete(`/api/notes/${noteId}/attributes/${added!.attributeId}`);+ expect(del.status).toBe(204);++ const afterDelete = await api.get<AttrRow[]>(`/api/notes/${noteId}/attributes`);+ const remainingIds = afterDelete.body.map((a) => a.attributeId);+ expect(remainingIds).not.toContain(added!.attributeId);+ });++ it("sets an attribute idempotently via set-attribute", async () => {+ const { noteId } = await createTextNote(api);++ const first = await api.put(`/api/notes/${noteId}/set-attribute`, {+ body: { type: "label", name: "color", value: "red" }+ });+ expect(first.status).toBe(204);++ await api.put(`/api/notes/${noteId}/set-attribute`, {+ body: { type: "label", name: "color", value: "blue" }+ });++ const res = await api.get<AttrRow[]>(`/api/notes/${noteId}/attributes`);+ const colors = res.body.filter((a) => a.name === "color");+ expect(colors).toHaveLength(1);+ expect(colors[0].value).toBe("blue");+ });++ it("creates a relation between two notes", async () => {+ const { noteId } = await createTextNote(api);++ const res = await api.put<AttrRow>(`/api/notes/${noteId}/relations/myRelation/to/root`);+ expect(res.status).toBe(200);+ expect(res.body).toMatchObject({ type: "relation", name: "myRelation", value: "root" });+ });+ });+});diff --git a/packages/trilium-core/src/routes/api/notes.spec.ts b/packages/trilium-core/src/routes/api/notes.spec.tsnew file mode 100644index 0000000000..c472c9e89d--- /dev/null+++ b/packages/trilium-core/src/routes/api/notes.spec.ts@@ -0,0 +1,129 @@+import { beforeAll, describe, expect, it } from "vitest";++import { getSql } from "../../services/sql/index";+import { createTextNote } from "../../test/api_fixtures";+import { CoreApiTester } from "../../test/api_tester";++/**+ * Drives the shared core note routes through {@link CoreApiTester} (no Express),+ * so this spec runs under both the node and standalone (WASM) suites.+ */+let api: CoreApiTester;++function noteIsDeleted(noteId: string): number | null {+ const row = getSql().getRowOrNull<{ isDeleted: number }>(+ "SELECT isDeleted FROM notes WHERE noteId = ?",+ [ noteId ]+ );+ return row ? row.isDeleted : null;+}++describe("Notes API (core)", () => {+ beforeAll(() => {+ api = CoreApiTester.build();+ });++ describe("reading", () => {+ it("returns note metadata for an existing note", async () => {+ const res = await api.get<{ noteId: string; type: string }>("/api/notes/root");+ expect(res.status).toBe(200);+ expect(res.body.noteId).toBe("root");+ expect(res.body.type).toBeTruthy();+ });++ it("returns timestamp metadata", async () => {+ const res = await api.get("/api/notes/root/metadata");+ expect(res.status).toBe(200);+ expect(res.body).toMatchObject({+ dateCreated: expect.any(String),+ utcDateCreated: expect.any(String),+ dateModified: expect.any(String),+ utcDateModified: expect.any(String)+ });+ });++ it("returns the note blob", async () => {+ const res = await api.get<{ blobId: string; content: string }>("/api/notes/root/blob");+ expect(res.status).toBe(200);+ expect(res.body.blobId).toBeTruthy();+ expect(typeof res.body.content).toBe("string");+ });++ it("404s for a missing note", async () => {+ const res = await api.get("/api/notes/missingNote123");+ expect(res.status).toBe(404);+ });+ });++ describe("creating", () => {+ it("creates a child note under root", async () => {+ interface CreateResponse {+ note: { noteId: string; title: string };+ branch: { parentNoteId: string };+ }+ const res = await api.post<CreateResponse>(+ "/api/notes/root/children?target=into",+ { body: { title: "Created via API", type: "text", content: "<p>body</p>" } }+ );++ expect(res.status).toBe(200);+ expect(res.body.note.noteId).toBeTruthy();+ expect(res.body.note.title).toBe("Created via API");+ expect(res.body.branch.parentNoteId).toBe("root");+ });++ it("400s when the target query param is invalid", async () => {+ const res = await api.post("/api/notes/root/children", {+ body: { title: "no target", type: "text" }+ });+ expect(res.status).toBe(400);+ });+ });++ describe("updating", () => {+ it("changes a note title and returns the updated note", async () => {+ const { noteId } = await createTextNote(api, { title: "Before" });++ const res = await api.put<{ title: string }>(`/api/notes/${noteId}/title`, {+ body: { title: "After" }+ });+ expect(res.status).toBe(200);+ expect(res.body.title).toBe("After");+ });++ it("updates note content", async () => {+ const { noteId } = await createTextNote(api, { content: "<p>old</p>" });++ const update = await api.put(`/api/notes/${noteId}/data`, {+ body: { content: "<p>new</p>" }+ });+ expect(update.status).toBe(204);++ const blob = await api.get<{ content: string }>(`/api/notes/${noteId}/blob`);+ expect(blob.body.content).toContain("new");+ });+ });++ describe("deleting and undeleting", () => {+ it("soft-deletes a note, then undeletes it", async () => {+ const { noteId } = await createTextNote(api, { title: "To delete" });+ expect(noteIsDeleted(noteId)).toBe(0);++ const del = await api.delete(`/api/notes/${noteId}`, {+ query: { taskId: "test-delete", last: "true" }+ });+ expect(del.status).toBe(204);+ expect(noteIsDeleted(noteId)).toBe(1);++ const undel = await api.put(`/api/notes/${noteId}/undelete`);+ expect(undel.status).toBe(204);+ expect(noteIsDeleted(noteId)).toBe(0);+ });++ it("400s when deleting without a taskId", async () => {+ const { noteId } = await createTextNote(api, { title: "Needs taskId" });+ const res = await api.delete(`/api/notes/${noteId}`);+ expect(res.status).toBe(400);+ });+ });+});diff --git a/apps/server/src/routes/api/search.spec.ts b/packages/trilium-core/src/routes/api/search.spec.tssimilarity index 50%rename from apps/server/src/routes/api/search.spec.tsrename to packages/trilium-core/src/routes/api/search.spec.tsindex 171a9605e4..59681f1887 100644--- a/apps/server/src/routes/api/search.spec.ts+++ b/packages/trilium-core/src/routes/api/search.spec.ts@@ -1,49 +1,51 @@import { beforeAll, describe, expect, it } from "vitest";-import {- type ApiTestContext,- bootLoggedInApp,- createTextNote } from "../../../spec/support/internal_api.js";+import { createTextNote } from "../../test/api_fixtures";+import { CoreApiTester } from "../../test/api_tester";-let ctx: ApiTestContext;+let api: CoreApiTester;const UNIQUE_TOKEN = "ZzUniqueSearchTokenQwerty";-describe("Search API", () => {+describe("Search API (core)", () => {let createdNoteId: string;beforeAll(async () => {- ctx = await bootLoggedInApp();- ({ noteId: createdNoteId } = await createTextNote(ctx, { title: UNIQUE_TOKEN }));+ api = CoreApiTester.build();+ ({ noteId: createdNoteId } = await createTextNote(api, { title: UNIQUE_TOKEN }));});it("returns matching note ids for a full search", async () => {- const res = await ctx.agent.get(`/api/search/${UNIQUE_TOKEN}`).expect(200);+ const res = await api.get<string[]>(`/api/search/${UNIQUE_TOKEN}`);+ expect(res.status).toBe(200);expect(Array.isArray(res.body)).toBe(true);expect(res.body).toContain(createdNoteId);});it("returns structured quick-search results with snippets", async () => {- const res = await ctx.agent.get(`/api/quick-search/${UNIQUE_TOKEN}`).expect(200);+ const res = await api.get<{ searchResultNoteIds: string[]; searchResults: unknown[] }>(+ `/api/quick-search/${UNIQUE_TOKEN}`+ );+ expect(res.status).toBe(200);expect(res.body.searchResultNoteIds).toContain(createdNoteId);expect(Array.isArray(res.body.searchResults)).toBe(true);});it("lists template note ids", async () => {- const res = await ctx.agent.get("/api/search-templates").expect(200);+ const res = await api.get("/api/search-templates");+ expect(res.status).toBe(200);expect(Array.isArray(res.body)).toBe(true);});it("400s when searching from a note that is not a search note", async () => {- await ctx.agent.get("/api/search-note/root").expect(400);+ const res = await api.get("/api/search-note/root");+ expect(res.status).toBe(400);});it("returns related notes for an attribute query", async () => {- const res = await ctx.agent- .post("/api/search-related")- .set("x-csrf-token", ctx.csrfToken)- .send({ type: "label", name: "docName", value: "hidden" })- .expect(200);-+ const res = await api.post<{ count: number; results: unknown[] }>("/api/search-related", {+ body: { type: "label", name: "docName", value: "hidden" }+ });+ expect(res.status).toBe(200);expect(typeof res.body.count).toBe("number");expect(Array.isArray(res.body.results)).toBe(true);});diff --git a/apps/server/src/routes/api/stats.spec.ts b/packages/trilium-core/src/routes/api/stats.spec.tssimilarity index 52%rename from apps/server/src/routes/api/stats.spec.tsrename to packages/trilium-core/src/routes/api/stats.spec.tsindex a9f7526641..20730716ce 100644--- a/apps/server/src/routes/api/stats.spec.ts+++ b/packages/trilium-core/src/routes/api/stats.spec.ts@@ -1,22 +1,26 @@import { beforeAll, describe, expect, it } from "vitest";-import { type ApiTestContext,bootLoggedInApp } from "../../../spec/support/internal_api.js";+import { CoreApiTester } from "../../test/api_tester";-let ctx: ApiTestContext;+let api: CoreApiTester;-describe("Stats API", () => {- beforeAll(async () => {- ctx = await bootLoggedInApp();+describe("Stats API (core)", () => {+ beforeAll(() => {+ api = CoreApiTester.build();});it("returns the blob size of a note", async () => {- const res = await ctx.agent.get("/api/stats/note-size/root").expect(200);+ const res = await api.get<{ noteSize: number }>("/api/stats/note-size/root");+ expect(res.status).toBe(200);expect(typeof res.body.noteSize).toBe("number");expect(res.body.noteSize).toBeGreaterThanOrEqual(0);});it("returns the subtree size and note count", async () => {- const res = await ctx.agent.get("/api/stats/subtree-size/root").expect(200);+ const res = await api.get<{ subTreeSize: number; subTreeNoteCount: number }>(+ "/api/stats/subtree-size/root"+ );+ expect(res.status).toBe(200);expect(typeof res.body.subTreeSize).toBe("number");expect(res.body.subTreeNoteCount).toBeGreaterThan(1);});@@ -24,11 +28,13 @@ describe("Stats API", () => {// note-size runs a pure SQL aggregate (no note lookup), so a missing note is// 0 bytes rather than an error; subtree-size resolves the note first and 404s.it("reports zero size for a missing note", async () => {- const res = await ctx.agent.get("/api/stats/note-size/missingNote123").expect(200);+ const res = await api.get<{ noteSize: number }>("/api/stats/note-size/missingNote123");+ expect(res.status).toBe(200);expect(res.body.noteSize).toBe(0);});it("404s for the subtree size of a missing note", async () => {- await ctx.agent.get("/api/stats/subtree-size/missingNote123").expect(404);+ const res = await api.get("/api/stats/subtree-size/missingNote123");+ expect(res.status).toBe(404);});});diff --git a/packages/trilium-core/src/routes/api/tree.spec.ts b/packages/trilium-core/src/routes/api/tree.spec.tsnew file mode 100644index 0000000000..0c1686246a--- /dev/null+++ b/packages/trilium-core/src/routes/api/tree.spec.ts@@ -0,0 +1,53 @@+import { beforeAll, describe, expect, it } from "vitest";++import { CoreApiTester } from "../../test/api_tester";++/**+ * Drives the shared core tree routes through the in-process {@link CoreApiTester}+ * (no Express / HTTP server), so this same spec runs under both the node+ * (better-sqlite3) and standalone (sql.js WASM) suites against the seeded demo DB.+ */+let api: CoreApiTester;++interface TreeResponse {+ notes: { noteId: string }[];+ branches: { branchId: string }[];+ attributes: unknown[];+}++describe("Tree API (core)", () => {+ beforeAll(() => {+ api = CoreApiTester.build();+ });++ it("returns notes, branches and attributes rooted at root", async () => {+ const res = await api.get<TreeResponse>("/api/tree");++ expect(res.status).toBe(200);+ expect(Array.isArray(res.body.notes)).toBe(true);+ expect(res.body.notes.some((n) => n.noteId === "root")).toBe(true);+ // root always gets the synthetic `none_root` branch (parentNoteId "none").+ expect(res.body.branches.some((b) => b.branchId === "none_root")).toBe(true);+ });++ it("scopes the tree to a subtree via subTreeNoteId", async () => {+ const res = await api.get<TreeResponse>("/api/tree", {+ query: { subTreeNoteId: "_hidden" }+ });+ expect(res.status).toBe(200);+ expect(res.body.notes.some((n) => n.noteId === "_hidden")).toBe(true);+ });++ it("404s for an unknown subtree note", async () => {+ const res = await api.get("/api/tree", { query: { subTreeNoteId: "doesNotExist123" } });+ expect(res.status).toBe(404);+ });++ it("loads an explicit set of note ids", async () => {+ const res = await api.post<TreeResponse>("/api/tree/load", {+ body: { noteIds: [ "root" ] }+ });+ expect(res.status).toBe(200);+ expect(res.body.notes.some((n) => n.noteId === "root")).toBe(true);+ });+});diff --git a/packages/trilium-core/src/test/api_fixtures.ts b/packages/trilium-core/src/test/api_fixtures.tsnew file mode 100644index 0000000000..593f9d244a--- /dev/null+++ b/packages/trilium-core/src/test/api_fixtures.ts@@ -0,0 +1,32 @@+import { CoreApiTester } from "./api_tester";++export interface CreatedNote {+ noteId: string;+ branchId: string;+}++interface CreateNoteOptions {+ parentNoteId?: string;+ title?: string;+ content?: string;+}++/**+ * Creates a disposable child note through the core API and returns its+ * `{ noteId, branchId }`, so tests can operate on a known note without+ * coupling to specific fixture content.+ */+export async function createTextNote(+ api: CoreApiTester,+ { parentNoteId = "root", title = "Test note", content = "<p>hello</p>" }: CreateNoteOptions = {}+): Promise<CreatedNote> {+ const res = await api.post<{ note: { noteId: string }; branch: { branchId: string } }>(+ `/api/notes/${parentNoteId}/children?target=into`,+ { body: { title, type: "text", content } }+ );++ return {+ noteId: res.body.note.noteId,+ branchId: res.body.branch.branchId+ };+}diff --git a/packages/trilium-core/src/test/api_tester.ts b/packages/trilium-core/src/test/api_tester.tsnew file mode 100644index 0000000000..946eb3e8f7--- /dev/null+++ b/packages/trilium-core/src/test/api_tester.ts@@ -0,0 +1,286 @@+import { HttpError } from "../errors";+import * as routes from "../routes";+import { getContext } from "../services/context";+import entityChanges from "../services/entity_changes";+import { getSql } from "../services/sql/index";++/**+ * In-process, transport-agnostic test driver for the **shared core API routes**+ * (the ones registered by `routes.buildSharedApiRoutes`). Think of it as+ * "supertest for core": it drives the exact same handlers that the Express+ * server (`apps/server`) and the standalone browser router+ * (`apps/standalone/.../browser_routes.ts`) expose, but without an HTTP server,+ * Express, or a socket — so the same spec runs under **both** the node+ * (better-sqlite3) and the standalone (sql.js WASM) test suites.+ *+ * It exercises the real request lifecycle around each handler:+ * - path/param + query parsing (Express-style `:param`)+ * - the execution context (cls) and SQL transaction wrapping+ * - `convertEntitiesToPojo` + the `[statusCode, body]` / `undefined → 204`+ * result-handler conventions+ * - `HttpError` → status mapping (404 / 400 / 403 …)+ * - JSON round-tripping of the response body (so e.g. dates surface as the+ * strings an HTTP client would actually receive)+ *+ * It deliberately does **not** run the platform middleware (auth, CSRF, rate+ * limiting, multipart parsing) — those are server/Express concerns and are+ * covered by the supertest specs in `apps/server`. Auth/CSRF are treated as+ * always-passing here, mirroring the standalone browser adapter.+ */++type HttpMethod = "get" | "post" | "put" | "patch" | "delete";++type Handler = (req: ApiRequest, res?: MockResponse) => unknown;+type ResultHandler = (req: ApiRequest, res: CaptureResponse, result: unknown) => void;++interface ApiRequest {+ params: Record<string, string>;+ query: Record<string, string | undefined>;+ body: unknown;+ headers: Record<string, string>;+ method: string;+ file?: unknown;+ originalUrl: string;+}++interface RegisteredRoute {+ method: string;+ pattern: RegExp;+ paramNames: string[];+ run: (req: ApiRequest) => Promise<TestResponse>;+}++export interface TestResponse<T = unknown> {+ status: number;+ headers: Record<string, string>;+ body: T;+}++export interface RequestOptions {+ body?: unknown;+ query?: Record<string, string | number | boolean | undefined>;+ headers?: Record<string, string>;+}++function pathToRegex(path: string): { pattern: RegExp; paramNames: string[] } {+ const paramNames: string[] = [];+ // Drop a trailing slash from the registered path and allow an optional one+ // when matching, mirroring Express's default (non-strict) routing — several+ // core routes are registered with a trailing slash (e.g. /api/attribute-names/).+ const normalized = path.replace(/\/$/, "");+ const regexPattern = normalized+ .replace(/[.*+?^${}()|[\]\\]/g, "\\$&")+ .replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g, (_, paramName) => {+ paramNames.push(paramName);+ return "([^/]+)";+ });+ return { pattern: new RegExp(`^${regexPattern}\\/?$`), paramNames };+}++function jsonRoundTrip(value: unknown): unknown {+ if (value === undefined || typeof value === "string") {+ return value;+ }+ return JSON.parse(JSON.stringify(value));+}++/** Mirrors the server's `apiResultHandler` / browser `formatResult` conventions. */+function formatApiResult(result: unknown): TestResponse {+ const headers: Record<string, string> = {+ "trilium-max-entity-change-id": String(entityChanges.getMaxEntityChangeId())+ };+ const pojo = routes.convertEntitiesToPojo(result);++ if (Array.isArray(pojo) && pojo.length > 0 && Number.isInteger(pojo[0])) {+ const [ status, response ] = pojo as [number, unknown];+ return { status, headers, body: jsonRoundTrip(response) };+ }+ if (pojo === undefined) {+ return { status: 204, headers, body: undefined };+ }+ return { status: 200, headers, body: jsonRoundTrip(pojo) };+}++/** Captures what a result handler writes, for the `route(..., resultHandler)` path. */+interface CaptureResponse {+ captured?: TestResponse;+ 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;+}++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;+}++export class CoreApiTester {++ private routes: RegisteredRoute[] = [];++ private add(method: string, path: string, run: (req: ApiRequest) => Promise<TestResponse>) {+ const { pattern, paramNames } = pathToRegex(path);+ this.routes.push({ method: method.toUpperCase(), pattern, paramNames, run });+ }++ /** Builds a tester with every shared core route registered. */+ static build(): CoreApiTester {+ const tester = new CoreApiTester();+ tester.registerAll();+ return tester;+ }++ private registerAll() {+ const apiRoute = (method: HttpMethod, path: string, handler: Handler) =>+ this.add(method, path, async (req) => {+ const result = await getContext().init(() =>+ getSql().transactional(() => handler(req)));+ return formatApiResult(result);+ });++ const asyncApiRoute = (method: HttpMethod, path: string, handler: Handler) =>+ this.add(method, path, async (req) => {+ const result = await getContext().init(async () => await handler(req));+ return formatApiResult(result);+ });++ const buildRoute = (transactional: boolean) =>+ (+ method: HttpMethod,+ path: string,+ _mw: unknown[],+ handler: Handler,+ resultHandler?: ResultHandler | null+ ) =>+ this.add(method, path, async (req) => {+ const mockRes = createMockResponse();+ const invoke = () => handler(req, mockRes);+ const result = transactional+ ? await getContext().init(() => getSql().transactional(invoke))+ : await getContext().init(async () => await invoke());++ if (mockRes.used) {+ return mockRes.snapshot();+ }+ if (resultHandler) {+ const capture: CaptureResponse = { setHeader() {} };+ resultHandler(req, capture, result);+ return capture.captured ?? formatApiResult(result);+ }+ return formatApiResult(result);+ });++ const apiResultHandler: ResultHandler = (_req, res, result) => {+ res.captured = formatApiResult(result);+ };+ const noop = () => {};++ routes.buildSharedApiRoutes({+ route: buildRoute(true),+ asyncRoute: buildRoute(false),+ apiRoute,+ asyncApiRoute,+ apiResultHandler,+ checkApiAuth: noop,+ checkApiAuthOrElectron: noop,+ checkAppNotInitialized: noop,+ checkCredentials: noop,+ loginRateLimiter: noop,+ uploadMiddlewareWithErrorHandling: noop,+ csrfMiddleware: noop+ });+ }++ async request<T = unknown>(+ method: HttpMethod,+ path: string,+ opts: RequestOptions = {}+ ): Promise<TestResponse<T>> {+ const url = new URL(path, "http://core.test");+ for (const [ key, value ] of Object.entries(opts.query ?? {})) {+ if (value !== undefined) {+ url.searchParams.set(key, String(value));+ }+ }++ const query: Record<string, string | undefined> = {};+ for (const [ key, value ] of url.searchParams) {+ query[key] = value;+ }++ const upperMethod = method.toUpperCase();+ for (const route of this.routes) {+ if (route.method !== upperMethod) {+ continue;+ }+ const match = url.pathname.match(route.pattern);+ if (!match) {+ continue;+ }++ const params: Record<string, string> = {};+ route.paramNames.forEach((name, i) => {+ params[name] = decodeURIComponent(match[i + 1]);+ });++ const req: ApiRequest = {+ params,+ query,+ body: opts.body,+ headers: opts.headers ?? {},+ method: upperMethod,+ originalUrl: url.pathname + url.search+ };++ try {+ return (await route.run(req)) as TestResponse<T>;+ } catch (e) {+ const status = e instanceof HttpError ? e.statusCode : 500;+ const message = e instanceof Error ? e.message : String(e);+ return { status, headers: {}, body: { message } as T };+ }+ }++ const message = `No route for ${upperMethod} ${url.pathname}`;+ return { status: 404, headers: {}, body: { message } as T };+ }++ get<T = unknown>(path: string, opts?: RequestOptions) {+ return this.request<T>("get", path, opts);+ }++ post<T = unknown>(path: string, opts?: RequestOptions) {+ return this.request<T>("post", path, opts);+ }++ put<T = unknown>(path: string, opts?: RequestOptions) {+ return this.request<T>("put", path, opts);+ }++ patch<T = unknown>(path: string, opts?: RequestOptions) {+ return this.request<T>("patch", path, opts);+ }++ delete<T = unknown>(path: string, opts?: RequestOptions) {+ return this.request<T>("delete", path, opts);+ }++}