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
test(share): bring the share code back to full coverage and fix CI-only failures
Elian Doranabdd7f76b1d8
diff --git a/apps/client/src/widgets/PromotedAttributes.spec.tsx b/apps/client/src/widgets/PromotedAttributes.spec.tsxindex 93a4b19ad3..189ba299d9 100644--- a/apps/client/src/widgets/PromotedAttributes.spec.tsx+++ b/apps/client/src/widgets/PromotedAttributes.spec.tsx@@ -43,17 +43,6 @@ vi.mock("./react/hooks", async (importOriginal) => ({})}));-// Keep the global setup.ts websocket mock (subscribeToMessages et al.) and only add logError,-// which the unknown-attribute-type branch reports through.-const logErrorMock = vi.hoisted(() => vi.fn());-vi.mock("../services/ws", async (importOriginal) => {- const original = await importOriginal<{ default: object }>();- return {- ...original,- default: { ...original.default, logError: (...args: unknown[]) => logErrorMock(...args) }- };-});-import type Component from "../components/component";import FAttribute from "../entities/fattribute";import type FNote from "../entities/fnote";@@ -62,6 +51,7 @@ import type LoadResults from "../services/load_results";import noteAttributeCache from "../services/note_attribute_cache";import server from "../services/server";import { randomString } from "../services/utils";+import ws from "../services/ws";import { buildNote } from "../test/easy-froca";import { renderInto } from "../test/render";import { ParentComponent } from "./react/react_utils";@@ -75,6 +65,10 @@ const serverRemoveMock = vi.fn(async () => undefined);server.get = serverGetMock as unknown as typeof server.get;server.put = serverPutMock as unknown as typeof server.put;server.remove = serverRemoveMock as unknown as typeof server.remove;+// The global websocket mock in setup.ts has no logError, which the unknown-attribute-type branch+// reports through.+const logErrorMock = vi.fn();+ws.logError = logErrorMock;describe("buildPromotedCells", () => {it("gathers a label allowing several values into one field, leaving a single-valued one its own", () => {diff --git a/packages/trilium-core/src/services/export/zip.spec.ts b/packages/trilium-core/src/services/export/zip.spec.tsindex 9f80e8dd28..9c10b5f758 100644--- a/packages/trilium-core/src/services/export/zip.spec.ts+++ b/packages/trilium-core/src/services/export/zip.spec.ts@@ -2,7 +2,7 @@ import { mkdtempSync, readFileSync, rmSync } from "fs";import { tmpdir } from "os";import { join } from "path";import { PassThrough } from "stream";-import { beforeAll, describe, expect, it } from "vitest";+import { afterAll, beforeAll, describe, expect, it } from "vitest";import { isLocalPreviewImageSrc } from "@triliumnext/commons";@@ -16,6 +16,12 @@ import sql_init from "../sql_init.js";import type { ZipArchive, ZipArchiveEntryOptions, ZipProvider } from "../zip_provider.js";import { getZipProvider, initZipProvider } from "../zip_provider.js";import zip, { shouldStoreUncompressed } from "./zip.js";+import ShareThemeExportProvider from "./zip/share_theme.js";+import {+ getZipExportProviderFactory,+ initZipExportProviderFactory,+ type ZipExportProviderFactory+} from "./zip_export_provider_factory.js";// happy-dom (standalone/WASM) exposes `window`; the Node server suite does not.const isBrowserRuntime = typeof window !== "undefined";@@ -113,11 +119,20 @@ function parseMeta(entries: Record<string, Buffer>): NoteMetaFile {// provider does not support (createFileStream throws). The browser zip provider// has different streaming semantics and is validated separately.describe.skipIf(isBrowserRuntime)("zip export (real DB)", () => {+ // The server's share factory reads the theme from the client build, which a test run lacks.+ let platformFactory: ZipExportProviderFactory;beforeAll(async () => {sql_init.initializeDb();await sql_init.dbReady;+ platformFactory = getZipExportProviderFactory();+ const noAssets = { files: new Map(), readBuiltinFont: () => undefined };+ initZipExportProviderFactory(async (format, data) => (format === "share"+ ? new ShareThemeExportProvider(data, noAssets)+ : platformFactory(format, data)));});+ afterAll(() => initZipExportProviderFactory(platformFactory));+describe("exportToZip", () => {it("produces a meta file plus the note's data file and sets the zip headers", async () => {const { note } = createNote("root", { title: "ExportRoot", content: "<p>body text</p>" });diff --git a/packages/trilium-core/src/share/content_renderer.spec.ts b/packages/trilium-core/src/share/content_renderer.spec.tsindex 73f7b33956..354f1e3abb 100644--- a/packages/trilium-core/src/share/content_renderer.spec.ts+++ b/packages/trilium-core/src/share/content_renderer.spec.ts@@ -1749,11 +1749,19 @@ describe("content_renderer pages", () => {{ id: "lockedCard", title: "Locked", content: "<p>Locked</p>", "#shareCredentials": "other:secret" }]});- const page = parse(String(renderNoteContent(board, (note) => note.noteId !== "lockedCard")));- const payload = JSON.parse(page.querySelector("script.share-froca")?.textContent ?? "{}");+ const setDevMode = mockDevMode();+ const readPayload = () => {+ const content = renderNoteContent(board, (note) => note.noteId !== "lockedCard");+ const page = parse(String(content));+ return JSON.parse(page.querySelector("script.share-froca")?.textContent ?? "{}");+ };+ const payload = readPayload();expect(payload.notes.map((note: { noteId: string }) => note.noteId)).toEqual([ "lockedBoard", "openCard" ]);expect(payload.attributes.map((attribute: { name: string }) => attribute.name)).toEqual([ "viewType" ]);expect("exportBasePath" in payload).toBe(false);+ expect(payload.assetPath).toBe(`../${assetUrlFragment}`);+ setDevMode(true);+ expect(readPayload().assetPath).toBe(`../${assetUrlFragment}/src`);});it("lists the subpages of a collection whose template makes it a list", () => {diff --git a/packages/trilium-core/src/share/content_renderer.ts b/packages/trilium-core/src/share/content_renderer.tsindex 6cf302de17..90310cc460 100644--- a/packages/trilium-core/src/share/content_renderer.ts+++ b/packages/trilium-core/src/share/content_renderer.ts@@ -1001,7 +1001,7 @@ function hostInAppView(const json = JSON.stringify(payload).replace(/</g, "\\u003c");result.isAppView = true;result.isFullHeight = true;- const content = String(result.content ?? "");+ const content = String(result.content);result.content = `<div class="${container}" data-note-id="${note.noteId}">${content}</div>`+ `<script type="application/json" class="share-froca">${json}</script>`;}@@ -1012,8 +1012,9 @@ function hostInAppView(*/function buildExportRows(note: BNote, exportHosting: ExportHosting | undefined) {const getLink = (linked: BNote) => exportHosting?.getLink(linked.noteId) ?? null;+ // `canAccess` admits only the notes with a link, so `getLink` is never asked for another.return buildFrocaRows([ note ], (candidate) => getLink(candidate) !== null,- (candidate) => getLink(candidate) ?? "");+ (candidate) => String(getLink(candidate)));}/**diff --git a/packages/trilium-core/src/share/froca_payload.spec.ts b/packages/trilium-core/src/share/froca_payload.spec.tsindex 54853fe9d4..5ca5e17507 100644--- a/packages/trilium-core/src/share/froca_payload.spec.ts+++ b/packages/trilium-core/src/share/froca_payload.spec.ts@@ -3,11 +3,17 @@ import { beforeEach, describe, expect, it, vi } from "vitest";import becca from "../becca/becca.js";import scriptService from "../services/script.js";import { buildNote } from "../test/becca_easy_mocking.js";-import { buildVisibleRelationMap, buildVisibleScriptBundle } from "./froca_payload.js";+import { buildShareNote } from "../test/shaca_mocking.js";+import {+ buildFrocaPayload, buildFrocaRows, buildVisibleRelationMap, buildVisibleScriptBundle,+ type FrocaRows+} from "./froca_payload.js";+import shaca from "./shaca/shaca.js";describe("hosted view data", () => {beforeEach(() => {becca.reset();+ shaca.reset();});it("builds no script bundle for a backend script or one that cannot be read", () => {@@ -28,6 +34,24 @@ describe("hosted view data", () => {bundle.mockRestore();});+ it("reads a built-in template from becca, which lacks shaca, and lists it only once", () => {+ buildNote({ "id": "_template_calendar", "title": "Calendar", "#viewType": "calendar" });+ const shared = buildShareNote({ "id": "sharedNote", "~template": "_template_calendar" });+ const noteIds = (rows: FrocaRows) => rows.notes.map((row) => row.noteId);++ const rows = buildFrocaPayload(shared);+ expect(noteIds(rows)).toEqual([ "_template_calendar", "sharedNote" ]);+ expect(rows.attributes.map((row) => [ row.noteId, row.name ])).toEqual([+ [ "_template_calendar", "viewType" ],+ [ "sharedNote", "template" ]+ ]);+ expect(rows.links).not.toHaveProperty("_template_calendar");++ const exported = buildNote({ "id": "exportedCalendar", "~template": "_template_calendar" });+ expect(noteIds(buildFrocaRows([ exported ], () => true, (note) => note.noteId)))+ .toEqual([ "exportedCalendar", "_template_calendar" ]);+ });+it("places no note on a relation map whose content is not its JSON", () => {const map = buildNote({ type: "relationMap" });diff --git a/packages/trilium-core/src/share/handlers.spec.ts b/packages/trilium-core/src/share/handlers.spec.tsindex 087daec744..7590d43153 100644--- a/packages/trilium-core/src/share/handlers.spec.ts+++ b/packages/trilium-core/src/share/handlers.spec.ts@@ -1,7 +1,9 @@import { NOTE_TYPE_IMAGE_ATTACHMENTS } from "@triliumnext/commons";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import becca from "../becca/becca.js";import { getCrypto } from "../services/encryption/crypto.js";+import scriptService from "../services/script.js";import SearchResult from "../services/search/search_result.js";import searchService from "../services/search/services/search.js";import { encodeBase64, encodeUtf8 } from "../services/utils/binary.js";@@ -213,7 +215,14 @@ describe("share handlers", () => {"/share/api/notes/:noteId/view","/share/api/images/:noteId/:filename","/share/api/attachments/:attachmentId/image/:filename",- "/share/api/attachments/:attachmentId/download"+ "/share/api/attachments/:attachmentId/download",+ "/share/api/notes/:noteId/attachments",+ "/share/api/notes/:noteId/blob",+ "/share/api/attachments/:attachmentId/all",+ "/share/api/attachments/:attachmentId/blob",+ "/share/api/note-map/:noteId/:mapType",+ "/share/api/relation-map/:noteId",+ "/share/api/script/bundle/:noteId"] as const) {expect(request(path).status, path).toBe(404);}@@ -542,6 +551,106 @@ describe("share handlers", () => {expect(names({ type: "label" })).toBe(400);});+ it("reads the notes, attachments and blobs of only the readable notes for an app view", () => {+ buildShareTree([+ {+ id: "viewParent",+ title: "Parent",+ content: "<p>Parent body</p>",+ children: [ { id: "viewChild", title: "Child", content: "" } ],+ attachments: [+ { id: "firstAttachment", role: "file", mime: "text/plain", title: "a.txt" },+ { id: "secondAttachment", role: "file", mime: "text/plain", title: "b.txt" }+ ]+ },+ { "id": "viewLocked", "content": "", "#shareCredentials": "root:hunter2" }+ ]);+ stubAttachmentContent("firstAttachment", "first text");+ const noteIds = "viewParent,viewLocked,noSuchNote";++ const tree = readJson("/share/api/tree", { query: { noteIds } });+ expect(tree.notes.map((note: { noteId: string }) => note.noteId))+ .toEqual([ "viewParent", "viewChild" ]);+ expect(tree.branches)+ .toMatchObject([ { noteId: "viewChild", parentNoteId: "viewParent" } ]);+ expect(readJson("/share/api/tree").notes).toEqual([]);++ const attachments = readJson("/share/api/notes/:noteId/attachments",+ { params: { noteId: "viewParent" } });+ expect(attachments).toMatchObject([+ { attachmentId: "firstAttachment", ownerId: "viewParent", contentLength: 0 },+ { attachmentId: "secondAttachment", ownerId: "viewParent", title: "b.txt" }+ ]);+ expect(readJson("/share/api/attachments/:attachmentId/all",+ { params: { attachmentId: "secondAttachment" } })).toEqual(attachments);++ expect(readJson("/share/api/notes/:noteId/blob", { params: { noteId: "viewParent" } }))+ .toMatchObject({ content: "<p>Parent body</p>", contentLength: 18 });+ expect(readJson("/share/api/attachments/:attachmentId/blob",+ { params: { attachmentId: "firstAttachment" } }))+ .toMatchObject({ content: "first text", contentLength: 10 });+ const lockedBlob = request("/share/api/notes/:noteId/blob",+ { params: { noteId: "viewLocked" } });+ expect(lockedBlob.status).toBe(401);+ });++ it("draws a note map, a relation map and a script bundle of only the readable notes", () => {+ const frontendMime = "application/javascript;env=frontend";+ buildShareTree([+ {+ id: "mapRoot",+ type: "noteMap",+ content: "",+ children: [+ { id: "mapReadable", content: "" },+ { "id": "mapLocked", "content": "", "#shareCredentials": "root:hunter2" }+ ]+ },+ {+ id: "relationMap",+ type: "relationMap",+ content: JSON.stringify({ notes: [ { noteId: "mapLocked" }, {} ] })+ },+ { id: "scriptNote", type: "code", mime: frontendMime, content: "run()" }+ ]);+ buildNote({+ id: "mapRoot",+ type: "noteMap",+ children: [ { id: "mapReadable" }, { id: "mapLocked" }, { id: "mapUnshared" } ]+ });+ buildNote({ id: "relationMap", type: "relationMap" });+ buildNote({ id: "scriptNote", type: "code", mime: frontendMime });+ const noteMap = (mapType: string, query: ShareRequest["query"] = {}) =>+ request("/share/api/note-map/:noteId/:mapType",+ { params: { noteId: "mapRoot", mapType }, query });++ const tree = JSON.parse(String(noteMap("tree").body));+ expect(tree.notes.map(([ noteId ]: [ string ]) => noteId).sort())+ .toEqual([ "mapReadable", "mapRoot" ]);+ expect(tree.links).toHaveLength(1);+ expect(Object.keys(tree.noteIdToDescendantCountMap)).not.toContain("mapLocked");+ const linkMap = noteMap("link",+ { excludeRelation: "imageLink", includeRelation: [ "author" ] });+ expect(JSON.parse(String(linkMap.body)).links).toEqual([]);+ expect(noteMap("bogus").status).toBe(404);++ expect(readJson("/share/api/relation-map/:noteId", { params: { noteId: "relationMap" } })+ .noteTitles).toEqual({});++ const scriptBundle = vi.spyOn(scriptService, "getScriptBundleForFrontend");+ const bundle = () => request("/share/api/script/bundle/:noteId",+ { params: { noteId: "scriptNote" } });+ const bundleOf = (allNoteIds: string[]) =>+ ({ script: "run()", html: "", allNoteIds }) as never;+ scriptBundle.mockReturnValue(bundleOf([ "scriptNote" ]));+ expect(JSON.parse(String(bundle().body))).toMatchObject({ script: "run()" });+ scriptBundle.mockReturnValue(bundleOf([ "scriptNote", "mapLocked" ]));+ expect(bundle().status).toBe(404);+ becca.reset();+ expect(JSON.parse(String(bundle().body)))+ .toEqual({ message: "Note 'scriptNote' has no script to run." });+ });+it("reads a search string without running it, answering its error", () => {const lint = (query: ShareRequest["query"]) => request("/share/api/search/lint", { query });vi.spyOn(searchService, "validateSearchQuery").mockImplementation((query) =>@@ -567,6 +676,10 @@ function request(path: ShareRoutePath, overrides: RequestOverrides = {}) {return handleShareRequest(getShareRoute(path), buildRequest(path, overrides));}+function readJson(path: ShareRoutePath, overrides: RequestOverrides = {}) {+ return JSON.parse(String(request(path, overrides).body));+}+type RequestOverrides = Partial<ShareRequest> & { headers?: Record<string, string> };function buildRequest(path: ShareRoutePath, overrides: RequestOverrides = {}): ShareRequest {diff --git a/packages/trilium-core/src/share/shaca/entities/snote.spec.ts b/packages/trilium-core/src/share/shaca/entities/snote.spec.tsindex 2a14e439ca..6c48c3d71b 100644--- a/packages/trilium-core/src/share/shaca/entities/snote.spec.ts+++ b/packages/trilium-core/src/share/shaca/entities/snote.spec.ts@@ -1,6 +1,8 @@import { afterEach, beforeEach, describe, expect, it } from "vitest";+import becca from "../../../becca/becca.js";import { encodeUtf8 } from "../../../services/utils/binary.js";+import { buildNote } from "../../../test/becca_easy_mocking.js";import { buildShareNote, stubShareSql } from "../../../test/shaca_mocking.js";import shaca from "../shaca.js";import SAttribute from "./sattribute.js";@@ -219,6 +221,19 @@ describe("SNote", () => {expect(shaca.getNote("child").getPojo().parentNoteIds).toEqual([ "parent" ]);});+ it("reads a label from the first built-in template it names, skipping the user's", () => {+ becca.reset();+ buildNote({ "id": "_template_board", "#subtreeHidden": "true" });+ buildNote({ "id": "userTemplate", "#subtreeHidden": "false" });+ const note = buildShareNote({ "id": "templated", "~template": "userTemplate" });+ addAttribute("builtInTemplate", "templated", "relation", "template", "_template_board");++ expect(note.getBuiltInTemplateLabelValue("subtreeHidden")).toBe("true");+ expect(note.getBuiltInTemplateLabelValue("viewType")).toBeNull();+ const untemplated = buildShareNote({ id: "untemplated" });+ expect(untemplated.getBuiltInTemplateLabelValue("subtreeHidden")).toBeNull();+ });+it("hides a protected note's title", () => {const note = buildShareNote({ id: "locked", title: "Secret plans", isProtected: true });