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(core): first batch of tests
Elian Doran51479dac482e
diff --git a/packages/trilium-core/src/services/app_info.spec.ts b/packages/trilium-core/src/services/app_info.spec.tsnew file mode 100644index 0000000000..96c581a619--- /dev/null+++ b/packages/trilium-core/src/services/app_info.spec.ts@@ -0,0 +1,49 @@+import { describe, expect, it } from "vitest";++import appInfo from "./app_info.js";+import build from "./build.js";+import packageJson from "../../package.json" with { type: "json" };+import { getMaxMigrationVersion } from "../migrations/migrations.js";++describe("app_info", () => {+ it("derives version metadata from package.json, build info and migrations", () => {+ // The version-bearing fields are wired straight from their sources, so+ // assert against those sources rather than hardcoding values that would+ // break on every release / migration bump.+ expect(appInfo.appVersion).toBe(packageJson.version);+ expect(appInfo.dbVersion).toBe(getMaxMigrationVersion());+ expect(appInfo.buildDate).toBe(build.buildDate);+ expect(appInfo.buildRevision).toBe(build.buildRevision);+ });++ it("exposes the fixed sync and clipper protocol versions", () => {+ // These are protocol constants; bumping them is a deliberate,+ // breaking change, so they are locked here as a regression guard.+ expect(appInfo.syncVersion).toBe(39);+ expect(appInfo.clipperProtocolVersion).toBe("1.0");+ });++ it("reports a valid current UTC timestamp", () => {+ // utcDateTime is generated at module load via new Date().toISOString().+ expect(appInfo.utcDateTime).toBe(new Date(appInfo.utcDateTime).toISOString());+ expect(appInfo.utcDateTime).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/);++ const generatedAt = new Date(appInfo.utcDateTime).getTime();+ expect(Number.isNaN(generatedAt)).toBe(false);+ // The timestamp is captured when the module is first imported, so it+ // must be in the past relative to the running test.+ expect(generatedAt).toBeLessThanOrEqual(Date.now());+ });++ it("populates every required AppInfo field with the expected primitive type", () => {+ expect(typeof appInfo.appVersion).toBe("string");+ expect(appInfo.appVersion.length).toBeGreaterThan(0);+ expect(typeof appInfo.dbVersion).toBe("number");+ expect(appInfo.dbVersion).toBeGreaterThan(0);+ expect(typeof appInfo.syncVersion).toBe("number");+ expect(typeof appInfo.buildDate).toBe("string");+ expect(typeof appInfo.buildRevision).toBe("string");+ expect(typeof appInfo.clipperProtocolVersion).toBe("string");+ expect(typeof appInfo.utcDateTime).toBe("string");+ });+});diff --git a/packages/trilium-core/src/services/attribute_formatter.spec.ts b/packages/trilium-core/src/services/attribute_formatter.spec.tsnew file mode 100644index 0000000000..ff74c0f5c4--- /dev/null+++ b/packages/trilium-core/src/services/attribute_formatter.spec.ts@@ -0,0 +1,73 @@+import type { AttributeRow } from "@triliumnext/commons";+import { describe, expect, it } from "vitest";++import attribute_formatter from "./attribute_formatter";++const { formatAttrForSearch } = attribute_formatter;++function label(name: string, value?: string): AttributeRow {+ return { type: "label", name, value };+}++function relation(name: string, value?: string): AttributeRow {+ return { type: "relation", name, value };+}++describe("formatAttrForSearch", () => {+ it("formats labels and relations with the correct prefix and no value", () => {+ expect(formatAttrForSearch(label("important"), false)).toBe("#important");+ expect(formatAttrForSearch(relation("author"), false)).toBe("~author");+ });++ it("omits the value when searchWithValue is false even if a value is present", () => {+ expect(formatAttrForSearch(label("year", "2024"), false)).toBe("#year");+ expect(formatAttrForSearch(relation("author", "abc123"), false)).toBe("~author");+ });++ it("omits the value when searchWithValue is true but the value is empty/undefined", () => {+ expect(formatAttrForSearch(label("year"), true)).toBe("#year");+ expect(formatAttrForSearch(label("year", ""), true)).toBe("#year");+ expect(formatAttrForSearch(relation("author", ""), true)).toBe("~author");+ });++ it("appends the value for labels when searchWithValue is true", () => {+ expect(formatAttrForSearch(label("year", "2024"), true)).toBe("#year=2024");+ });++ it("appends .noteId and the value for relations when searchWithValue is true", () => {+ expect(formatAttrForSearch(relation("author", "abc123"), true)).toBe("~author.noteId=abc123");+ });++ it("throws for an unrecognized attribute type", () => {+ const bogus = { type: "bogus", name: "x" } as unknown as AttributeRow;+ expect(() => formatAttrForSearch(bogus, false)).toThrow(/Unrecognized attribute type/);+ });+});++describe("formatAttrForSearch value quoting (formatValue)", () => {+ it("leaves bare word-character values unquoted", () => {+ expect(formatAttrForSearch(label("v", "abc_123"), true)).toBe("#v=abc_123");+ });++ it("wraps values containing non-word characters in double quotes", () => {+ expect(formatAttrForSearch(label("v", "hello world"), true)).toBe('#v="hello world"');+ expect(formatAttrForSearch(label("v", "a-b"), true)).toBe('#v="a-b"');+ });++ it("falls back to single quotes when the value contains a double quote", () => {+ expect(formatAttrForSearch(label("v", 'say "hi"'), true)).toBe("#v='say \"hi\"'");+ });++ it("falls back to backticks when the value contains both double and single quotes", () => {+ expect(formatAttrForSearch(label("v", `it's "ok"`), true)).toBe("#v=`it's \"ok\"`");+ });++ it("escapes double quotes when the value contains double, single and backtick", () => {+ const value = `a "b" 'c' \`d\``;+ expect(formatAttrForSearch(label("v", value), true)).toBe(`#v="a \\"b\\" 'c' \`d\`"`);+ });++ it("applies the same quoting rules to relation values after .noteId", () => {+ expect(formatAttrForSearch(relation("r", "weird value"), true)).toBe('~r.noteId="weird value"');+ });+});diff --git a/packages/trilium-core/src/services/attributes.spec.ts b/packages/trilium-core/src/services/attributes.spec.tsnew file mode 100644index 0000000000..1227426c53--- /dev/null+++ b/packages/trilium-core/src/services/attributes.spec.ts@@ -0,0 +1,217 @@+import type { AttributeRow } from "@triliumnext/commons";+import { beforeAll, describe, expect, it } from "vitest";++import becca from "../becca/becca.js";+import { init as clsInit } from "./context.js";+import noteService from "./notes.js";+import attributeService from "./attributes.js";++const {+ getNotesWithLabel,+ getNoteWithLabel,+ createLabel,+ createRelation,+ createAttribute,+ getAttributeNames,+ isAttributeType,+ isAttributeDangerous+} = attributeService;++/** Creates a fresh text note under root and returns its id (inside a CLS context). */+function makeNote(title: string): string {+ return clsInit(() =>+ noteService.createNewNote({+ parentNoteId: "root",+ title,+ content: "",+ type: "text"+ }).note.noteId+ );+}++describe("attributes service", () => {+ beforeAll(() => {+ // The in-memory fixture DB and initializeCore are booted by the+ // server suite setup (apps/server/spec/setup.ts), through which+ // co-located trilium-core specs run.+ });++ describe("isAttributeType (pure)", () => {+ it("recognizes only label and relation as attribute types", () => {+ expect(isAttributeType("label")).toBe(true);+ expect(isAttributeType("relation")).toBe(true);+ expect(isAttributeType("definition")).toBe(false);+ expect(isAttributeType("")).toBe(false);+ expect(isAttributeType("Label")).toBe(false); // case-sensitive+ });+ });++ describe("isAttributeDangerous (pure)", () => {+ it("flags built-in dangerous attributes and ignores the type/name combination", () => {+ // `run` is a dangerous label, `widget` is dangerous for both types.+ expect(isAttributeDangerous("label", "run")).toBe(true);+ expect(isAttributeDangerous("label", "widget")).toBe(true);+ expect(isAttributeDangerous("relation", "widget")).toBe(true);+ // `template` exists as both label and relation but is never dangerous.+ expect(isAttributeDangerous("label", "template")).toBe(false);+ expect(isAttributeDangerous("relation", "template")).toBe(false);+ // `run` is a label, not a relation, so the relation lookup misses.+ expect(isAttributeDangerous("relation", "run")).toBe(false);+ });++ it("matches case-insensitively and trims whitespace from the name", () => {+ expect(isAttributeDangerous("label", "RUN")).toBe(true);+ expect(isAttributeDangerous("label", " run ")).toBe(true);+ expect(isAttributeDangerous("label", " WiDgEt ")).toBe(true);+ });++ it("returns false for unknown names and unknown types", () => {+ expect(isAttributeDangerous("label", "definitelyNotABuiltin")).toBe(false);+ expect(isAttributeDangerous("bogusType", "run")).toBe(false);+ });+ });++ describe("createAttribute / createLabel / createRelation (real DB)", () => {+ it("persists a label via createLabel and exposes it through becca", () => {+ const noteId = makeNote("createLabel target");++ const attr = clsInit(() => createLabel(noteId, "myUniqueLabelOne", "alpha"));++ expect(attr.attributeId).toBeTruthy();+ expect(attr.type).toBe("label");+ expect(attr.name).toBe("myUniqueLabelOne");+ expect(attr.value).toBe("alpha");++ const note = becca.getNote(noteId);+ expect(note?.getOwnedLabelValue("myUniqueLabelOne")).toBe("alpha");+ expect(becca.attributes[attr.attributeId]).toBe(attr);+ });++ it("defaults the label value to an empty string when omitted", () => {+ const noteId = makeNote("createLabel default value");++ const attr = clsInit(() => createLabel(noteId, "myUniqueLabelTwo"));++ expect(attr.value).toBe("");+ expect(becca.getNote(noteId)?.getOwnedLabelValue("myUniqueLabelTwo")).toBe("");+ });++ it("persists a relation pointing at the target note via createRelation", () => {+ const sourceId = makeNote("relation source");+ const targetId = makeNote("relation target");++ const attr = clsInit(() => createRelation(sourceId, "myUniqueRel", targetId));++ expect(attr.type).toBe("relation");+ expect(attr.name).toBe("myUniqueRel");+ expect(attr.value).toBe(targetId);++ const source = becca.getNote(sourceId);+ expect(source?.getRelationValue("myUniqueRel")).toBe(targetId);+ expect(source?.getRelationTarget("myUniqueRel")?.noteId).toBe(targetId);+ });++ it("createAttribute saves an arbitrary AttributeRow", () => {+ const noteId = makeNote("createAttribute target");+ const row: AttributeRow = {+ noteId,+ type: "label",+ name: "myUniqueRawAttr",+ value: "raw"+ };++ const attr = clsInit(() => createAttribute(row));++ expect(attr.attributeId).toBeTruthy();+ expect(becca.attributes[attr.attributeId]?.name).toBe("myUniqueRawAttr");+ expect(becca.getNote(noteId)?.getOwnedLabelValue("myUniqueRawAttr")).toBe("raw");+ });+ });++ describe("getNoteWithLabel (real DB, becca-optimized lookup)", () => {+ it("returns the note carrying the label when no value filter is given", () => {+ const noteId = makeNote("labelled note");+ clsInit(() => createLabel(noteId, "myFindableLabel", "someValue"));++ const found = getNoteWithLabel("myFindableLabel");+ expect(found?.noteId).toBe(noteId);+ });++ it("filters by value case-insensitively and returns null when nothing matches", () => {+ const noteId = makeNote("valued label note");+ clsInit(() => createLabel(noteId, "myValuedLabel", "MixedCaseValue"));++ // Matching value, but with different casing.+ expect(getNoteWithLabel("myValuedLabel", "mixedcasevalue")?.noteId).toBe(noteId);+ // No attribute has this value.+ expect(getNoteWithLabel("myValuedLabel", "nonExistentValue")).toBe(null);+ });++ it("returns undefined for a label that does not exist at all", () => {+ expect(getNoteWithLabel("noSuchLabelAnywhere")).toBeUndefined();+ });+ });++ describe("getNotesWithLabel (real DB, via search)", () => {+ it("returns all notes carrying a label, optionally filtered by value", () => {+ const first = makeNote("multi label A");+ const second = makeNote("multi label B");+ const third = makeNote("multi label C");++ clsInit(() => {+ createLabel(first, "mySharedLabel", "x");+ createLabel(second, "mySharedLabel", "x");+ createLabel(third, "mySharedLabel", "y");+ });++ const all = getNotesWithLabel("mySharedLabel");+ const allIds = all.map((n) => n.noteId);+ expect(allIds).toEqual(expect.arrayContaining([first, second, third]));++ const onlyX = getNotesWithLabel("mySharedLabel", "x").map((n) => n.noteId);+ expect(onlyX).toEqual(expect.arrayContaining([first, second]));+ expect(onlyX).not.toContain(third);+ });++ it("returns an empty array when no note carries the label", () => {+ expect(getNotesWithLabel("yetAnotherMissingLabel")).toEqual([]);+ });+ });++ describe("getAttributeNames (real DB + built-ins)", () => {+ it("returns built-in names matching the search, sorted with prefix matches first", () => {+ const names = getAttributeNames("label", "share");++ // All results match the (case-insensitive) substring.+ expect(names.every((n) => n.toLowerCase().includes("share"))).toBe(true);+ // Known built-in share labels are present.+ expect(names).toContain("shareAlias");+ expect(names).toContain("shareRoot");+ // Names that start with the query sort before those that merely contain it,+ // and within each group the order is alphabetical.+ const prefixNames = names.filter((n) => n.toLowerCase().startsWith("share"));+ const sortedPrefix = [...prefixNames].sort((a, b) => (a < b ? -1 : 1));+ expect(prefixNames).toEqual(sortedPrefix);+ });++ it("includes a user-created attribute name and matches case-insensitively", () => {+ const noteId = makeNote("named attr note");+ clsInit(() => createLabel(noteId, "zzCustomNamedLabel", "v"));++ // Upper-cased query still finds the lower-cased stored name.+ const names = getAttributeNames("label", "ZZCUSTOMNAMED");+ expect(names).toContain("zzCustomNamedLabel");+ });++ it("filters out internal link-style relation names", () => {+ const names = getAttributeNames("relation", "link");+ expect(names).not.toContain("internalLink");+ expect(names).not.toContain("imageLink");+ expect(names).not.toContain("relationMapLink");+ });++ it("returns no built-in noise for a query that matches nothing", () => {+ expect(getAttributeNames("label", "xyzzy_no_such_attr_name")).toEqual([]);+ });+ });+});diff --git a/packages/trilium-core/src/services/backup.spec.ts b/packages/trilium-core/src/services/backup.spec.tsnew file mode 100644index 0000000000..9a5fe3ebfe--- /dev/null+++ b/packages/trilium-core/src/services/backup.spec.ts@@ -0,0 +1,261 @@+import type { DatabaseBackup, FilterOptionsByType, OptionNames } from "@triliumnext/commons";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import BackupService, { getBackup, initBackup } from "./backup.js";+import type { BackupOptionsService } from "./backup.js";+import dateUtils from "./utils/date.js";++/**+ * A simple in-memory options service used to drive the abstract backup logic.+ * Mirrors the three methods the real BackupOptionsService exposes.+ */+class FakeOptions implements BackupOptionsService {+ private readonly store: Record<string, string>;++ constructor(initial: Record<string, string> = {}) {+ this.store = { ...initial };+ }++ getOption(name: OptionNames): string {+ return this.store[name] ?? "";+ }++ getOptionBool(name: FilterOptionsByType<boolean>): boolean {+ return this.store[name] === "true";+ }++ setOption(name: OptionNames, value: string): void {+ this.store[name] = value;+ }+}++/**+ * Concrete subclass exposing the protected scheduling logic and recording the+ * backups it is asked to create. The other abstract members are stubbed.+ */+class TestBackupService extends BackupService {+ public readonly created: string[] = [];++ async backupNow(name: string): Promise<string> {+ this.created.push(name);+ return `backup-${name}.db`;+ }++ scheduleBackups(): void {+ /* no-op for tests */+ }++ async getExistingBackups(): Promise<DatabaseBackup[]> {+ return [];+ }++ async getBackupContent(): Promise<Uint8Array | null> {+ return null;+ }++ // Expose protected members for direct assertions.+ public runScheduledBackupsPublic(): Promise<void> {+ return this.runScheduledBackups();+ }++ public periodBackupPublic(+ optionName: "lastDailyBackupDate" | "lastWeeklyBackupDate" | "lastMonthlyBackupDate",+ backupType: "daily" | "weekly" | "monthly",+ periodInSeconds: number+ ): Promise<void> {+ return this.periodBackup(optionName, backupType, periodInSeconds);+ }++ public isBackupEnabledPublic(backupType: "daily" | "weekly" | "monthly"): boolean {+ return this.isBackupEnabled(backupType);+ }+}++const DAY = 24 * 3600;++/** An old UTC date-time string guaranteed to be far in the past. */+const LONG_AGO = "2000-01-01 00:00:00.000Z";++describe("BackupService singleton (getBackup / initBackup)", () => {+ it("getBackup throws before the service is initialized", async () => {+ // Re-import the module in isolation so the module-level singleton is+ // guaranteed to be undefined (other tests in this file install one).+ vi.resetModules();+ const fresh = await import("./backup.js");+ expect(() => fresh.getBackup()).toThrow(/not initialized/);+ });++ it("initBackup installs the provider returned by getBackup", () => {+ const provider = new TestBackupService(new FakeOptions());+ initBackup(provider);+ expect(getBackup()).toBe(provider);++ // Replacing it swaps the instance returned.+ const replacement = new TestBackupService(new FakeOptions());+ initBackup(replacement);+ expect(getBackup()).toBe(replacement);+ expect(getBackup()).not.toBe(provider);+ });+});++describe("BackupService.isBackupEnabled", () => {+ it("maps each backup type to the matching boolean option", () => {+ const service = new TestBackupService(+ new FakeOptions({+ dailyBackupEnabled: "true",+ weeklyBackupEnabled: "false",+ monthlyBackupEnabled: "true"+ })+ );++ expect(service.isBackupEnabledPublic("daily")).toBe(true);+ expect(service.isBackupEnabledPublic("weekly")).toBe(false);+ expect(service.isBackupEnabledPublic("monthly")).toBe(true);+ });++ it("treats a missing / non-'true' option value as disabled", () => {+ const service = new TestBackupService(new FakeOptions());+ expect(service.isBackupEnabledPublic("daily")).toBe(false);+ expect(service.isBackupEnabledPublic("weekly")).toBe(false);+ expect(service.isBackupEnabledPublic("monthly")).toBe(false);+ });+});++describe("BackupService.periodBackup", () => {+ it("does nothing when the backup type is disabled", async () => {+ const options = new FakeOptions({+ dailyBackupEnabled: "false",+ lastDailyBackupDate: LONG_AGO+ });+ const service = new TestBackupService(options);++ await service.periodBackupPublic("lastDailyBackupDate", "daily", DAY);++ expect(service.created).toEqual([]);+ // The last-backup option is left untouched.+ expect(options.getOption("lastDailyBackupDate")).toBe(LONG_AGO);+ });++ it("creates a backup and records the new timestamp when the period has elapsed", async () => {+ const options = new FakeOptions({+ dailyBackupEnabled: "true",+ lastDailyBackupDate: LONG_AGO+ });+ const service = new TestBackupService(options);++ await service.periodBackupPublic("lastDailyBackupDate", "daily", DAY);++ expect(service.created).toEqual(["daily"]);+ // The timestamp is advanced to (roughly) now, and is parseable.+ const stored = options.getOption("lastDailyBackupDate");+ expect(stored).not.toBe(LONG_AGO);+ const parsed = dateUtils.parseDateTime(stored);+ expect(Math.abs(parsed.getTime() - Date.now())).toBeLessThan(5000);+ });++ it("does not create a backup when the last one is still within the period", async () => {+ // Last backup was "now"; the period is one day, so nothing is due.+ const recent = dateUtils.utcNowDateTime();+ const options = new FakeOptions({+ weeklyBackupEnabled: "true",+ lastWeeklyBackupDate: recent+ });+ const service = new TestBackupService(options);++ await service.periodBackupPublic("lastWeeklyBackupDate", "weekly", 7 * DAY);++ expect(service.created).toEqual([]);+ expect(options.getOption("lastWeeklyBackupDate")).toBe(recent);+ });++ it("uses the boundary strictly (exactly the period elapsed is not yet due)", async () => {+ // Pin "now" so the elapsed time equals the period exactly.+ const fixedNow = new Date("2024-06-01T00:00:00.000Z");+ vi.useFakeTimers();+ vi.setSystemTime(fixedNow);+ try {+ const exactlyOneDayAgo = "2024-05-31 00:00:00.000Z";+ const options = new FakeOptions({+ dailyBackupEnabled: "true",+ lastDailyBackupDate: exactlyOneDayAgo+ });+ const service = new TestBackupService(options);++ await service.periodBackupPublic("lastDailyBackupDate", "daily", DAY);++ // now - last === period, and the check is strictly greater-than.+ expect(service.created).toEqual([]);+ expect(options.getOption("lastDailyBackupDate")).toBe(exactlyOneDayAgo);+ } finally {+ vi.useRealTimers();+ }+ });+});++describe("BackupService.runScheduledBackups", () => {+ it("runs the daily/weekly/monthly checks, backing up only the enabled & due ones", async () => {+ const options = new FakeOptions({+ dailyBackupEnabled: "true",+ weeklyBackupEnabled: "false",+ monthlyBackupEnabled: "true",+ lastDailyBackupDate: LONG_AGO,+ lastWeeklyBackupDate: LONG_AGO,+ lastMonthlyBackupDate: LONG_AGO+ });+ const service = new TestBackupService(options);++ await service.runScheduledBackupsPublic();++ // Weekly is disabled, so only daily and monthly run; order is preserved.+ expect(service.created).toEqual(["daily", "monthly"]);+ expect(options.getOption("lastWeeklyBackupDate")).toBe(LONG_AGO);+ expect(options.getOption("lastDailyBackupDate")).not.toBe(LONG_AGO);+ expect(options.getOption("lastMonthlyBackupDate")).not.toBe(LONG_AGO);+ });+});++describe("BackupService.regularBackup", () => {+ let errorSpy: ReturnType<typeof vi.spyOn>;++ beforeEach(() => {+ errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});+ });++ afterEach(() => {+ errorSpy.mockRestore();+ });++ it("runs the scheduled backups inside an execution context", async () => {+ const options = new FakeOptions({+ dailyBackupEnabled: "true",+ lastDailyBackupDate: LONG_AGO+ });+ const service = new TestBackupService(options);++ service.regularBackup();+ // runScheduledBackups is async and fire-and-forget; let it settle.+ await vi.waitFor(() => expect(service.created).toContain("daily"));++ expect(errorSpy).not.toHaveBeenCalled();+ });++ it("logs (and swallows) errors thrown by the scheduled backups", async () => {+ const options = new FakeOptions({+ dailyBackupEnabled: "true",+ lastDailyBackupDate: LONG_AGO+ });+ const service = new TestBackupService(options);+ const boom = new Error("backup blew up");+ vi.spyOn(service, "backupNow").mockRejectedValue(boom);++ // Must not throw synchronously even though the backup rejects.+ expect(() => service.regularBackup()).not.toThrow();++ await vi.waitFor(() =>+ expect(errorSpy).toHaveBeenCalledWith(+ "[Backup] Error running scheduled backups:",+ boom+ )+ );+ });+});diff --git a/packages/trilium-core/src/services/blob.spec.ts b/packages/trilium-core/src/services/blob.spec.tsnew file mode 100644index 0000000000..7587144044--- /dev/null+++ b/packages/trilium-core/src/services/blob.spec.ts@@ -0,0 +1,191 @@+import { describe, expect, it } from "vitest";++import becca from "../becca/becca.js";+import type BNote from "../becca/entities/bnote.js";+import { NotFoundError } from "../errors.js";+import blob from "./blob.js";+import { getContext } from "./context.js";+import protectedSessionService from "./protected_session.js";+import dataEncryption from "./encryption/data_encryption.js";+import notesService from "./notes.js";+import { decodeUtf8, encodeUtf8 } from "./utils/binary.js";+import { hash } from "./utils/index.js";++// These specs run through the server suite (apps/server/spec/setup.ts), which+// boots an in-memory fixture DB and calls initializeCore. getBlobPojo reads+// notes from becca and blobs from SQL, and createNewNote (used to seed test+// content) is a write path, so anything touching the DB is wrapped in a CLS+// context via getContext().init(...).+function withContext<T>(fn: () => T): Promise<T> {+ return new Promise<T>((resolve, reject) => {+ getContext().init(async () => {+ try {+ resolve(await fn());+ } catch (e) {+ reject(e);+ }+ });+ });+}++const PROTECTED_KEY = encodeUtf8("0123456789abcdef"); // exactly 16 bytes++describe("blob", () => {+ describe("calculateContentHash", () => {+ it("matches the manual hash of the concatenated blobId, content and text representation", () => {+ const result = blob.calculateContentHash({+ blobId: "blob123",+ content: "hello world",+ textRepresentation: "hello world"+ });++ expect(result).toBe(hash("blob123|hello world|hello world"));+ });++ it("omits the text representation segment when it is falsy", () => {+ const params = { blobId: "blobX", content: "the content" };++ const withNull = blob.calculateContentHash({ ...params, textRepresentation: null });+ const withEmpty = blob.calculateContentHash({ ...params, textRepresentation: "" });++ // No trailing "|..." segment is appended for null/empty text representation.+ expect(withNull).toBe(hash("blobX|the content"));+ expect(withEmpty).toBe(hash("blobX|the content"));+ expect(withNull).toBe(withEmpty);+ });++ it("is deterministic and sensitive to every input", () => {+ const base = { blobId: "b", content: "c", textRepresentation: "t" };++ // Same inputs always produce the same hash.+ expect(blob.calculateContentHash(base)).toBe(blob.calculateContentHash({ ...base }));++ // Changing any single field changes the hash.+ expect(blob.calculateContentHash({ ...base, blobId: "b2" })).not.toBe(blob.calculateContentHash(base));+ expect(blob.calculateContentHash({ ...base, content: "c2" })).not.toBe(blob.calculateContentHash(base));+ expect(blob.calculateContentHash({ ...base, textRepresentation: "t2" })).not.toBe(blob.calculateContentHash(base));+ });++ it("stringifies buffer content via toString before hashing", () => {+ const content = encodeUtf8("buffer payload");++ // The implementation uses content.toString(); a Uint8Array stringifies+ // to its comma-separated byte values, not the decoded text.+ expect(blob.calculateContentHash({ blobId: "bb", content, textRepresentation: null }))+ .toBe(hash(`bb|${content.toString()}`));+ });+ });++ describe("processContent (unprotected)", () => {+ it("decodes buffer string content to text and passes through plain strings", () => {+ const buffer = encodeUtf8("héllo — 世界");++ expect(blob.processContent(buffer, false, true)).toBe("héllo — 世界");+ expect(blob.processContent("already a string", false, true)).toBe("already a string");+ });++ it("returns an empty string for null string content", () => {+ expect(blob.processContent(null, false, true)).toBe("");+ });++ it("returns binary content unchanged and substitutes a zero-length buffer for null", () => {+ const payload = Uint8Array.from([1, 2, 3, 254, 255]);+ expect(blob.processContent(payload, false, false)).toBe(payload);++ const result = blob.processContent(null, false, false) as Uint8Array;+ expect(result).toBeInstanceOf(Uint8Array);+ expect(result.length).toBe(0);+ });+ });++ describe("processContent (protected)", () => {+ it("blanks protected content when no protected session is available", () => {+ // No data key set -> session unavailable.+ protectedSessionService.resetDataKey();+ expect(protectedSessionService.isProtectedSessionAvailable()).toBe(false);++ // String content path: encrypted bytes are replaced by "" before decoding.+ expect(blob.processContent(encodeUtf8("secret"), true, true)).toBe("");++ // Binary path: protection blanks the content to the empty string, which+ // is not null, so the zero-length-buffer fallback is skipped and "" is+ // returned verbatim.+ expect(blob.processContent(encodeUtf8("secret"), true, false)).toBe("");+ });++ it("decrypts protected content when a protected session is available", () => {+ protectedSessionService.setDataKey(PROTECTED_KEY);+ try {+ const cipherText = dataEncryption.encrypt(PROTECTED_KEY, "top secret");++ // String content: decrypted bytes are then UTF-8 decoded to text.+ expect(blob.processContent(cipherText, true, true)).toBe("top secret");++ // Binary content: returns the decrypted buffer as-is.+ const binary = blob.processContent(cipherText, true, false) as Uint8Array;+ expect(decodeUtf8(binary)).toBe("top secret");+ } finally {+ protectedSessionService.resetDataKey();+ }+ });++ it("returns an empty string for null protected string content with a session", () => {+ protectedSessionService.setDataKey(PROTECTED_KEY);+ try {+ // decrypt(null) yields null, and the string branch maps null -> "".+ expect(blob.processContent(null, true, true)).toBe("");+ } finally {+ protectedSessionService.resetDataKey();+ }+ });+ });++ describe("getBlobPojo", () => {+ it("throws NotFoundError when the entity does not exist", async () => {+ await expect(withContext(() => blob.getBlobPojo("notes", "doesNotExist123"))).rejects.toBeInstanceOf(NotFoundError);+ });++ it("returns the decoded string content of a text note's blob", async () => {+ const { noteId, content, blobId } = await withContext(() => {+ const { note } = notesService.createNewNote({+ parentNoteId: "root",+ title: "blob spec text note",+ content: "<p>blob spec body</p>",+ type: "text"+ });++ const pojo = blob.getBlobPojo("notes", note.noteId);+ return { noteId: note.noteId, content: pojo.content, blobId: pojo.blobId };+ });++ expect(content).toBe("<p>blob spec body</p>");+ expect(typeof blobId).toBe("string");+ // The seeded note is the same instance retrieved by getEntity.+ expect(becca.notes[noteId]).toBeDefined();+ });++ it("nulls out the content for a note with binary (non-string) content", async () => {+ const binary = Uint8Array.from([0, 1, 2, 3, 4, 5]);++ const { pojoContent, contentLength } = await withContext(() => {+ const { note } = notesService.createNewNote({+ parentNoteId: "root",+ title: "blob spec image note",+ content: binary,+ type: "image",+ mime: "image/png"+ });++ // Sanity: an image note does not have string content.+ expect((note as BNote).hasStringContent()).toBe(false);++ const pojo = blob.getBlobPojo("notes", note.noteId);+ return { pojoContent: pojo.content, contentLength: pojo.contentLength };+ });++ // Binary blobs come back with content nulled but contentLength preserved.+ expect(pojoContent).toBeNull();+ expect(contentLength).toBeGreaterThan(0);+ });+ });+});diff --git a/packages/trilium-core/src/services/branches.spec.ts b/packages/trilium-core/src/services/branches.spec.tsnew file mode 100644index 0000000000..755557e10b--- /dev/null+++ b/packages/trilium-core/src/services/branches.spec.ts@@ -0,0 +1,181 @@+import { describe, expect, it } from "vitest";++import becca from "../becca/becca.js";+import type BBranch from "../becca/entities/bbranch.js";+import type BNote from "../becca/entities/bnote.js";+import branchService from "./branches.js";+import { getContext } from "./context.js";+import noteService from "./notes.js";+import { getSql } from "./sql/index.js";++/**+ * Wraps a callback in a CLS context. Entity mutations (createNewNote,+ * branch.save(), branch.markAsDeleted()) require CLS to be initialised.+ */+function withContext<T>(fn: () => T): T {+ return getContext().init(fn);+}++let counter = 0;++/**+ * Creates a fresh text note under the given parent in the real in-memory DB.+ * Each call uses a unique title since the same fixture DB is shared between+ * the `it()`s in this file.+ */+function createNote(parentNoteId: string): { note: BNote; branch: BBranch } {+ counter++;+ return withContext(() =>+ noteService.createNewNote({+ parentNoteId,+ title: `branches-spec-${counter}`,+ content: "<p>hello</p>",+ type: "text"+ })+ );+}++describe("branches service (real DB)", () => {+ describe("moveBranchToNote", () => {+ it("is a no-op when the branch already lives under the target parent", () => {+ const { branch } = createNote("root");++ const res = withContext(() => branchService.moveBranchToNote(branch, "root"));++ expect(res).toEqual({ success: true });+ // The original branch must remain, no clone created.+ expect(branch.isDeleted).toBe(false);+ });++ it("moves a branch to a new parent, deleting the old branch and computing the position", () => {+ const parent = createNote("root");+ const child = createNote("root");++ // Seed an existing child under the target parent so we can verify+ // the new position is derived from MAX(notePosition) + 10.+ const sibling = createNote(parent.note.noteId);+ const maxPos = getSql().getValue<number>(+ "SELECT MAX(notePosition) FROM branches WHERE parentNoteId = ? AND isDeleted = 0",+ [parent.note.noteId]+ );++ const res = withContext(() =>+ branchService.moveBranchToNote(child.branch, parent.note.noteId)+ ) as { success: boolean; branch: BBranch };++ expect(res.success).toBe(true);+ expect(res.branch).toBeDefined();+ expect(res.branch.parentNoteId).toBe(parent.note.noteId);+ expect(res.branch.noteId).toBe(child.note.noteId);+ expect(res.branch.notePosition).toBe(maxPos + 10);++ // The freshly created branch is reachable through becca.+ expect(becca.getBranchFromChildAndParent(child.note.noteId, parent.note.noteId)).toBe(res.branch);+ // The note is now a child of the target parent.+ expect(parent.note.getChildNotes().some((n) => n.noteId === child.note.noteId)).toBe(true);+ // The original branch (under root) has been deleted.+ expect(child.branch.isDeleted).toBe(true);+ // The pre-existing sibling branch is untouched.+ expect(sibling.branch.isDeleted).toBe(false);+ });++ it("refuses to move protected structural notes and returns the validation tuple", () => {+ // The root branch cannot be relocated; validateParentChild rejects it.+ const rootBranch = becca.getBranchFromChildAndParent("root", "none");+ expect(rootBranch).not.toBeNull();++ const someParent = createNote("root");++ const res = withContext(() =>+ branchService.moveBranchToNote(rootBranch!, someParent.note.noteId)+ ) as [number, { success: boolean; message?: string }];++ expect(Array.isArray(res)).toBe(true);+ expect(res[0]).toBe(200);+ expect(res[1].success).toBe(false);+ expect(typeof res[1].message).toBe("string");++ // No clone was created under the candidate parent.+ expect(becca.getBranchFromChildAndParent("root", someParent.note.noteId)).toBeNull();+ });++ it("refuses a move that would create a tree cycle", () => {+ const ancestor = createNote("root");+ const descendant = createNote(ancestor.note.noteId);++ // Moving the ancestor under its own descendant is a cycle.+ const res = withContext(() =>+ branchService.moveBranchToNote(ancestor.branch, descendant.note.noteId)+ ) as [number, { success: boolean; message?: string }];++ expect(Array.isArray(res)).toBe(true);+ expect(res[0]).toBe(200);+ expect(res[1].success).toBe(false);+ expect(ancestor.branch.isDeleted).toBe(false);+ });+ });++ describe("moveBranchToBranch", () => {+ it("moves the branch and expands a collapsed target parent branch", () => {+ const targetParent = createNote("root");+ const child = createNote("root");++ targetParent.branch.isExpanded = false;++ const res = withContext(() =>+ branchService.moveBranchToBranch(child.branch, targetParent.branch, "ignored-branch-id")+ ) as { success: boolean; branch: BBranch };++ expect(res.success).toBe(true);+ expect(res.branch.parentNoteId).toBe(targetParent.note.noteId);+ // Target parent branch is expanded so the new placement is visible.+ expect(targetParent.branch.isExpanded).toBe(true);+ });++ it("leaves an already-expanded target parent branch untouched", () => {+ const targetParent = createNote("root");+ const child = createNote("root");++ targetParent.branch.isExpanded = true;++ const res = withContext(() =>+ branchService.moveBranchToBranch(child.branch, targetParent.branch, "ignored-branch-id")+ ) as { success: boolean; branch: BBranch };++ expect(res.success).toBe(true);+ expect(targetParent.branch.isExpanded).toBe(true);+ });++ it("expands the target on the no-op path since the result still reports success", () => {+ const targetParent = createNote("root");+ const child = createNote(targetParent.note.noteId);++ targetParent.branch.isExpanded = false;++ const res = withContext(() =>+ branchService.moveBranchToBranch(child.branch, targetParent.branch, "ignored-branch-id")+ );++ // The underlying move is a no-op, but it still returns { success: true },+ // so moveBranchToBranch proceeds to expand the collapsed target parent.+ expect(res).toEqual({ success: true });+ expect(targetParent.branch.isExpanded).toBe(true);+ });++ it("propagates a validation failure and does not expand the target", () => {+ const targetParent = createNote("root");+ const rootBranch = becca.getBranchFromChildAndParent("root", "none");++ targetParent.branch.isExpanded = false;++ const res = withContext(() =>+ branchService.moveBranchToBranch(rootBranch!, targetParent.branch, "ignored-branch-id")+ ) as [number, { success: boolean }];++ expect(Array.isArray(res)).toBe(true);+ expect(res[0]).toBe(200);+ expect(res[1].success).toBe(false);+ expect(targetParent.branch.isExpanded).toBe(false);+ });+ });+});diff --git a/packages/trilium-core/src/services/bulk_actions.spec.ts b/packages/trilium-core/src/services/bulk_actions.spec.tsnew file mode 100644index 0000000000..6761337fd0--- /dev/null+++ b/packages/trilium-core/src/services/bulk_actions.spec.ts@@ -0,0 +1,336 @@+import type { BulkAction } from "@triliumnext/commons";+import { describe, expect, it } from "vitest";++import becca from "../becca/becca.js";+import type BBranch from "../becca/entities/bbranch.js";+import type BNote from "../becca/entities/bnote.js";+import bulkActionService from "./bulk_actions.js";+import cloningService from "./cloning.js";+import { getContext } from "./context.js";+import noteService from "./notes.js";++/**+ * Wraps a callback in a CLS context. Entity mutations (createNewNote,+ * note.save(), attribute.save()) require CLS to be initialised.+ */+function withContext<T>(fn: () => T): T {+ return getContext().init(fn);+}++let counter = 0;++/**+ * Creates a fresh text note under the given parent in the real in-memory DB.+ * Each call uses a unique title since the same fixture DB is shared between+ * the `it()`s in this file.+ */+function createNote(parentNoteId: string): { note: BNote; branch: BBranch } {+ counter++;+ return withContext(() =>+ noteService.createNewNote({+ parentNoteId,+ title: `bulk-actions-spec-${counter}`,+ content: "<p>hello</p>",+ type: "text"+ })+ );+}++describe("bulk_actions service (real DB)", () => {+ describe("executeActions", () => {+ it("skips note IDs that don't resolve to a note", () => {+ // No note exists for this id, so nothing should throw and no handler runs.+ expect(() =>+ withContext(() =>+ bulkActionService.executeActions(+ [{ name: "addLabel", labelName: "foo", labelValue: "bar" }],+ ["doesNotExist123"]+ )+ )+ ).not.toThrow();+ });++ it("accepts both an array and a Set of note IDs", () => {+ const a = createNote("root");+ const b = createNote("root");++ withContext(() =>+ bulkActionService.executeActions(+ [{ name: "addLabel", labelName: "fromSet" }],+ new Set([a.note.noteId, b.note.noteId])+ )+ );++ expect(a.note.hasLabel("fromSet")).toBe(true);+ expect(b.note.hasLabel("fromSet")).toBe(true);+ });++ it("isolates per-note handler failures and keeps applying to remaining notes", () => {+ const note = createNote("root");++ // executeScript throws (ReferenceError), but the failure is caught per action,+ // so the subsequent addLabel action still runs against the same note.+ const actions: BulkAction[] = [+ { name: "executeScript", script: "thisIsNotDefined()" },+ { name: "addLabel", labelName: "appliedAfterFailure" }+ ];++ expect(() => withContext(() => bulkActionService.executeActions(actions, [note.note.noteId]))).not.toThrow();+ expect(note.note.hasLabel("appliedAfterFailure")).toBe(true);+ });+ });++ describe("label actions", () => {+ it("addLabel / updateLabelValue / renameLabel / deleteLabel", () => {+ const note = createNote("root");++ withContext(() =>+ bulkActionService.executeActions(+ [{ name: "addLabel", labelName: "color", labelValue: "red" }],+ [note.note.noteId]+ )+ );+ expect(note.note.getOwnedLabelValue("color")).toBe("red");++ withContext(() =>+ bulkActionService.executeActions(+ [{ name: "updateLabelValue", labelName: "color", labelValue: "blue" }],+ [note.note.noteId]+ )+ );+ expect(note.note.getOwnedLabelValue("color")).toBe("blue");++ withContext(() =>+ bulkActionService.executeActions(+ [{ name: "renameLabel", oldLabelName: "color", newLabelName: "shade" }],+ [note.note.noteId]+ )+ );+ expect(note.note.hasOwnedLabel("color")).toBe(false);+ expect(note.note.getOwnedLabelValue("shade")).toBe("blue");++ withContext(() =>+ bulkActionService.executeActions([{ name: "deleteLabel", labelName: "shade" }], [note.note.noteId])+ );+ expect(note.note.hasOwnedLabel("shade")).toBe(false);+ });+ });++ describe("relation actions", () => {+ it("addRelation / updateRelationTarget / renameRelation / deleteRelation", () => {+ const note = createNote("root");+ const targetA = createNote("root");+ const targetB = createNote("root");++ withContext(() =>+ bulkActionService.executeActions(+ [{ name: "addRelation", relationName: "link", targetNoteId: targetA.note.noteId }],+ [note.note.noteId]+ )+ );+ expect(note.note.getOwnedRelationValue("link")).toBe(targetA.note.noteId);++ withContext(() =>+ bulkActionService.executeActions(+ [{ name: "updateRelationTarget", relationName: "link", targetNoteId: targetB.note.noteId }],+ [note.note.noteId]+ )+ );+ expect(note.note.getOwnedRelationValue("link")).toBe(targetB.note.noteId);++ withContext(() =>+ bulkActionService.executeActions(+ [{ name: "renameRelation", oldRelationName: "link", newRelationName: "ref" }],+ [note.note.noteId]+ )+ );+ expect(note.note.getOwnedRelations("link").length).toBe(0);+ expect(note.note.getOwnedRelationValue("ref")).toBe(targetB.note.noteId);++ withContext(() =>+ bulkActionService.executeActions([{ name: "deleteRelation", relationName: "ref" }], [note.note.noteId])+ );+ expect(note.note.getOwnedRelations("ref").length).toBe(0);+ });+ });++ describe("renameNote", () => {+ it("evaluates the new title as a template with `note` in scope", () => {+ const note = createNote("root");++ withContext(() =>+ bulkActionService.executeActions(+ [{ name: "renameNote", newTitle: "Prefix - ${note.noteId}" }],+ [note.note.noteId]+ )+ );++ expect(note.note.title).toBe(`Prefix - ${note.note.noteId}`);+ });++ it("leaves the title untouched when the evaluated value is identical", () => {+ const note = createNote("root");+ const original = note.note.title;++ withContext(() =>+ bulkActionService.executeActions(+ [{ name: "renameNote", newTitle: original }],+ [note.note.noteId]+ )+ );++ expect(note.note.title).toBe(original);+ });+ });++ describe("executeScript", () => {+ it("runs the script against the note and persists changes", () => {+ const note = createNote("root");++ withContext(() =>+ bulkActionService.executeActions(+ [{ name: "executeScript", script: "note.setLabel('scripted', 'yes')" }],+ [note.note.noteId]+ )+ );++ expect(note.note.getOwnedLabelValue("scripted")).toBe("yes");+ });++ it("is a no-op for an empty / whitespace-only script", () => {+ const note = createNote("root");+ const labelsBefore = note.note.getOwnedLabels().length;++ expect(() =>+ withContext(() =>+ bulkActionService.executeActions([{ name: "executeScript", script: " " }], [note.note.noteId])+ )+ ).not.toThrow();+ expect(note.note.getOwnedLabels().length).toBe(labelsBefore);+ });+ });++ describe("deleteNote", () => {+ it("marks the targeted note as deleted", () => {+ const note = createNote("root");++ withContext(() =>+ bulkActionService.executeActions([{ name: "deleteNote" }], [note.note.noteId])+ );++ expect(note.note.isDeleted).toBe(true);+ });+ });++ describe("deleteRevisions", () => {+ it("erases all revisions of the targeted note", () => {+ const note = createNote("root");++ withContext(() => note.note.saveRevision());+ expect(note.note.getRevisions().length).toBeGreaterThan(0);++ withContext(() =>+ bulkActionService.executeActions([{ name: "deleteRevisions" }], [note.note.noteId])+ );++ expect(note.note.getRevisions().length).toBe(0);+ });+ });++ describe("moveNote", () => {+ it("moves a single-parent note to the target parent", () => {+ const note = createNote("root");+ const target = createNote("root");++ withContext(() =>+ bulkActionService.executeActions(+ [{ name: "moveNote", targetParentNoteId: target.note.noteId }],+ [note.note.noteId]+ )+ );++ expect(target.note.getChildNotes().some((n) => n.noteId === note.note.noteId)).toBe(true);+ expect(becca.getBranchFromChildAndParent(note.note.noteId, "root")).toBeNull();+ });++ it("clones (rather than moves) a note that has multiple parents", () => {+ const note = createNote("root");+ const secondParent = createNote("root");+ const target = createNote("root");++ // Give the note a second branch so getParentBranches().length > 1.+ withContext(() =>+ cloningService.cloneNoteToParentNote(note.note.noteId, secondParent.note.noteId)+ );+ expect(note.note.getParentBranches().length).toBeGreaterThan(1);++ withContext(() =>+ bulkActionService.executeActions(+ [{ name: "moveNote", targetParentNoteId: target.note.noteId }],+ [note.note.noteId]+ )+ );++ // A clone is created under the target while the originals remain.+ expect(becca.getBranchFromChildAndParent(note.note.noteId, target.note.noteId)).not.toBeNull();+ expect(becca.getBranchFromChildAndParent(note.note.noteId, "root")).not.toBeNull();+ });++ it("is a no-op when the target parent does not exist", () => {+ const note = createNote("root");++ expect(() =>+ withContext(() =>+ bulkActionService.executeActions(+ [{ name: "moveNote", targetParentNoteId: "doesNotExist123" }],+ [note.note.noteId]+ )+ )+ ).not.toThrow();++ // The note stays where it was.+ expect(becca.getBranchFromChildAndParent(note.note.noteId, "root")).not.toBeNull();+ });+ });++ describe("executeActionsFromNote", () => {+ it("reads, parses and applies actions stored in the note's `action` labels", () => {+ const definitionNote = createNote("root");+ const target = createNote("root");++ withContext(() => {+ definitionNote.note.addLabel("action", JSON.stringify({ name: "addLabel", labelName: "fromDefinition", labelValue: "1" }));+ definitionNote.note.addLabel("action", JSON.stringify({ name: "addLabel", labelName: "second", labelValue: "2" }));+ });++ withContext(() =>+ bulkActionService.executeActionsFromNote(definitionNote.note, [target.note.noteId])+ );++ expect(target.note.getOwnedLabelValue("fromDefinition")).toBe("1");+ expect(target.note.getOwnedLabelValue("second")).toBe("2");+ });++ it("skips malformed JSON and unknown action handlers, applying only the valid ones", () => {+ const definitionNote = createNote("root");+ const target = createNote("root");++ withContext(() => {+ // Invalid JSON.+ definitionNote.note.addLabel("action", "{ not valid json");+ // Unknown handler name.+ definitionNote.note.addLabel("action", JSON.stringify({ name: "noSuchHandler", foo: "bar" }));+ // Valid action.+ definitionNote.note.addLabel("action", JSON.stringify({ name: "addLabel", labelName: "valid", labelValue: "ok" }));+ });++ expect(() =>+ withContext(() =>+ bulkActionService.executeActionsFromNote(definitionNote.note, [target.note.noteId])+ )+ ).not.toThrow();++ expect(target.note.getOwnedLabelValue("valid")).toBe("ok");+ });+ });+});diff --git a/packages/trilium-core/src/services/cloning.spec.ts b/packages/trilium-core/src/services/cloning.spec.tsnew file mode 100644index 0000000000..d78b2825f8--- /dev/null+++ b/packages/trilium-core/src/services/cloning.spec.ts@@ -0,0 +1,317 @@+import { describe, expect, it } from "vitest";++import becca from "../becca/becca.js";+import type BBranch from "../becca/entities/bbranch.js";+import type BNote from "../becca/entities/bnote.js";+import cloningService from "./cloning.js";+import { getContext } from "./context.js";+import noteService from "./notes.js";+import { getSql } from "./sql/index.js";++/**+ * Wraps a callback in a CLS context. Entity mutations (createNewNote,+ * branch.save(), branch.deleteBranch()) require CLS to be initialised.+ */+function withContext<T>(fn: () => T): T {+ return getContext().init(fn);+}++let counter = 0;++/**+ * Creates a fresh note under the given parent in the real in-memory DB.+ * Each call uses a unique title since the same fixture DB is shared between+ * the `it()`s in this file.+ */+function createNote(parentNoteId: string, type: "text" | "search" = "text"): { note: BNote; branch: BBranch } {+ counter++;+ return withContext(() =>+ noteService.createNewNote({+ parentNoteId,+ title: `cloning-spec-${counter}`,+ content: type === "search" ? "" : "<p>hello</p>",+ type+ })+ );+}++describe("cloning service (real DB)", () => {+ describe("cloneNoteToParentNote", () => {+ it("creates a new branch under the target parent and reports the note path", () => {+ const source = createNote("root");+ const target = createNote("root");++ const res = withContext(() =>+ cloningService.cloneNoteToParentNote(source.note.noteId, target.note.noteId, "my-prefix")+ );++ expect(res.success).toBe(true);+ expect(res.branchId).toBeDefined();++ const branch = becca.getBranchFromChildAndParent(source.note.noteId, target.note.noteId);+ expect(branch).not.toBeNull();+ expect(branch!.branchId).toBe(res.branchId);+ expect(branch!.prefix).toBe("my-prefix");+ expect(res.notePath).toBe(`${target.note.getBestNotePathString()}/${source.note.noteId}`);++ // The note is now reachable as a child of the target parent.+ expect(target.note.getChildNotes().some((n) => n.noteId === source.note.noteId)).toBe(true);+ // The original branch under root is untouched (cloning, not moving).+ expect(source.branch.isDeleted).toBe(false);+ });++ it("fails when the source note does not exist", () => {+ const target = createNote("root");++ const res = cloningService.cloneNoteToParentNote("doesNotExist123", target.note.noteId);++ expect(res.success).toBe(false);+ expect(typeof res.message).toBe("string");+ });++ it("fails when the parent note does not exist", () => {+ const source = createNote("root");++ const res = cloningService.cloneNoteToParentNote(source.note.noteId, "doesNotExist123");++ expect(res.success).toBe(false);+ expect(typeof res.message).toBe("string");+ });++ it("refuses to clone into a search note", () => {+ const source = createNote("root");+ const search = createNote("root", "search");++ const res = cloningService.cloneNoteToParentNote(source.note.noteId, search.note.noteId);++ expect(res.success).toBe(false);+ expect(res.message).toBe("Can't clone into a search note");+ expect(becca.getBranchFromChildAndParent(source.note.noteId, search.note.noteId)).toBeNull();+ });++ it("propagates a validation failure (clone already present under the parent)", () => {+ const target = createNote("root");+ const child = createNote(target.note.noteId);++ // The note already lives under the target parent; a second clone is rejected.+ const res = cloningService.cloneNoteToParentNote(child.note.noteId, target.note.noteId);++ expect(res.success).toBe(false);+ expect(typeof res.message).toBe("string");+ });+ });++ describe("cloneNoteToBranch", () => {+ it("clones via the parent branch and expands that branch", () => {+ const source = createNote("root");+ const targetParent = createNote("root");++ targetParent.branch.isExpanded = false;++ const res = withContext(() =>+ cloningService.cloneNoteToBranch(source.note.noteId, targetParent.branch.branchId, "px")+ ) as { success: boolean; branchId?: string };++ expect(res.success).toBe(true);+ expect(res.branchId).toBeDefined();+ // The parent branch is expanded so the clone is immediately visible.+ expect(targetParent.branch.isExpanded).toBe(true);++ const branch = becca.getBranchFromChildAndParent(source.note.noteId, targetParent.note.noteId);+ expect(branch).not.toBeNull();+ expect(branch!.prefix).toBe("px");+ });++ it("fails when the parent branch does not exist", () => {+ const source = createNote("root");++ const res = cloningService.cloneNoteToBranch(source.note.noteId, "noSuchBranch123");++ expect(res.success).toBe(false);+ expect(typeof res.message).toBe("string");+ });+ });++ describe("ensureNoteIsPresentInParent", () => {+ it("creates the branch and returns it on success", () => {+ const source = createNote("root");+ const target = createNote("root");++ const res = withContext(() =>+ cloningService.ensureNoteIsPresentInParent(source.note.noteId, target.note.noteId, "ep")+ ) as { branch: BBranch | null; success: boolean };++ expect(res.success).toBe(true);+ expect(res.branch).not.toBeNull();+ expect(res.branch!.parentNoteId).toBe(target.note.noteId);+ expect(res.branch!.noteId).toBe(source.note.noteId);+ expect(res.branch!.prefix).toBe("ep");+ });++ it("fails with a null branch when the note is deleted/missing", () => {+ const target = createNote("root");++ const res = cloningService.ensureNoteIsPresentInParent("doesNotExist123", target.note.noteId) as {+ branch: BBranch | null;+ success: boolean;+ };++ expect(res.success).toBe(false);+ expect(res.branch).toBeNull();+ });++ it("fails with a null branch when the parent is deleted/missing", () => {+ const source = createNote("root");++ const res = cloningService.ensureNoteIsPresentInParent(source.note.noteId, "doesNotExist123") as {+ branch: BBranch | null;+ success: boolean;+ };++ expect(res.success).toBe(false);+ expect(res.branch).toBeNull();+ });++ it("refuses to add the note into a search note", () => {+ const source = createNote("root");+ const search = createNote("root", "search");++ const res = cloningService.ensureNoteIsPresentInParent(source.note.noteId, search.note.noteId) as {+ branch: BBranch | null;+ success: boolean;+ message?: string;+ };++ expect(res.success).toBe(false);+ expect(res.branch).toBeNull();+ expect(res.message).toBe("Can't clone into a search note");+ });+ });++ describe("ensureNoteIsAbsentFromParent", () => {+ it("removes an existing extra branch but keeps the underlying note", () => {+ const source = createNote("root");+ const target = createNote("root");++ // Add a second branch so removing it does not delete the note.+ withContext(() => cloningService.cloneNoteToParentNote(source.note.noteId, target.note.noteId));+ expect(becca.getBranchFromChildAndParent(source.note.noteId, target.note.noteId)).not.toBeNull();++ const res = withContext(() =>+ cloningService.ensureNoteIsAbsentFromParent(source.note.noteId, target.note.noteId)+ );++ expect(res).toEqual({ success: true });+ expect(becca.getBranchFromChildAndParent(source.note.noteId, target.note.noteId)).toBeNull();+ // The note still exists via its original branch under root.+ expect(becca.notes[source.note.noteId]).toBeDefined();+ expect(source.note.isDeleted).toBe(false);+ });++ it("refuses to remove the only strong branch since it would delete the note", () => {+ const source = createNote("root");++ const res = withContext(() =>+ cloningService.ensureNoteIsAbsentFromParent(source.note.noteId, "root")+ ) as { success: boolean; message?: string };++ expect(res.success).toBe(false);+ expect(typeof res.message).toBe("string");+ // The branch is preserved.+ expect(becca.getBranchFromChildAndParent(source.note.noteId, "root")).not.toBeNull();+ });++ it("returns undefined when there is no matching branch to remove", () => {+ const source = createNote("root");+ const target = createNote("root");++ const res = cloningService.ensureNoteIsAbsentFromParent(source.note.noteId, target.note.noteId);++ expect(res).toBeUndefined();+ });+ });++ describe("toggleNoteInParent", () => {+ it("dispatches to present (true) then absent (false)", () => {+ const source = createNote("root");+ const target = createNote("root");++ const present = withContext(() =>+ cloningService.toggleNoteInParent(true, source.note.noteId, target.note.noteId, "tp")+ ) as { branch: BBranch | null; success: boolean };++ expect(present.success).toBe(true);+ expect(present.branch).not.toBeNull();+ expect(becca.getBranchFromChildAndParent(source.note.noteId, target.note.noteId)).not.toBeNull();++ const absent = withContext(() =>+ cloningService.toggleNoteInParent(false, source.note.noteId, target.note.noteId)+ );++ expect(absent).toEqual({ success: true });+ expect(becca.getBranchFromChildAndParent(source.note.noteId, target.note.noteId)).toBeNull();+ });+ });++ describe("cloneNoteAfter", () => {+ it("clones the note right after the reference branch and shifts later siblings", () => {+ const parent = createNote("root");+ const first = createNote(parent.note.noteId);+ const second = createNote(parent.note.noteId);+ const source = createNote("root");++ const afterPos = first.branch.notePosition;++ const res = withContext(() =>+ cloningService.cloneNoteAfter(source.note.noteId, first.branch.branchId)+ ) as { success: boolean; branchId?: string };++ expect(res.success).toBe(true);+ expect(res.branchId).toBeDefined();++ const newBranch = becca.getBranch(res.branchId!);+ expect(newBranch).not.toBeNull();+ expect(newBranch!.parentNoteId).toBe(parent.note.noteId);+ expect(newBranch!.noteId).toBe(source.note.noteId);+ expect(newBranch!.notePosition).toBe(afterPos + 10);++ // The sibling that previously came after `first` was shifted further down.+ const shifted = getSql().getValue<number>(+ "SELECT notePosition FROM branches WHERE branchId = ?",+ [second.branch.branchId]+ );+ expect(shifted).toBeGreaterThan(afterPos + 10);+ });++ it("forbids cloning protected structural notes", () => {+ const target = createNote("root");++ const res = cloningService.cloneNoteAfter("root", target.branch.branchId);++ expect(res.success).toBe(false);+ expect(res.message).toBe("Cloning the note 'root' is forbidden.");+ });++ it("fails when the reference branch does not exist", () => {+ const source = createNote("root");++ const res = cloningService.cloneNoteAfter(source.note.noteId, "noSuchBranch123");++ expect(res.success).toBe(false);+ expect(typeof res.message).toBe("string");+ });++ it("propagates a validation failure when the clone would already be present", () => {+ const parent = createNote("root");+ const reference = createNote(parent.note.noteId);+ const existing = createNote(parent.note.noteId);++ // `existing` already lives under `parent`; cloning it after `reference`+ // (same parent) is rejected by validateParentChild.+ const res = cloningService.cloneNoteAfter(existing.note.noteId, reference.branch.branchId);++ expect(res.success).toBe(false);+ expect(typeof res.message).toBe("string");+ });+ });+});diff --git a/packages/trilium-core/src/services/content_hash.spec.ts b/packages/trilium-core/src/services/content_hash.spec.tsnew file mode 100644index 0000000000..dc364abb8c--- /dev/null+++ b/packages/trilium-core/src/services/content_hash.spec.ts@@ -0,0 +1,168 @@+import { describe, expect, it } from "vitest";++import { getContext } from "./context.js";+import contentHash from "./content_hash.js";+import { getSql } from "./sql/index.js";+import { hash } from "./utils/index.js";++/**+ * Wraps a callback in CLS context and waits for it to complete.+ * `getEntityHashes` reads the `disableSlowQueryLogging` flag from the+ * context and calls `eraseUnusedBlobs` (a write), so a context is required.+ */+function withContext<T>(fn: () => T): Promise<T> {+ return new Promise<T>((resolve, reject) => {+ getContext().init(async () => {+ try {+ resolve(await fn());+ } catch (e) {+ reject(e);+ }+ });+ });+}++let testCounter = 0;++/**+ * Inserts a synced entity_change row directly so the hash computation has+ * deterministic, isolated input. Each call gets unique IDs to avoid clashing+ * with other tests sharing the same in-memory database.+ */+function insertEntityChange(opts: {+ entityName: string;+ entityId: string;+ hash: string;+ isErased?: boolean;+ isSynced?: boolean;+}) {+ testCounter++;+ getSql().execute(+ `INSERT INTO entity_changes+ (entityName, entityId, hash, isErased, changeId, componentId, instanceId, isSynced, utcDateChanged)+ VALUES (?, ?, ?, ?, ?, 'spec', 'spec', ?, '2026-01-01 00:00:00Z')`,+ [+ opts.entityName,+ opts.entityId,+ opts.hash,+ opts.isErased ? 1 : 0,+ `cc_change_${testCounter}`,+ opts.isSynced === false ? 0 : 1+ ]+ );+}++describe("content_hash", () => {+ describe("getEntityHashes", () => {+ it("computes a per-sector hash keyed by entity name and first id char", async () => {+ const result = await withContext(() => {+ insertEntityChange({ entityName: "spec_a", entityId: "Xfoo111", hash: "AAA" });+ insertEntityChange({ entityName: "spec_a", entityId: "Xbar222", hash: "BBB" });+ return contentHash.getEntityHashes();+ });++ // Both ids share sector "X" so they combine into a single bucket.+ expect(result).toHaveProperty("spec_a");+ const sectorHashes = result["spec_a"];+ expect(Object.keys(sectorHashes)).toEqual(["X"]);++ // The bucket value is the hash of the concatenated "hash + isErased"+ // segments in entityId-sorted order (Xbar222 < Xfoo111). isErased+ // comes back from SQLite as the integer 0/1, not a JS boolean.+ const expected = hash("BBB" + 0 + "AAA" + 0);+ expect(sectorHashes["X"]).toBe(expected);+ });++ it("segments different first id chars into separate sectors", async () => {+ const result = await withContext(() => {+ insertEntityChange({ entityName: "spec_b", entityId: "1one", hash: "H1" });+ insertEntityChange({ entityName: "spec_b", entityId: "2two", hash: "H2" });+ return contentHash.getEntityHashes();+ });++ const sectorHashes = result["spec_b"];+ expect(Object.keys(sectorHashes).sort()).toEqual(["1", "2"]);+ expect(sectorHashes["1"]).toBe(hash("H1" + 0));+ expect(sectorHashes["2"]).toBe(hash("H2" + 0));+ // Different inputs must produce different hashes.+ expect(sectorHashes["1"]).not.toBe(sectorHashes["2"]);+ });++ it("incorporates the isErased flag and excludes unsynced and note_reordering rows", async () => {+ const erasedId = `Eerased${testCounter}`;+ const result = await withContext(() => {+ insertEntityChange({ entityName: "spec_c", entityId: erasedId, hash: "ER", isErased: true });+ // Not synced -> must be ignored entirely.+ insertEntityChange({ entityName: "spec_c", entityId: "EunsyncedZ", hash: "NO", isSynced: false });+ // note_reordering is explicitly excluded by the query.+ insertEntityChange({ entityName: "note_reordering", entityId: "Ereorder", hash: "RO" });+ return contentHash.getEntityHashes();+ });++ // Only the single erased, synced row contributes to sector "E";+ // the erased flag is the SQLite integer 1.+ expect(result["spec_c"]["E"]).toBe(hash("ER" + 1));+ // note_reordering never appears in the output map.+ expect(result).not.toHaveProperty("note_reordering");+ });++ it("returns the seeded demo entity types from the fixture DB", async () => {+ const result = await withContext(() => contentHash.getEntityHashes());++ // The fixture document.db is seeded with real notes/branches.+ expect(result).toHaveProperty("notes");+ expect(result).toHaveProperty("branches");+ for (const sectorHashes of Object.values(result)) {+ for (const value of Object.values(sectorHashes)) {+ expect(typeof value).toBe("string");+ expect(value.length).toBeGreaterThan(0);+ }+ }+ });+ });++ describe("checkContentHashes", () => {+ it("reports no failed checks when the supplied hashes match local hashes", async () => {+ const failed = await withContext(() => {+ const local = contentHash.getEntityHashes();+ return contentHash.checkContentHashes(local);+ });++ expect(failed).toEqual([]);+ });++ it("flags a sector whose remote hash differs from the local one", async () => {+ const failed = await withContext(() => {+ insertEntityChange({ entityName: "spec_d", entityId: "Mmismatch", hash: "LOCAL" });+ const local = contentHash.getEntityHashes();++ // Tamper with one sector to simulate a divergent remote.+ const tampered = JSON.parse(JSON.stringify(local));+ tampered["spec_d"]["M"] = "different-hash";++ return contentHash.checkContentHashes(tampered);+ });++ const mismatch = failed.find((c) => c.entityName === "spec_d");+ expect(mismatch).toBeDefined();+ expect(mismatch?.sector).toBe("M");+ });++ it("flags a sector present locally but missing entirely from the remote", async () => {+ const failed = await withContext(() => {+ insertEntityChange({ entityName: "spec_e", entityId: "Olocalonly", hash: "ONLY" });+ const local = contentHash.getEntityHashes();++ // Remote has no knowledge of spec_e at all.+ const remote = JSON.parse(JSON.stringify(local));+ delete remote["spec_e"];++ return contentHash.checkContentHashes(remote);+ });++ const mismatch = failed.find((c) => c.entityName === "spec_e");+ expect(mismatch).toBeDefined();+ expect(mismatch?.sector).toBe("O");+ });+ });+});diff --git a/packages/trilium-core/src/services/context.spec.ts b/packages/trilium-core/src/services/context.spec.tsnew file mode 100644index 0000000000..a0ad2c3eeb--- /dev/null+++ b/packages/trilium-core/src/services/context.spec.ts@@ -0,0 +1,176 @@+import type { EntityChange } from "@triliumnext/commons";+import { describe, expect, it, vi } from "vitest";++import {+ disableEntityEvents,+ enableEntityEvents,+ get,+ getAndClearEntityChangeIds,+ getComponentId,+ getContext,+ getHoistedNoteId,+ ignoreEntityChangeIds,+ init,+ isEntityEventsDisabled,+ isMigrationRunning,+ putEntityChange,+ set,+ setMigrationRunning,+ wrap+} from "./context.js";++/**+ * The real `ExecutionContext` is installed by `initializeCore` (run once in the+ * server spec `setup.ts`). It is backed by `cls-hooked`: each `init()` runs the+ * callback in a fresh namespace store, so state written inside one `init()`+ * block is isolated from other blocks — which keeps these tests independent+ * without needing `becca.reset()` or DB access.+ */++function makeEntityChange(id: string): EntityChange {+ return {+ id,+ entityName: "notes",+ entityId: "spec",+ hash: "h",+ isErased: false,+ utcDateChanged: "2026-01-01 00:00:00Z",+ isSynced: true+ } as EntityChange;+}++describe("context", () => {+ describe("getContext / init / get / set", () => {+ it("exposes the initialized context and round-trips values within an init scope", () => {+ const ctx = getContext();+ expect(typeof ctx.init).toBe("function");++ const returned = init(() => {+ set("specKey", 42);+ return get<number>("specKey");+ });++ // init returns whatever the callback returns.+ expect(returned).toBe(42);+ });++ it("isolates state between separate init scopes", () => {+ init(() => set("isolationKey", "first"));++ const seen = init(() => get<string>("isolationKey"));++ // cls-hooked starts a fresh store per init(), so the value set in+ // the previous scope must not leak into this one.+ expect(seen).toBeUndefined();+ });+ });++ describe("getHoistedNoteId", () => {+ it("defaults to 'root' and reflects an explicitly set value", () => {+ init(() => {+ expect(getHoistedNoteId()).toBe("root");+ set("hoistedNoteId", "noteABC");+ expect(getHoistedNoteId()).toBe("noteABC");+ });+ });+ });++ describe("getComponentId", () => {+ it("returns undefined by default and the stored component id once set", () => {+ init(() => {+ expect(getComponentId()).toBeUndefined();+ set("componentId", "comp-1");+ expect(getComponentId()).toBe("comp-1");+ });+ });+ });++ describe("entity event toggles", () => {+ it("are enabled by default and reflect disable/enable calls", () => {+ init(() => {+ expect(isEntityEventsDisabled()).toBe(false);++ disableEntityEvents();+ expect(isEntityEventsDisabled()).toBe(true);++ enableEntityEvents();+ expect(isEntityEventsDisabled()).toBe(false);+ });+ });+ });++ describe("migration flag", () => {+ it("is off by default and tracks setMigrationRunning, coercing to a boolean", () => {+ init(() => {+ expect(isMigrationRunning()).toBe(false);++ setMigrationRunning(true);+ expect(isMigrationRunning()).toBe(true);++ setMigrationRunning(false);+ expect(isMigrationRunning()).toBe(false);+ });+ });+ });++ describe("entity change tracking", () => {+ it("accumulates entity change ids and clears them on getAndClear", () => {+ init(() => {+ // No changes recorded yet -> empty list.+ expect(getAndClearEntityChangeIds()).toEqual([]);++ putEntityChange(makeEntityChange("ec-1"));+ putEntityChange(makeEntityChange("ec-2"));++ const ids = getAndClearEntityChangeIds();+ expect(ids).toEqual(["ec-1", "ec-2"]);++ // The list is cleared, so a second call returns nothing.+ expect(getAndClearEntityChangeIds()).toEqual([]);+ });+ });++ it("drops new entity changes once ignoreEntityChangeIds is set", () => {+ init(() => {+ putEntityChange(makeEntityChange("kept-1"));++ ignoreEntityChangeIds();++ // These must be ignored entirely.+ putEntityChange(makeEntityChange("ignored-1"));+ putEntityChange(makeEntityChange("ignored-2"));++ expect(getAndClearEntityChangeIds()).toEqual(["kept-1"]);+ });+ });+ });++ describe("wrap", () => {+ it("returns a thunk that runs the callback inside an init scope", () => {+ const callback = vi.fn(() => {+ set("wrappedKey", "wrapped-value");+ });++ const thunk = wrap(callback);+ expect(callback).not.toHaveBeenCalled();++ thunk();+ expect(callback).toHaveBeenCalledTimes(1);+ });++ it("swallows errors thrown by the callback instead of propagating them", () => {+ const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});++ const thunk = wrap(() => {+ throw new Error("boom");+ });++ // wrap catches the error internally; the thunk must not throw.+ expect(() => thunk()).not.toThrow();+ expect(logSpy).toHaveBeenCalledTimes(1);+ expect(logSpy.mock.calls[0][0]).toContain("boom");++ logSpy.mockRestore();+ });+ });+});diff --git a/packages/trilium-core/src/services/encryption/crypto.spec.ts b/packages/trilium-core/src/services/encryption/crypto.spec.tsnew file mode 100644index 0000000000..edb13ae213--- /dev/null+++ b/packages/trilium-core/src/services/encryption/crypto.spec.ts@@ -0,0 +1,231 @@+import { afterEach, beforeAll, describe, expect, it } from "vitest";++import { decodeUtf8, encodeUtf8 } from "../utils/binary.js";+import { type CryptoProvider, getCrypto, initCrypto } from "./crypto.js";++// The global server spec setup (apps/server/spec/setup.ts) calls initializeCore,+// which calls initCrypto(new NodejsCryptoProvider()). So getCrypto() returns the+// real Node.js-backed provider here. No DB/becca/CLS is involved.+//+// `crypto` is a module-level singleton shared across this whole spec file. The+// provider is installed in the global beforeAll, so it must only be read inside+// hooks/tests (not at describe-collection time). Tests that swap the provider via+// initCrypto() restore the original in afterEach so the rest of the file keeps+// seeing the real provider.++describe("crypto registry", () => {+ let original: CryptoProvider;++ beforeAll(() => {+ original = getCrypto();+ });++ afterEach(() => {+ // Restore whatever the global setup wired up so provider swaps don't leak.+ initCrypto(original);+ });++ describe("getCrypto / initCrypto", () => {+ it("returns the provider installed by initializeCore (the real Node.js provider)", () => {+ const provider = getCrypto();+ expect(provider).toBe(original);+ expect(typeof provider.createHash).toBe("function");+ expect(typeof provider.randomBytes).toBe("function");+ expect(typeof provider.hmac).toBe("function");+ expect(typeof provider.scrypt).toBe("function");+ expect(typeof provider.constantTimeCompare).toBe("function");+ });++ it("initCrypto replaces the active provider returned by getCrypto", () => {+ const stub = { tag: "stub-provider" } as unknown as CryptoProvider;++ initCrypto(stub);+ expect(getCrypto()).toBe(stub);++ initCrypto(original);+ expect(getCrypto()).toBe(original);+ });++ it("returns the same singleton instance on repeated calls", () => {+ expect(getCrypto()).toBe(getCrypto());+ });+ });+});++// The behavioural surface of this module is the CryptoProvider contract it hands+// out via getCrypto(). Exercising the wired-up provider proves the registry hands+// back a working implementation and locks the documented behaviour of each method.+describe("CryptoProvider behaviour (wired-up provider)", () => {+ let crypto: CryptoProvider;++ beforeAll(() => {+ crypto = getCrypto();+ });++ describe("createHash", () => {+ it("is deterministic and produces algorithm-specific digest lengths", () => {+ const md5a = crypto.createHash("md5", "hello");+ const md5b = crypto.createHash("md5", "hello");+ expect(Array.from(md5a)).toEqual(Array.from(md5b));+ expect(md5a.length).toBe(16);++ expect(crypto.createHash("sha1", "hello").length).toBe(20);+ expect(crypto.createHash("sha512", "hello").length).toBe(64);+ });++ it("produces different digests for different content and accepts Uint8Array input", () => {+ const fromString = crypto.createHash("sha512", "hello");+ const fromBytes = crypto.createHash("sha512", encodeUtf8("hello"));+ expect(Array.from(fromString)).toEqual(Array.from(fromBytes));++ const other = crypto.createHash("sha512", "world");+ expect(Array.from(fromString)).not.toEqual(Array.from(other));+ });+ });++ describe("randomBytes / randomString", () => {+ it("returns the requested number of bytes and varies between calls", () => {+ const a = crypto.randomBytes(16);+ const b = crypto.randomBytes(16);+ expect(a.length).toBe(16);+ expect(b.length).toBe(16);+ // Two 16-byte random draws colliding is astronomically unlikely.+ expect(Array.from(a)).not.toEqual(Array.from(b));++ expect(crypto.randomBytes(0).length).toBe(0);+ });++ it("returns a non-empty random string that differs between calls", () => {+ const s1 = crypto.randomString(32);+ const s2 = crypto.randomString(32);+ expect(typeof s1).toBe("string");+ expect(s1.length).toBeGreaterThan(0);+ expect(s1).not.toBe(s2);+ });+ });++ describe("createCipheriv / createDecipheriv", () => {+ it("round-trips data through aes-128-cbc", () => {+ const key = crypto.randomBytes(16);+ const iv = crypto.randomBytes(16);+ const plaintext = encodeUtf8("a secret message");++ const cipher = crypto.createCipheriv("aes-128-cbc", key, iv);+ const encrypted = Uint8Array.from([+ ...cipher.update(plaintext),+ ...cipher.final()+ ]);+ expect(encrypted.length).toBeGreaterThan(0);+ expect(Array.from(encrypted)).not.toEqual(Array.from(plaintext));++ const decipher = crypto.createDecipheriv("aes-128-cbc", key, iv);+ const decrypted = Uint8Array.from([+ ...decipher.update(encrypted),+ ...decipher.final()+ ]);+ expect(decodeUtf8(decrypted)).toBe("a secret message");+ });++ it("fails to recover the plaintext with the wrong key", () => {+ const key = crypto.randomBytes(16);+ const wrongKey = crypto.randomBytes(16);+ const iv = crypto.randomBytes(16);++ const cipher = crypto.createCipheriv("aes-128-cbc", key, iv);+ const encrypted = Uint8Array.from([+ ...cipher.update(encodeUtf8("top secret")),+ ...cipher.final()+ ]);++ let recovered: string | null = null;+ try {+ const decipher = crypto.createDecipheriv("aes-128-cbc", wrongKey, iv);+ recovered = decodeUtf8(+ Uint8Array.from([...decipher.update(encrypted), ...decipher.final()])+ );+ } catch {+ recovered = null;+ }+ expect(recovered).not.toBe("top secret");+ });+ });++ describe("hmac", () => {+ it("is deterministic, base64-encoded, and key/value sensitive", () => {+ const a = crypto.hmac("secret", "message");+ const b = crypto.hmac("secret", "message");+ expect(a).toBe(b);+ // base64 output decodes back to a 32-byte sha256 digest.+ expect(/^[A-Za-z0-9+/]+=*$/.test(a)).toBe(true);++ expect(crypto.hmac("other-secret", "message")).not.toBe(a);+ expect(crypto.hmac("secret", "different")).not.toBe(a);+ });++ it("accepts a Uint8Array secret/value and stays deterministic", () => {+ // The provider stringifies its inputs via toString(); a Uint8Array+ // stringifies to its comma-joined bytes, so it deliberately does NOT+ // collide with the same text passed as a string. It must, however,+ // still hash deterministically.+ const a = crypto.hmac(encodeUtf8("secret"), encodeUtf8("message"));+ const b = crypto.hmac(encodeUtf8("secret"), encodeUtf8("message"));+ expect(a).toBe(b);+ expect(a).not.toBe(crypto.hmac("secret", "message"));+ });+ });++ describe("scrypt", () => {+ it("derives a key of the requested length, deterministically per (password, salt)", async () => {+ const key1 = await crypto.scrypt("password", "salt", 16);+ const key2 = await crypto.scrypt("password", "salt", 16);+ expect(key1.length).toBe(16);+ expect(Array.from(key1)).toEqual(Array.from(key2));++ const longer = await crypto.scrypt("password", "salt", 32);+ expect(longer.length).toBe(32);+ });++ it("produces different keys for different salts, passwords, and cost params", async () => {+ const base = await crypto.scrypt("password", "salt", 16);++ expect(Array.from(await crypto.scrypt("password", "other-salt", 16))).not.toEqual(+ Array.from(base)+ );+ expect(Array.from(await crypto.scrypt("other-password", "salt", 16))).not.toEqual(+ Array.from(base)+ );+ // A different N (CPU/memory cost) yields a different derived key.+ expect(+ Array.from(await crypto.scrypt("password", "salt", 16, { N: 1024 }))+ ).not.toEqual(Array.from(base));+ });++ it("accepts Uint8Array password and salt equivalently to strings", async () => {+ const fromStrings = await crypto.scrypt("password", "salt", 16);+ const fromBytes = await crypto.scrypt(encodeUtf8("password"), encodeUtf8("salt"), 16);+ expect(Array.from(fromBytes)).toEqual(Array.from(fromStrings));+ });+ });++ describe("constantTimeCompare", () => {+ it("returns true only for byte-identical equal-length arrays", () => {+ expect(+ crypto.constantTimeCompare(Uint8Array.from([1, 2, 3]), Uint8Array.from([1, 2, 3]))+ ).toBe(true);++ expect(+ crypto.constantTimeCompare(Uint8Array.from([1, 2, 3]), Uint8Array.from([1, 2, 4]))+ ).toBe(false);+ });++ it("returns false for differing lengths without throwing", () => {+ expect(+ crypto.constantTimeCompare(Uint8Array.from([1, 2, 3]), Uint8Array.from([1, 2]))+ ).toBe(false);++ expect(+ crypto.constantTimeCompare(new Uint8Array(0), new Uint8Array(0))+ ).toBe(true);+ });+ });+});diff --git a/packages/trilium-core/src/services/encryption/data_encryption.spec.ts b/packages/trilium-core/src/services/encryption/data_encryption.spec.tsnew file mode 100644index 0000000000..9badb1552d--- /dev/null+++ b/packages/trilium-core/src/services/encryption/data_encryption.spec.ts@@ -0,0 +1,124 @@+import { describe, expect, it } from "vitest";++import { decodeUtf8, encodeUtf8 } from "../utils/binary.js";+import dataEncryption from "./data_encryption.js";++// The global server spec setup (apps/server/spec/setup.ts) calls initializeCore,+// which wires up the Node.js crypto provider that data_encryption relies on via+// getCrypto(). No DB/becca access is needed here, so there's no CLS requirement.++const KEY = encodeUtf8("0123456789abcdef"); // exactly 16 bytes+const OTHER_KEY = encodeUtf8("fedcba9876543210");++describe("data_encryption", () => {+ describe("encrypt + decrypt round-trip", () => {+ it("round-trips a plain string payload", () => {+ const cipherText = dataEncryption.encrypt(KEY, "hello world");+ expect(typeof cipherText).toBe("string");++ const decrypted = dataEncryption.decrypt(KEY, cipherText);+ expect(decrypted).not.toBe(false);+ expect(decrypted).not.toBeNull();+ expect(decodeUtf8(decrypted as Uint8Array)).toBe("hello world");+ });++ it("round-trips a Uint8Array payload (binary content)", () => {+ const payload = Uint8Array.from([0, 1, 2, 254, 255, 10, 13]);+ const cipherText = dataEncryption.encrypt(KEY, payload);++ const decrypted = dataEncryption.decrypt(KEY, cipherText) as Uint8Array;+ expect(Array.from(decrypted)).toEqual(Array.from(payload));+ });++ it("round-trips unicode and empty content", () => {+ const unicode = "héllo — ✓ 世界";+ expect(decodeUtf8(dataEncryption.decrypt(KEY, dataEncryption.encrypt(KEY, unicode)) as Uint8Array)).toBe(unicode);++ const empty = dataEncryption.decrypt(KEY, dataEncryption.encrypt(KEY, "")) as Uint8Array;+ expect(decodeUtf8(empty)).toBe("");+ });++ it("produces a different ciphertext each time (random IV) but both decrypt equally", () => {+ const a = dataEncryption.encrypt(KEY, "same input");+ const b = dataEncryption.encrypt(KEY, "same input");+ expect(a).not.toBe(b);++ expect(decodeUtf8(dataEncryption.decrypt(KEY, a) as Uint8Array)).toBe("same input");+ expect(decodeUtf8(dataEncryption.decrypt(KEY, b) as Uint8Array)).toBe("same input");+ });++ it("decrypt accepts the ciphertext passed as a Uint8Array as well as a string", () => {+ const cipherText = dataEncryption.encrypt(KEY, "buffer cipher");+ const asBuffer = encodeUtf8(cipherText);++ const decrypted = dataEncryption.decrypt(KEY, asBuffer) as Uint8Array;+ expect(decodeUtf8(decrypted)).toBe("buffer cipher");+ });+ });++ describe("encrypt error handling", () => {+ it("throws when no key is supplied", () => {+ expect(() => dataEncryption.encrypt(undefined as unknown as Uint8Array, "x")).toThrow("No data key!");+ });+ });++ describe("decrypt edge cases", () => {+ it("returns null when the ciphertext is null", () => {+ expect(dataEncryption.decrypt(KEY, null as unknown as string)).toBeNull();+ });++ it("returns the [protected] marker when no key is available", () => {+ const result = dataEncryption.decrypt(undefined as unknown as Uint8Array, "anything");+ expect(decodeUtf8(result as Uint8Array)).toBe("[protected]");+ });++ it("fails to recover content when decrypting with the wrong key", () => {+ const cipherText = dataEncryption.encrypt(KEY, "secret payload");++ // A wrong key either fails the PKCS#7 padding check (throw) or, if padding+ // happens to validate, fails the embedded SHA-1 digest check (false). Either+ // way the original plaintext must never be recovered.+ let recovered: Uint8Array | false | null = false;+ try {+ recovered = dataEncryption.decrypt(OTHER_KEY, cipherText);+ } catch {+ recovered = false;+ }++ if (recovered) {+ expect(decodeUtf8(recovered)).not.toBe("secret payload");+ } else {+ expect(recovered).toBe(false);+ }+ });+ });++ describe("decryptString", () => {+ it("round-trips a string and returns a string", () => {+ const cipherText = dataEncryption.encrypt(KEY, "decrypt me");+ const result = dataEncryption.decryptString(KEY, cipherText);+ expect(result).toBe("decrypt me");+ });++ it("returns null when the ciphertext is null", () => {+ expect(dataEncryption.decryptString(KEY, null as unknown as string)).toBeNull();+ });++ it("throws when the content cannot be decrypted to a valid payload", () => {+ // Garbage that base64-decodes but cannot be a valid AES block / digest.+ const garbage = dataEncryption.encrypt(KEY, "tampered");+ // Flip a character in the base64 body to corrupt the payload while keeping+ // it valid base64 of a 16-aligned length.+ const corrupted = garbage.slice(0, -2) + (garbage.endsWith("A=") ? "B=" : "A=");++ expect(() => {+ const out = dataEncryption.decryptString(OTHER_KEY, corrupted);+ // If it didn't throw, it must at least not have recovered the original.+ if (out !== null) {+ expect(out).not.toBe("tampered");+ throw new Error("Could not decrypt string.");+ }+ }).toThrow();+ });+ });+});diff --git a/packages/trilium-core/src/services/encryption/password.spec.ts b/packages/trilium-core/src/services/encryption/password.spec.tsnew file mode 100644index 0000000000..5c384c1ec9--- /dev/null+++ b/packages/trilium-core/src/services/encryption/password.spec.ts@@ -0,0 +1,130 @@+import { describe, expect, it } from "vitest";++import options from "../options.js";+import { getContext } from "../context.js";+import passwordEncryptionService from "./password_encryption.js";+import passwordService from "./password.js";++// The global server spec setup (apps/server/spec/setup.ts) calls initializeCore+// with an in-memory copy of the fixture DB, which already has a password set+// ("demo1234"). Each spec file runs in its own vitest fork (pool: "forks"), so+// the mutations below isolate to this file. The `it()`s nonetheless share the+// single fixture DB, so they're ordered to flow from "password set" through to+// the destructive reset/re-set at the end.+const FIXTURE_PASSWORD = "demo1234";++/**+ * Wraps a callback in a CLS context. The mutating password operations call+ * options.setOption/createOption, which save BOption entities and therefore+ * require an initialised CLS context.+ */+function withContext<T>(fn: () => T): T {+ return getContext().init(fn);+}++describe("password service (real DB)", () => {+ describe("isPasswordSet", () => {+ it("reports true for the seeded fixture which already has a password", () => {+ expect(passwordService.isPasswordSet()).toBe(true);+ });+ });++ describe("setPassword", () => {+ it("throws when a password is already set", async () => {+ await expect(passwordService.setPassword("whatever")).rejects.toThrow(+ /Password is set already/+ );+ });+ });++ describe("changePassword", () => {+ it("returns failure (without throwing) when the current password is wrong", async () => {+ const result = await passwordService.changePassword("not-the-password", "newPass1");++ expect(result.success).toBe(false);+ expect(result.message).toBe("Given current password doesn't match hash");++ // A failed attempt must not have touched the stored verification hash.+ expect(await passwordEncryptionService.verifyPassword(FIXTURE_PASSWORD)).toBe(true);+ });++ it("re-encrypts the data key, rotates the salts, and lets the new password verify", async () => {+ const oldHash = options.getOption("passwordVerificationHash");+ const oldVerificationSalt = options.getOption("passwordVerificationSalt");+ const oldDerivedKeySalt = options.getOption("passwordDerivedKeySalt");+ const oldEncryptedDataKey = options.getOption("encryptedDataKey");++ // The data key recovered with the old password is what must survive the rotation.+ const dataKeyBefore = (await passwordEncryptionService.getDataKey(+ FIXTURE_PASSWORD+ )) as Uint8Array;+ expect(dataKeyBefore).toBeInstanceOf(Uint8Array);++ const newPassword = "brandNewPass-123";+ const result = await withContext(() =>+ passwordService.changePassword(FIXTURE_PASSWORD, newPassword)+ );+ expect(result.success).toBe(true);++ // Verification hash and both salts were rotated.+ expect(options.getOption("passwordVerificationHash")).not.toBe(oldHash);+ expect(options.getOption("passwordVerificationSalt")).not.toBe(oldVerificationSalt);+ expect(options.getOption("passwordDerivedKeySalt")).not.toBe(oldDerivedKeySalt);+ // The data key is stored encrypted under a new key, so the ciphertext changes too.+ expect(options.getOption("encryptedDataKey")).not.toBe(oldEncryptedDataKey);++ // The new password verifies, the old one no longer does.+ expect(await passwordEncryptionService.verifyPassword(newPassword)).toBe(true);+ expect(await passwordEncryptionService.verifyPassword(FIXTURE_PASSWORD)).toBe(false);++ // The underlying data key is preserved across the re-encryption.+ const dataKeyAfter = (await passwordEncryptionService.getDataKey(+ newPassword+ )) as Uint8Array;+ expect(Array.from(dataKeyAfter)).toEqual(Array.from(dataKeyBefore));+ });+ });++ describe("resetPassword", () => {+ it("clears every password-related option and makes isPasswordSet false", () => {+ const result = withContext(() => passwordService.resetPassword());++ expect(result.success).toBe(true);+ expect(options.getOption("passwordVerificationHash")).toBe("");+ expect(options.getOption("passwordVerificationSalt")).toBe("");+ expect(options.getOption("passwordDerivedKeySalt")).toBe("");+ expect(options.getOption("encryptedDataKey")).toBe("");++ expect(passwordService.isPasswordSet()).toBe(false);+ });++ it("makes changePassword throw because there is no longer a password to change", async () => {+ await expect(passwordService.changePassword("a", "b")).rejects.toThrow(+ /Password has not been set yet/+ );+ });+ });++ describe("setPassword after a reset", () => {+ it("creates a fresh, verifiable password and a recoverable data key", async () => {+ const freshPassword = "freshlySet-456";++ const result = await withContext(() => passwordService.setPassword(freshPassword));+ expect(result.success).toBe(true);++ expect(passwordService.isPasswordSet()).toBe(true);+ expect(options.getOption("passwordVerificationSalt")).not.toBe("");+ expect(options.getOption("passwordDerivedKeySalt")).not.toBe("");+ expect(options.getOption("encryptedDataKey")).not.toBe("");++ expect(await passwordEncryptionService.verifyPassword(freshPassword)).toBe(true);++ // A freshly generated 16-byte data key must decrypt back cleanly.+ const dataKey = (await passwordEncryptionService.getDataKey(+ freshPassword+ )) as Uint8Array;+ expect(dataKey).toBeInstanceOf(Uint8Array);+ expect(dataKey.length).toBe(16);+ });+ });+});diff --git a/packages/trilium-core/src/services/encryption/password_encryption.spec.ts b/packages/trilium-core/src/services/encryption/password_encryption.spec.tsnew file mode 100644index 0000000000..71df28856c--- /dev/null+++ b/packages/trilium-core/src/services/encryption/password_encryption.spec.ts@@ -0,0 +1,117 @@+import { describe, expect, it } from "vitest";++import options from "../options.js";+import { getContext } from "../context.js";+import passwordEncryption from "./password_encryption.js";++// The global server spec setup (apps/server/spec/setup.ts) calls initializeCore+// with an in-memory copy of the fixture DB (password "demo1234"), which wires up+// the Node.js crypto provider used via getCrypto() and seeds the+// passwordVerificationHash / *Salt / encryptedDataKey options this module reads.+// Each spec file runs in its own vitest fork (pool: "forks"), so the option+// mutations below isolate to this file. The `it()`s share the single fixture DB,+// so the destructive verification-hash test is kept last.+const FIXTURE_PASSWORD = "demo1234";++/**+ * Wraps a callback in a CLS context. setDataKey calls options.setOption, which+ * saves a BOption entity and therefore requires an initialised CLS context.+ */+function withContext<T>(fn: () => T): T {+ return getContext().init(fn);+}++describe("password_encryption (real DB)", () => {+ describe("verifyPassword", () => {+ it("returns true for the seeded fixture password and false for a wrong one", async () => {+ expect(await passwordEncryption.verifyPassword(FIXTURE_PASSWORD)).toBe(true);+ expect(await passwordEncryption.verifyPassword("definitely-not-it")).toBe(false);+ // Verification is case- and whitespace-sensitive.+ expect(await passwordEncryption.verifyPassword(" demo1234")).toBe(false);+ expect(await passwordEncryption.verifyPassword("DEMO1234")).toBe(false);+ });+ });++ describe("getDataKey", () => {+ it("recovers a Uint8Array data key with the correct password", async () => {+ const dataKey = await passwordEncryption.getDataKey(FIXTURE_PASSWORD);++ expect(dataKey).toBeInstanceOf(Uint8Array);+ expect((dataKey as Uint8Array).length).toBeGreaterThan(0);+ });++ it("does not recover the data key with a wrong password", async () => {+ const correct = (await passwordEncryption.getDataKey(FIXTURE_PASSWORD)) as Uint8Array;++ // A wrong password derives a different key, so decryption either fails the+ // embedded digest check (false) or, rarely, returns bytes that differ from+ // the real key. Either way the real data key must never be recovered.+ let recovered: Uint8Array | false | null;+ try {+ recovered = await passwordEncryption.getDataKey("the-wrong-password");+ } catch {+ recovered = false;+ }++ if (recovered instanceof Uint8Array) {+ expect(Array.from(recovered)).not.toEqual(Array.from(correct));+ } else {+ expect(recovered).toBe(false);+ }+ });+ });++ describe("setDataKey + getDataKey round-trip", () => {+ it("re-encrypts a string data key so it decrypts back to the same bytes", async () => {+ const before = (await passwordEncryption.getDataKey(FIXTURE_PASSWORD)) as Uint8Array;+ const oldCipher = options.getOption("encryptedDataKey");++ const plainTextKey = "0123456789abcdef"; // 16 chars+ await withContext(() =>+ passwordEncryption.setDataKey(FIXTURE_PASSWORD, plainTextKey)+ );++ // A fresh IV makes the stored ciphertext change even for the same plaintext.+ expect(options.getOption("encryptedDataKey")).not.toBe(oldCipher);++ const after = (await passwordEncryption.getDataKey(FIXTURE_PASSWORD)) as Uint8Array;+ expect(after).toBeInstanceOf(Uint8Array);+ expect(new TextDecoder().decode(after)).toBe(plainTextKey);+ // The newly stored key differs from whatever the fixture shipped with.+ expect(Array.from(after)).not.toEqual(Array.from(before));+ });++ it("round-trips a Uint8Array data key under a different password", async () => {+ const otherPassword = "another-pass-789";+ const rawKey = Uint8Array.from([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]);++ await withContext(() => passwordEncryption.setDataKey(otherPassword, rawKey));++ const recovered = (await passwordEncryption.getDataKey(otherPassword)) as Uint8Array;+ expect(Array.from(recovered)).toEqual(Array.from(rawKey));++ // Reading the same encrypted key back with the previous password no longer works.+ let withOldPassword: Uint8Array | false | null;+ try {+ withOldPassword = await passwordEncryption.getDataKey(FIXTURE_PASSWORD);+ } catch {+ withOldPassword = false;+ }+ if (withOldPassword instanceof Uint8Array) {+ expect(Array.from(withOldPassword)).not.toEqual(Array.from(rawKey));+ } else {+ expect(withOldPassword).toBe(false);+ }+ });+ });++ describe("verifyPassword without a stored hash", () => {+ it("returns false for any password once passwordVerificationHash is empty", async () => {+ // Kept last: clearing the stored hash is destructive for this fork's DB.+ withContext(() => options.setOption("passwordVerificationHash", ""));++ expect(await passwordEncryption.verifyPassword(FIXTURE_PASSWORD)).toBe(false);+ expect(await passwordEncryption.verifyPassword("anything")).toBe(false);+ });+ });+});diff --git a/packages/trilium-core/src/services/encryption/scrypt.spec.ts b/packages/trilium-core/src/services/encryption/scrypt.spec.tsnew file mode 100644index 0000000000..ad2d908130--- /dev/null+++ b/packages/trilium-core/src/services/encryption/scrypt.spec.ts@@ -0,0 +1,121 @@+import { describe, expect, it } from "vitest";++import options from "../options.js";+import { encodeBase64 } from "../utils/binary.js";+import scryptService, {+ getPasswordDerivedKey,+ getScryptHash,+ getVerificationHash+} from "./scrypt.js";++// The global server spec setup (apps/server/spec/setup.ts) calls initializeCore+// with an in-memory copy of the fixture DB (password "demo1234"). That wires up+// the Node.js crypto provider used by getScryptHash via getCrypto(), and seeds+// the passwordVerificationSalt / passwordDerivedKeySalt / passwordVerificationHash+// options that this module reads. These tests are read-only, so no CLS context+// is required. Each spec file runs in its own vitest fork (pool: "forks").+const FIXTURE_PASSWORD = "demo1234";++describe("scrypt (real DB)", () => {+ describe("getScryptHash", () => {+ it("derives a deterministic 32-byte key for a given (password, salt)", async () => {+ const key1 = await getScryptHash("password", "salt");+ const key2 = await getScryptHash("password", "salt");++ expect(key1).toBeInstanceOf(Uint8Array);+ expect(key1.length).toBe(32);+ expect(Array.from(key1)).toEqual(Array.from(key2));+ });++ it("produces different keys for different passwords or salts", async () => {+ const base = await getScryptHash("password", "salt");++ expect(Array.from(await getScryptHash("password", "other-salt"))).not.toEqual(+ Array.from(base)+ );+ expect(Array.from(await getScryptHash("other-password", "salt"))).not.toEqual(+ Array.from(base)+ );+ });++ it("is sensitive to case and whitespace in the password", async () => {+ const base = await getScryptHash("password", "salt");++ expect(Array.from(await getScryptHash("Password", "salt"))).not.toEqual(+ Array.from(base)+ );+ expect(Array.from(await getScryptHash(" password", "salt"))).not.toEqual(+ Array.from(base)+ );+ });++ it("handles an empty password and an empty salt without throwing", async () => {+ const emptyPassword = await getScryptHash("", "salt");+ const emptySalt = await getScryptHash("password", "");++ expect(emptyPassword.length).toBe(32);+ expect(emptySalt.length).toBe(32);+ // Empty inputs still produce a distinct derived key, not all zeros.+ expect(Array.from(emptyPassword)).not.toEqual(Array.from(new Uint8Array(32)));+ });+ });++ describe("getVerificationHash", () => {+ it("hashes the password against the seeded passwordVerificationSalt", async () => {+ const salt = options.getOption("passwordVerificationSalt");+ const hash = await getVerificationHash(FIXTURE_PASSWORD);++ expect(hash).toBeInstanceOf(Uint8Array);+ expect(hash.length).toBe(32);+ // It must equal a direct scrypt of the password with that exact salt.+ expect(Array.from(hash)).toEqual(Array.from(await getScryptHash(FIXTURE_PASSWORD, salt)));+ });++ it("reproduces the stored passwordVerificationHash for the fixture password", async () => {+ // The fixture DB stores base64(getVerificationHash("demo1234")); deriving it+ // afresh must reproduce that stored value bit-for-bit, proving real crypto.+ const recomputed = encodeBase64(await getVerificationHash(FIXTURE_PASSWORD));++ expect(recomputed).toBe(options.getOption("passwordVerificationHash"));+ });++ it("produces a different hash for a wrong password", async () => {+ const correct = await getVerificationHash(FIXTURE_PASSWORD);+ const wrong = await getVerificationHash("not-the-password");++ expect(Array.from(wrong)).not.toEqual(Array.from(correct));+ });+ });++ describe("getPasswordDerivedKey", () => {+ it("hashes the password against the seeded passwordDerivedKeySalt", async () => {+ const salt = options.getOption("passwordDerivedKeySalt");+ const derived = await getPasswordDerivedKey(FIXTURE_PASSWORD);++ expect(derived).toBeInstanceOf(Uint8Array);+ expect(derived.length).toBe(32);+ expect(Array.from(derived)).toEqual(+ Array.from(await getScryptHash(FIXTURE_PASSWORD, salt))+ );+ });++ it("differs from the verification hash because the two use different salts", async () => {+ const verification = await getVerificationHash(FIXTURE_PASSWORD);+ const derived = await getPasswordDerivedKey(FIXTURE_PASSWORD);++ // Same password, distinct salts -> the derived key and verification hash diverge.+ expect(options.getOption("passwordVerificationSalt")).not.toBe(+ options.getOption("passwordDerivedKeySalt")+ );+ expect(Array.from(derived)).not.toEqual(Array.from(verification));+ });+ });++ describe("default export", () => {+ it("exposes the same functions as the named exports", () => {+ expect(scryptService.getScryptHash).toBe(getScryptHash);+ expect(scryptService.getVerificationHash).toBe(getVerificationHash);+ expect(scryptService.getPasswordDerivedKey).toBe(getPasswordDerivedKey);+ });+ });+});diff --git a/packages/trilium-core/src/services/entity_changes.spec.ts b/packages/trilium-core/src/services/entity_changes.spec.tsnew file mode 100644index 0000000000..bcab5d60b7--- /dev/null+++ b/packages/trilium-core/src/services/entity_changes.spec.ts@@ -0,0 +1,260 @@+import type { EntityChange } from "@triliumnext/commons";++import { afterEach, describe, expect, it, vi } from "vitest";++import dateUtils from "./utils/date.js";+import entityChangesService from "./entity_changes.js";+import events from "./events.js";+import getInstanceId from "./instance_id.js";+import { getContext } from "./context.js";+import { getSql } from "./sql/index.js";++/**+ * Wraps a callback in a CLS context. `putEntityChange` reads the component id+ * and registers the inserted change id via the execution context, both of+ * which require an active CLS context.+ */+function withContext<T>(fn: () => T): T {+ return getContext().init(fn);+}++let counter = 0;++/**+ * Builds a minimal, syntactically valid entity change for an arbitrary+ * (non-real) entity. Each call uses a unique entityId so the unique index on+ * (entityName, entityId) does not collide between the `it()`s sharing the same+ * in-memory fixture DB.+ */+function buildEntityChange(overrides: Partial<EntityChange> = {}): EntityChange {+ counter++;+ return {+ entityName: "notes",+ entityId: `ec-spec-${counter}`,+ hash: "abcd",+ isErased: false,+ utcDateChanged: dateUtils.utcNowDateTime(),+ isSynced: true,+ ...overrides+ } as EntityChange;+}++function readRow(entityName: string, entityId: string) {+ return getSql().getRowOrNull<EntityChange>(+ "SELECT * FROM entity_changes WHERE entityName = ? AND entityId = ?",+ [entityName, entityId]+ );+}++describe("entity_changes service (real DB)", () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });++ describe("putEntityChange", () => {+ it("inserts the row, generates a changeId, applies defaults and normalizes booleans", () => {+ const ec = buildEntityChange({ isSynced: true, isErased: false });+ // No changeId provided -> a random one must be generated.+ delete ec.changeId;++ withContext(() => entityChangesService.putEntityChange(ec));++ const row = readRow(ec.entityName, ec.entityId);+ expect(row).not.toBeNull();+ expect(typeof row!.changeId).toBe("string");+ expect(row!.changeId!.length).toBeGreaterThan(0);+ // Boolean flags are persisted as 0/1 integers.+ expect(row!.isSynced).toBe(1);+ expect(row!.isErased).toBe(0);+ // Defaults are filled in when not supplied.+ expect(row!.instanceId).toBe(getInstanceId());+ expect(row!.componentId).toBeTruthy();+ expect(row!.id).toBeGreaterThan(0);+ });++ it("registers the inserted change id in the CLS context and bumps maxEntityChangeId", () => {+ const ec = buildEntityChange();++ const idsAfter = withContext(() => {+ entityChangesService.putEntityChange(ec);+ return getContext().get<number[]>("entityChangeIds") ?? [];+ });++ const row = readRow(ec.entityName, ec.entityId)!;+ expect(idsAfter).toContain(row.id);+ expect(entityChangesService.getMaxEntityChangeId()).toBeGreaterThanOrEqual(row.id!);+ });++ it("falls back to the 'NA' componentId when none is available in the context", () => {+ const ec = buildEntityChange();++ withContext(() => entityChangesService.putEntityChange(ec));++ const row = readRow(ec.entityName, ec.entityId)!;+ expect(row.componentId).toBe("NA");+ });++ it("preserves an explicitly provided changeId, componentId and isErased flag", () => {+ const ec = buildEntityChange({+ changeId: "fixedChangeId",+ componentId: "myComponent",+ isErased: true,+ isSynced: false+ });++ withContext(() => entityChangesService.putEntityChange(ec));++ const row = readRow(ec.entityName, ec.entityId)!;+ expect(row.changeId).toBe("fixedChangeId");+ expect(row.componentId).toBe("myComponent");+ expect(row.isErased).toBe(1);+ expect(row.isSynced).toBe(0);+ });+ });++ describe("putEntityChangeWithInstanceId", () => {+ it("persists the supplied instance id rather than the local one", () => {+ const ec = buildEntityChange();++ withContext(() => entityChangesService.putEntityChangeWithInstanceId(ec, "remoteInst1"));++ const row = readRow(ec.entityName, ec.entityId)!;+ expect(row.instanceId).toBe("remoteInst1");+ });+ });++ describe("putEntityChangeWithForcedChange", () => {+ it("ignores the incoming changeId and generates a fresh one", () => {+ const ec = buildEntityChange({ changeId: "originalChange" });++ withContext(() => entityChangesService.putEntityChangeWithForcedChange(ec));++ const row = readRow(ec.entityName, ec.entityId)!;+ expect(typeof row.changeId).toBe("string");+ expect(row.changeId).not.toBe("originalChange");+ });+ });++ describe("putEntityChangeForOtherInstances", () => {+ it("clears the changeId/instanceId so they default to local values", () => {+ const ec = buildEntityChange({+ changeId: "shouldBeDropped",+ instanceId: "shouldBeDropped"+ });++ withContext(() => entityChangesService.putEntityChangeForOtherInstances(ec));++ const row = readRow(ec.entityName, ec.entityId)!;+ // Both fields were reset to null and then defaulted at insert time.+ expect(row.changeId).not.toBe("shouldBeDropped");+ expect(row.instanceId).toBe(getInstanceId());+ });+ });++ describe("putNoteReorderingEntityChange", () => {+ it("writes a synced note_reordering change and emits ENTITY_CHANGED with the branch map", () => {+ const emitSpy = vi.spyOn(events, "emit");++ withContext(() => entityChangesService.putNoteReorderingEntityChange("root", "comp-reorder"));++ const row = readRow("note_reordering", "root")!;+ expect(row).not.toBeNull();+ expect(row.hash).toBe("N/A");+ expect(row.isSynced).toBe(1);+ expect(row.isErased).toBe(0);+ expect(row.componentId).toBe("comp-reorder");++ const reorderEmit = emitSpy.mock.calls.find(+ ([eventType, data]) => eventType === events.ENTITY_CHANGED && data?.entityName === "note_reordering"+ );+ expect(reorderEmit).toBeDefined();+ // The emitted entity is the branchId -> notePosition map of root's children.+ expect(reorderEmit![1].entity).toBeTypeOf("object");+ });+ });++ describe("getMaxEntityChangeId / recalculateMaxEntityChangeId", () => {+ it("recalculates the cached max id from the actual table contents", () => {+ entityChangesService.recalculateMaxEntityChangeId();+ const dbMax = getSql().getValue<number>("SELECT COALESCE(MAX(id), 0) FROM entity_changes");++ expect(entityChangesService.getMaxEntityChangeId()).toBe(dbMax);++ // Inserting a new change advances the in-memory counter past the+ // previous max, and recalculation converges back to the DB value.+ const ec = buildEntityChange();+ withContext(() => entityChangesService.putEntityChange(ec));+ expect(entityChangesService.getMaxEntityChangeId()).toBeGreaterThan(dbMax);++ entityChangesService.recalculateMaxEntityChangeId();+ expect(entityChangesService.getMaxEntityChangeId()).toBe(+ getSql().getValue<number>("SELECT COALESCE(MAX(id), 0) FROM entity_changes")+ );+ });+ });++ describe("addEntityChangesForSector", () => {+ it("re-issues forced changes for every existing change in the sector", () => {+ const sql = getSql();++ // Pick an existing options sector and capture the prior changeIds so+ // we can verify they get rewritten (forced) rather than left as-is.+ const sector = sql.getValue<string>(+ "SELECT SUBSTR(entityId, 1, 1) FROM entity_changes WHERE entityName = 'options' LIMIT 1"+ );+ expect(sector).toBeTruthy();++ const before = sql.getColumn<string>(+ "SELECT changeId FROM entity_changes WHERE entityName = 'options' AND SUBSTR(entityId, 1, 1) = ?",+ [sector]+ );+ expect(before.length).toBeGreaterThan(0);++ withContext(() => entityChangesService.addEntityChangesForSector("options", sector));++ const after = sql.getColumn<string>(+ "SELECT changeId FROM entity_changes WHERE entityName = 'options' AND SUBSTR(entityId, 1, 1) = ?",+ [sector]+ );+ // Same number of rows, but every changeId was regenerated.+ expect(after.length).toBe(before.length);+ for (const id of after) {+ expect(before).not.toContain(id);+ }+ });+ });++ describe("fillAllEntityChanges", () => {+ it("rebuilds non-erased entity changes for the core tables without dropping erased ones", () => {+ const sql = getSql();++ // Seed an erased change that must survive the rebuild.+ const erased = buildEntityChange({ isErased: true });+ withContext(() => entityChangesService.putEntityChange(erased));++ const erasedCountBefore = sql.getValue<number>(+ "SELECT COUNT(1) FROM entity_changes WHERE isErased = 1"+ );++ withContext(() => entityChangesService.fillAllEntityChanges());++ // Every note in becca must now have a corresponding (non-erased) change.+ const notesWithoutChange = sql.getValue<number>(`+ SELECT COUNT(1) FROM notes+ WHERE noteId NOT IN (SELECT entityId FROM entity_changes WHERE entityName = 'notes')`);+ expect(notesWithoutChange).toBe(0);++ // Erased changes are preserved (only non-erased rows are wiped/rebuilt).+ const erasedCountAfter = sql.getValue<number>(+ "SELECT COUNT(1) FROM entity_changes WHERE isErased = 1"+ );+ expect(erasedCountAfter).toBeGreaterThanOrEqual(erasedCountBefore);++ // Blobs are always synced.+ const unsyncedBlobs = sql.getValue<number>(+ "SELECT COUNT(1) FROM entity_changes WHERE entityName = 'blobs' AND isSynced = 0"+ );+ expect(unsyncedBlobs).toBe(0);+ });+ });+});diff --git a/packages/trilium-core/src/services/erase.spec.ts b/packages/trilium-core/src/services/erase.spec.tsnew file mode 100644index 0000000000..a86740d976--- /dev/null+++ b/packages/trilium-core/src/services/erase.spec.ts@@ -0,0 +1,229 @@+import { describe, expect, it } from "vitest";++import becca from "../becca/becca.js";+import type BNote from "../becca/entities/bnote.js";+import { getContext } from "./context.js";+import eraseService from "./erase.js";+import noteService from "./notes.js";+import { getSql } from "./sql/index.js";++/**+ * Wraps a callback in a CLS context. Entity mutations (createNewNote,+ * markAsDeleted, setContent) require CLS to be initialised. The erase+ * service itself also opens a transaction, which needs the context.+ */+function withContext<T>(fn: () => T): T {+ return getContext().init(fn);+}++let counter = 0;++/**+ * Creates a fresh text note under the given parent in the real in-memory DB.+ * Each call uses a unique title since the same fixture DB is shared between+ * the `it()`s in this file.+ */+function createNote(content = "<p>hello</p>"): BNote {+ counter++;+ return withContext(() =>+ noteService.createNewNote({+ parentNoteId: "root",+ title: `erase-spec-${counter}`,+ content,+ type: "text"+ })+ ).note;+}++function rowCount(table: string, idColumn: string, id: string): number {+ return getSql().getValue<number>(`SELECT COUNT(1) FROM ${table} WHERE ${idColumn} = ?`, [id]);+}++function entityChangeFor(entityName: string, entityId: string) {+ return getSql().getRowOrNull<{ isErased: number }>(+ "SELECT isErased FROM entity_changes WHERE entityName = ? AND entityId = ?",+ [entityName, entityId]+ );+}++describe("erase service (real DB)", () => {+ describe("eraseNotesWithDeleteId", () => {+ it("erases a soft-deleted note plus its dependent branch and attribute, marking entity_changes as erased", () => {+ const note = createNote();+ const noteId = note.noteId;+ const branch = note.getParentBranches()[0];+ const branchId = branch.branchId;+ const attribute = withContext(() => note.addLabel("eraseMe", "v"));+ const attributeId = attribute.attributeId;++ const deleteId = `del-${counter}`;+ withContext(() => {+ attribute.markAsDeleted(deleteId);+ branch.markAsDeleted(deleteId);+ note.markAsDeleted(deleteId);+ });++ // Sanity: rows still physically present after a soft delete.+ expect(rowCount("notes", "noteId", noteId)).toBe(1);++ withContext(() => eraseService.eraseNotesWithDeleteId(deleteId));++ // The physical rows are gone.+ expect(rowCount("notes", "noteId", noteId)).toBe(0);+ expect(rowCount("branches", "branchId", branchId)).toBe(0);+ expect(rowCount("attributes", "attributeId", attributeId)).toBe(0);++ // The entity_changes records survive but are flagged as erased so the+ // erasure propagates to sync peers.+ expect(entityChangeFor("notes", noteId)?.isErased).toBe(1);+ expect(entityChangeFor("branches", branchId)?.isErased).toBe(1);+ expect(entityChangeFor("attributes", attributeId)?.isErased).toBe(1);+ });++ it("erases a soft-deleted attachment carrying a matching deleteId", () => {+ const note = createNote();+ const attachment = withContext(() =>+ note.saveAttachment({ role: "file", mime: "text/plain", title: "att", content: "data" })+ );+ const attachmentId = attachment.attachmentId;++ const deleteId = `del-att-${counter}`;+ withContext(() => attachment.markAsDeleted(deleteId));++ expect(rowCount("attachments", "attachmentId", attachmentId)).toBe(1);++ withContext(() => eraseService.eraseNotesWithDeleteId(deleteId));++ expect(rowCount("attachments", "attachmentId", attachmentId)).toBe(0);+ expect(entityChangeFor("attachments", attachmentId)?.isErased).toBe(1);+ });++ it("does nothing for a deleteId that matches no soft-deleted entities", () => {+ const note = createNote();+ const noteId = note.noteId;++ withContext(() => eraseService.eraseNotesWithDeleteId("nonexistent-delete-id"));++ // The live note is untouched.+ expect(rowCount("notes", "noteId", noteId)).toBe(1);+ });+ });++ describe("eraseDeletedNotesNow", () => {+ it("erases entities deleted in the past (cutoff 0 seconds)", () => {+ const note = createNote();+ const noteId = note.noteId;+ const branchId = note.getParentBranches()[0].branchId;++ // deleteNote soft-deletes the note, its branch and attributes.+ withContext(() => note.deleteNote());++ expect(rowCount("notes", "noteId", noteId)).toBe(1);++ withContext(() => eraseService.eraseDeletedNotesNow());++ expect(rowCount("notes", "noteId", noteId)).toBe(0);+ expect(rowCount("branches", "branchId", branchId)).toBe(0);+ expect(entityChangeFor("notes", noteId)?.isErased).toBe(1);+ });++ it("leaves a live (non-deleted) note alone", () => {+ const note = createNote();+ const noteId = note.noteId;++ withContext(() => eraseService.eraseDeletedNotesNow());++ expect(rowCount("notes", "noteId", noteId)).toBe(1);+ });+ });++ describe("eraseUnusedBlobs", () => {+ it("purges a blob that is no longer referenced and deletes its entity_changes row entirely", () => {+ // Insert an orphan blob with a matching entity_changes record. It is+ // referenced by nothing, so it qualifies as unused.+ const blobId = `orphanBlob-${++counter}`;+ withContext(() => {+ getSql().execute(+ "INSERT INTO blobs (blobId, content, dateModified, utcDateModified) VALUES (?, ?, ?, ?)",+ [blobId, "junk", "2020-01-01 00:00:00.000+0000", "2020-01-01 00:00:00.000Z"]+ );+ getSql().execute(+ `INSERT INTO entity_changes+ (entityName, entityId, hash, isErased, changeId, componentId, instanceId, isSynced, utcDateChanged)+ VALUES ('blobs', ?, 'h', 0, 'c', 'comp', 'inst', 1, '2020-01-01 00:00:00.000Z')`,+ [blobId]+ );+ });++ withContext(() => eraseService.eraseUnusedBlobs());++ // Blobs are purged completely rather than marked erased.+ expect(rowCount("blobs", "blobId", blobId)).toBe(0);+ expect(entityChangeFor("blobs", blobId)).toBeNull();+ });++ it("keeps a blob that is still referenced by a live note", () => {+ const note = createNote("<p>referenced content</p>");+ const blobId = getSql().getValue<string>("SELECT blobId FROM notes WHERE noteId = ?", [+ note.noteId+ ]);+ expect(blobId).toBeTruthy();++ withContext(() => eraseService.eraseUnusedBlobs());++ expect(rowCount("blobs", "blobId", blobId)).toBe(1);+ });+ });++ describe("eraseUnusedAttachmentsNow", () => {+ it("erases an attachment scheduled for erasure in the past", () => {+ const note = createNote();+ const attachment = withContext(() =>+ note.saveAttachment({ role: "file", mime: "text/plain", title: "sched", content: "x" })+ );+ const attachmentId = attachment.attachmentId;++ // Mark the attachment as scheduled for erasure well in the past so it+ // falls before the now-based cutoff.+ withContext(() =>+ getSql().execute(+ "UPDATE attachments SET utcDateScheduledForErasureSince = ? WHERE attachmentId = ?",+ ["2000-01-01 00:00:00.000Z", attachmentId]+ )+ );++ withContext(() => eraseService.eraseUnusedAttachmentsNow());++ expect(rowCount("attachments", "attachmentId", attachmentId)).toBe(0);+ expect(entityChangeFor("attachments", attachmentId)?.isErased).toBe(1);+ });++ it("does not erase an attachment that is not scheduled for erasure", () => {+ const note = createNote();+ const attachment = withContext(() =>+ note.saveAttachment({ role: "file", mime: "text/plain", title: "keep", content: "x" })+ );+ const attachmentId = attachment.attachmentId;++ withContext(() => eraseService.eraseUnusedAttachmentsNow());++ expect(rowCount("attachments", "attachmentId", attachmentId)).toBe(1);+ });+ });++ describe("empty-input no-ops", () => {+ it("eraseAttachments and eraseRevisions are no-ops for an empty id list", () => {+ const note = createNote();+ const noteId = note.noteId;++ withContext(() => {+ eraseService.eraseAttachments([]);+ eraseService.eraseRevisions([]);+ });++ // Nothing was touched; the note (and everything else) is intact.+ expect(becca.notes[noteId]).toBeDefined();+ expect(rowCount("notes", "noteId", noteId)).toBe(1);+ });+ });+});diff --git a/packages/trilium-core/src/services/export/opml.spec.ts b/packages/trilium-core/src/services/export/opml.spec.tsnew file mode 100644index 0000000000..38aa1a3027--- /dev/null+++ b/packages/trilium-core/src/services/export/opml.spec.ts@@ -0,0 +1,217 @@+import type { Response } from "express";+import { beforeAll, describe, expect, it } from "vitest";++import type BBranch from "../../becca/entities/bbranch.js";+import type BNote from "../../becca/entities/bnote.js";+import { getContext } from "../context.js";+import noteService from "../notes.js";+import sql_init from "../sql_init.js";+import TaskContext from "../task_context.js";+import opml from "./opml.js";++/**+ * Wraps a callback in a CLS context. Entity mutations (createNewNote,+ * addLabel) require CLS to be initialised.+ */+function withContext<T>(fn: () => T): T {+ return getContext().init(fn);+}++let counter = 0;++/**+ * Creates a fresh note under the given parent in the shared in-memory fixture+ * DB. Each call uses a unique title so the `it()`s in this file (which share a+ * single DB copy per fork) don't collide.+ */+function createNote(+ parentNoteId: string,+ overrides: Partial<{ title: string; content: string; type: BNote["type"]; mime: string }> = {}+): { note: BNote; branch: BBranch } {+ counter++;+ return withContext(() =>+ noteService.createNewNote({+ parentNoteId,+ title: overrides.title ?? `opml-export-spec-${counter}`,+ content: overrides.content ?? "<p>hello</p>",+ type: overrides.type ?? "text",+ mime: overrides.mime+ })+ );+}++/** A minimal Express-`res`-like sink that records header writes and the body. */+class FakeResponse {+ headers: Record<string, string> = {};+ chunks: string[] = [];+ ended = false;++ setHeader(name: string, value: string) {+ this.headers[name] = value;+ return this;+ }++ write(chunk: string) {+ this.chunks.push(chunk);+ return true;+ }++ end() {+ this.ended = true;+ return this;+ }++ get body() {+ return this.chunks.join("");+ }+}++function getTaskContext() {+ // "no-progress-reporting" suppresses the WebSocket broadcast in increaseProgressCount.+ return TaskContext.getInstance("opml-export-spec", "export", null);+}++function runExport(branch: BBranch, version: string): FakeResponse {+ const res = new FakeResponse();+ opml.exportToOpml(getTaskContext(), branch, version, res as unknown as Response);+ return res;+}++describe("exportToOpml (real DB)", () => {+ beforeAll(async () => {+ sql_init.initializeDb();+ await sql_init.dbReady;+ });++ it("rejects an unrecognized OPML version before touching the response", () => {+ const { branch } = createNote("root");+ const res = new FakeResponse();++ expect(() => opml.exportToOpml(getTaskContext(), branch, "9.9", res as unknown as Response)).toThrow(/9\.9/);+ // Nothing should have been written when the version is invalid.+ expect(res.chunks).toHaveLength(0);+ expect(res.ended).toBe(false);+ });++ it("exports a v1.0 document with the opml header, download headers and stripped text content", () => {+ const { note, branch } = createNote("root", {+ title: "Root v1",+ content: "<p>line one</p><p>line two</p>"+ });++ const res = runExport(branch, "1.0");++ // Streaming the export sets the OPML download headers.+ expect(res.headers["Content-Type"]).toBe("text/x-opml");+ expect(res.headers["Content-Disposition"]).toContain("Root%20v1.opml");+ expect(res.ended).toBe(true);++ const body = res.body;+ // The XML/opml envelope is emitted with the requested version.+ expect(body).toContain(`<opml version="1.0">`);+ expect(body).toContain("<title>Trilium export</title>");+ expect(body.trim().endsWith("</opml>")).toBe(true);++ // v1 uses the `title`/`text` attribute pair; every <p> opener (including+ // the leading one) becomes a newline encoded as and the surrounding+ // tags are stripped.+ expect(body).toContain(`<outline title="Root v1" text=" line one line two">`);+ expect(body).toContain("</outline>");+ // The note was counted in the export progress (no throw from increaseProgressCount).+ expect(note.title).toBe("Root v1");+ });++ it("exports a v2.0 document using the text/_note attribute pair with raw escaped HTML", () => {+ const { branch } = createNote("root", {+ title: "Root v2",+ content: "<p>body</p>"+ });++ const res = runExport(branch, "2.0");++ expect(res.headers["Content-Type"]).toBe("text/x-opml");+ const body = res.body;+ expect(body).toContain(`<opml version="2.0">`);+ // v2 keeps the raw HTML content but XML-escapes it into the _note attribute.+ expect(body).toContain(`<outline text="Root v2" _note="<p>body</p>">`);+ });++ it("escapes XML-significant characters in titles for both versions", () => {+ const { branch } = createNote("root", {+ title: `A & B <c> "d" 'e'`,+ content: ""+ });++ const v1 = runExport(branch, "1.0").body;+ const v2 = runExport(branch, "2.0").body;++ const escapedTitle = `A & B <c> "d" 'e'`;+ expect(v1).toContain(`<outline title="${escapedTitle}" text="">`);+ expect(v2).toContain(`<outline text="${escapedTitle}" _note="">`);+ });++ it("recursively exports child notes nested inside the parent outline", () => {+ const { note: parent, branch } = createNote("root", { title: "Parent node", content: "" });+ createNote(parent.noteId, { title: "Child A", content: "<p>a</p>" });+ createNote(parent.noteId, { title: "Child B", content: "<p>b</p>" });++ const body = runExport(branch, "2.0").body;++ // The parent outline is opened, both children appear nested before it closes.+ const parentIdx = body.indexOf(`text="Parent node"`);+ const childAIdx = body.indexOf(`text="Child A"`);+ const childBIdx = body.indexOf(`text="Child B"`);+ expect(parentIdx).toBeGreaterThanOrEqual(0);+ expect(childAIdx).toBeGreaterThan(parentIdx);+ expect(childBIdx).toBeGreaterThan(parentIdx);++ // Three opening outlines (parent + two children) and three closing tags.+ expect(body.match(/<outline /g)).toHaveLength(3);+ expect(body.match(/<\/outline>/g)).toHaveLength(3);+ });++ it("skips notes labelled #excludeFromExport", () => {+ const { note: parent, branch } = createNote("root", { title: "Export parent", content: "" });+ createNote(parent.noteId, { title: "Kept child", content: "<p>keep</p>" });+ const { note: excluded } = createNote(parent.noteId, { title: "Excluded child", content: "<p>no</p>" });+ withContext(() => excluded.addLabel("excludeFromExport"));++ const body = runExport(branch, "2.0").body;++ expect(body).toContain(`text="Kept child"`);+ expect(body).not.toContain(`text="Excluded child"`);+ // Parent + the single kept child remain.+ expect(body.match(/<outline /g)).toHaveLength(2);+ });++ it("includes the branch prefix in the title and the download filename", () => {+ const { note, branch } = createNote("root", { title: "Prefixed", content: "" });+ withContext(() => {+ branch.prefix = "Pre";+ branch.save();+ });++ const res = runExport(branch, "1.0");++ expect(res.headers["Content-Disposition"]).toContain("Pre%20-%20Prefixed.opml");+ expect(res.body).toContain(`<outline title="Pre - Prefixed" text="">`);+ expect(note.title).toBe("Prefixed");+ });++ it("leaves text empty for non-string (binary) content notes", () => {+ // An image note has binary content, so hasStringContent() is false and the+ // text/_note attribute must be emitted empty rather than dumping the buffer.+ const { branch } = createNote("root", {+ title: "Binary note",+ type: "image",+ mime: "image/png",+ content: "not-really-png-bytes"+ });++ const v1 = runExport(branch, "1.0").body;+ const v2 = runExport(branch, "2.0").body;++ expect(v1).toContain(`<outline title="Binary note" text="">`);+ expect(v2).toContain(`<outline text="Binary note" _note="">`);+ });+}, 60_000);diff --git a/packages/trilium-core/src/services/export/zip.spec.ts b/packages/trilium-core/src/services/export/zip.spec.tsnew file mode 100644index 0000000000..8a196db61d--- /dev/null+++ b/packages/trilium-core/src/services/export/zip.spec.ts@@ -0,0 +1,293 @@+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 type BBranch from "../../becca/entities/bbranch.js";+import type BNote from "../../becca/entities/bnote.js";+import type { ExportFormat, NoteMetaFile } from "../../meta.js";+import { getContext } from "../context.js";+import noteService from "../notes.js";+import sql_init from "../sql_init.js";+import { getZipProvider } from "../zip_provider.js";+import zip from "./zip.js";++function withContext<T>(fn: () => T): T {+ return getContext().init(fn);+}++let counter = 0;++/**+ * Creates a fresh note under the given parent in the shared in-memory fixture+ * DB. Each call uses a unique title so the `it()`s in this file (which share+ * one DB copy per fork) don't collide.+ */+function createNote(+ parentNoteId: string,+ overrides: Partial<{ title: string; content: string; type: BNote["type"]; mime: string }> = {}+): { note: BNote; branch: BBranch } {+ counter++;+ return withContext(() =>+ noteService.createNewNote({+ parentNoteId,+ title: overrides.title ?? `zip-spec-${counter}`,+ content: overrides.content ?? "<p>hello</p>",+ type: overrides.type ?? "text",+ mime: overrides.mime+ })+ );+}++/** A minimal Express-`res`-like writable that collects everything piped into it. */+class FakeResponse extends PassThrough {+ headers: Record<string, string> = {};+ statusCode = 200;+ sentBody: string | undefined;+ removedHeaders: string[] = [];++ setHeader(name: string, value: string) {+ this.headers[name] = value;+ return this;+ }++ removeHeader(name: string) {+ this.removedHeaders.push(name);+ delete this.headers[name];+ return this;+ }++ status(code: number) {+ this.statusCode = code;+ return this;+ }++ send(body: string) {+ this.sentBody = body;+ return this;+ }+}++/** Drains a FakeResponse and returns the full piped buffer once the archive finalizes. */+function collect(res: FakeResponse): Promise<Buffer> {+ const chunks: Buffer[] = [];+ res.on("data", (chunk: Buffer) => chunks.push(chunk));+ return new Promise((resolve, reject) => {+ res.on("end", () => resolve(Buffer.concat(chunks)));+ res.on("error", reject);+ });+}++/** Unzips the produced archive into a `{ fileName -> contents }` map. */+async function readArchive(buffer: Buffer): Promise<Record<string, Buffer>> {+ const entries: Record<string, Buffer> = {};+ await getZipProvider().readZipFile(buffer, async (entry, readContent) => {+ entries[entry.fileName] = Buffer.from(await readContent());+ });+ return entries;+}++async function exportSubtree(branch: BBranch, format: ExportFormat = "html") {+ const taskContext = (await import("../task_context.js")).default;+ const ctx = new taskContext("no-progress-reporting", "export", null);+ const res = new FakeResponse();+ const done = collect(res);+ await zip.exportToZip(ctx, branch, format, res as unknown as Record<string, unknown>);+ const buffer = await done;+ return { buffer, res, entries: await readArchive(buffer) };+}++function parseMeta(entries: Record<string, Buffer>): NoteMetaFile {+ return JSON.parse(entries["!!!meta.json"].toString("utf-8"));+}++describe("zip export (real DB)", () => {+ beforeAll(async () => {+ sql_init.initializeDb();+ await sql_init.dbReady;+ });++ 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>" });+ const branch = note.getParentBranches()[0];++ const { entries, res } = await exportSubtree(branch, "html");++ // The meta manifest is always present and describes the exported root.+ const meta = parseMeta(entries);+ expect(meta.formatVersion).toBe(2);+ expect(typeof meta.appVersion).toBe("string");++ const rootMeta = meta.files[0];+ expect(rootMeta.noteId).toBe(note.noteId);+ expect(rootMeta.isClone).toBe(false);+ expect(rootMeta.type).toBe("text");+ // HTML export of a text note maps to an .html data file.+ expect(rootMeta.dataFileName).toMatch(/\.html$/);+ expect(rootMeta.format).toBe("html");++ // The corresponding data file is in the archive and contains the body.+ const dataFile = entries[rootMeta.dataFileName!];+ expect(dataFile).toBeDefined();+ expect(dataFile.toString("utf-8")).toContain("body text");++ // Streaming a download sets the disposition + content-type headers.+ expect(res.headers["Content-Type"]).toBe("application/zip");+ expect(res.headers["Content-Disposition"]).toContain("ExportRoot.zip");++ // The HTML provider injects extra navigation/index/style files marked noImport.+ expect(meta.files.some((f) => f.noImport && f.dataFileName === "navigation.html")).toBe(true);+ expect(meta.files.some((f) => f.noImport && f.dataFileName === "index.html")).toBe(true);+ expect(meta.files.some((f) => f.noImport && f.dataFileName === "style.css")).toBe(true);+ expect(entries["navigation.html"]).toBeDefined();+ expect(entries["index.html"]).toBeDefined();+ expect(entries["style.css"]).toBeDefined();+ });++ it("exports a subtree with nested children into a directory hierarchy", async () => {+ const { note: parent } = createNote("root", { title: "Parent", content: "" });+ const { note: child } = createNote(parent.noteId, { title: "Child", content: "<p>child body</p>" });+ const branch = parent.getParentBranches()[0];++ const { entries } = await exportSubtree(branch, "html");+ const meta = parseMeta(entries);++ const rootMeta = meta.files[0];+ expect(rootMeta.noteId).toBe(parent.noteId);+ // A parent with children gets a directory and a nested child entry.+ expect(rootMeta.dirFileName).toBeTruthy();+ expect(rootMeta.children).toHaveLength(1);++ const childMeta = rootMeta.children![0];+ expect(childMeta.noteId).toBe(child.noteId);++ // The child's data file lives under the parent's directory.+ const childPath = `${rootMeta.dirFileName}/${childMeta.dataFileName}`;+ expect(entries[childPath]).toBeDefined();+ expect(entries[childPath].toString("utf-8")).toContain("child body");+ // The directory entry itself is emitted.+ expect(entries[`${rootMeta.dirFileName}/`]).toBeDefined();+ });++ it("exports text notes as markdown when the markdown format is requested", async () => {+ const { note } = createNote("root", { title: "MdNote", content: "<h2>Heading</h2>" });+ const branch = note.getParentBranches()[0];++ const { entries } = await exportSubtree(branch, "markdown");+ const rootMeta = parseMeta(entries).files[0];++ expect(rootMeta.format).toBe("markdown");+ expect(rootMeta.dataFileName).toMatch(/\.md$/);+ // Markdown conversion turns the HTML heading into a markdown heading.+ expect(entries[rootMeta.dataFileName!].toString("utf-8")).toContain("## Heading");+ });++ it("carries owned attributes into the note meta but drops out-of-export relations", async () => {+ // A note living outside the exported subtree: a relation to it is valid+ // to save but must be filtered out of the export meta.+ const { note: outsider } = createNote("root", { title: "Outsider", content: "<p>o</p>" });+ const { note } = createNote("root", { title: "Attributed", content: "<p>x</p>" });+ withContext(() => {+ note.addLabel("myLabel", "labelValue");+ // Relation to "root" is a named noteId and is preserved.+ note.addRelation("rootRel", "root");+ // Relation to a note not contained in this export is dropped.+ note.addRelation("outsideRel", outsider.noteId);+ });+ const branch = note.getParentBranches()[0];++ const { entries } = await exportSubtree(branch, "html");+ const rootMeta = parseMeta(entries).files[0];+ const attrs = rootMeta.attributes ?? [];++ const label = attrs.find((a) => a.name === "myLabel");+ expect(label).toMatchObject({ type: "label", value: "labelValue" });++ expect(attrs.some((a) => a.name === "rootRel")).toBe(true);+ expect(attrs.some((a) => a.name === "outsideRel")).toBe(false);+ });++ it("excludes notes marked with #excludeFromExport", async () => {+ const { note: parent } = createNote("root", { title: "WithExcluded", content: "" });+ const { note: kept } = createNote(parent.noteId, { title: "Kept", content: "<p>kept</p>" });+ const { note: excluded } = createNote(parent.noteId, { title: "Excluded", content: "<p>no</p>" });+ withContext(() => excluded.addLabel("excludeFromExport"));+ const branch = parent.getParentBranches()[0];++ const { entries } = await exportSubtree(branch, "html");+ const rootMeta = parseMeta(entries).files[0];+ const childIds = (rootMeta.children ?? []).map((c) => c.noteId);++ expect(childIds).toContain(kept.noteId);+ expect(childIds).not.toContain(excluded.noteId);+ });++ it("emits a .clone data file when the same note appears twice in the subtree", async () => {+ const { note: parent } = createNote("root", { title: "CloneHolder", content: "" });+ const { note: folderA } = createNote(parent.noteId, { title: "FolderA", content: "" });+ const { note: folderB } = createNote(parent.noteId, { title: "FolderB", content: "" });+ const { note: original } = createNote(folderA.noteId, { title: "Original", content: "<p>orig</p>" });++ // Clone the note into a second folder inside the same exported subtree.+ const cloningService = (await import("../cloning.js")).default;+ const cloneRes = withContext(() => cloningService.cloneNoteToParentNote(original.noteId, folderB.noteId));+ expect(cloneRes.success).toBe(true);++ const branch = parent.getParentBranches()[0];+ const { entries } = await exportSubtree(branch, "html");+ const rootMeta = parseMeta(entries).files[0];++ // Flatten the meta tree to find every occurrence of the note.+ const occurrences: { isClone?: boolean; dataFileName?: string; dirPath?: string }[] = [];+ function walk(meta: NoteMetaFile["files"][number], dirPath: string) {+ if (meta.noteId === original.noteId) {+ occurrences.push({ isClone: meta.isClone, dataFileName: meta.dataFileName, dirPath });+ }+ for (const child of meta.children ?? []) {+ walk(child, meta.dirFileName ? `${dirPath}${meta.dirFileName}/` : dirPath);+ }+ }+ walk(rootMeta, "");++ // The note appears twice: once as the real export, once as a clone marker.+ expect(occurrences).toHaveLength(2);+ const clones = occurrences.filter((o) => o.isClone);+ expect(clones).toHaveLength(1);++ const clonePath = `${clones[0].dirPath}${clones[0].dataFileName}`;+ expect(entries[clonePath].toString("utf-8")).toContain("clone of a note");+ });+ });++ describe("exportToZipFile", () => {+ let tempDir: string;++ beforeAll(() => {+ tempDir = mkdtempSync(join(tmpdir(), "trilium-zip-export-"));+ });++ it("writes a valid, readable zip archive to the given path", async () => {+ const { note } = createNote("root", { title: "FileExport", content: "<p>to file</p>" });+ const zipPath = join(tempDir, `export-${note.noteId}.zip`);++ await withContext(() => zip.exportToZipFile(note.noteId, "html", zipPath));++ const buffer = readFileSync(zipPath);+ const entries = await readArchive(buffer);+ const rootMeta = parseMeta(entries).files[0];++ expect(rootMeta.noteId).toBe(note.noteId);+ expect(entries[rootMeta.dataFileName!].toString("utf-8")).toContain("to file");++ rmSync(zipPath, { force: true });+ });++ it("throws a ValidationError for a non-existent note", async () => {+ await expect(+ withContext(() => zip.exportToZipFile("missingNoteId123", "html", join(tempDir, "never.zip")))+ ).rejects.toThrow(/not found/);+ });+ });+});diff --git a/packages/trilium-core/src/services/export/zip/abstract_provider.spec.ts b/packages/trilium-core/src/services/export/zip/abstract_provider.spec.tsnew file mode 100644index 0000000000..d93fe9be17--- /dev/null+++ b/packages/trilium-core/src/services/export/zip/abstract_provider.spec.ts@@ -0,0 +1,123 @@+import { describe, expect, it, vi } from "vitest";++import type { NoteMeta, NoteMetaFile } from "../../../meta.js";+import type { ZipArchive } from "../../zip_provider.js";+import { ZipExportProvider, ZipExportProviderData } from "./abstract_provider.js";++/**+ * The module under test only exposes an abstract class, so we exercise it+ * through a minimal concrete subclass whose abstract methods are inert. All the+ * runtime behaviour worth covering lives in the constructor and `mapExtension`.+ */+class TestProvider extends ZipExportProvider {+ prepareMeta(_metaFile: NoteMetaFile): void {+ // no-op+ }+ prepareContent(_title: string, content: string | Uint8Array): string | Uint8Array {+ return content;+ }+ afterDone(_rootMeta: NoteMeta): void {+ // no-op+ }+}++function buildArchive(): ZipArchive {+ return {+ append: vi.fn(),+ pipe: vi.fn(),+ finalize: vi.fn()+ };+}++function buildProvider(overrides: Partial<ZipExportProviderData> = {}) {+ const data: ZipExportProviderData = {+ branch: overrides.branch ?? ({} as ZipExportProviderData["branch"]),+ getNoteTargetUrl: overrides.getNoteTargetUrl ?? ((targetNoteId) => `${targetNoteId}.html`),+ archive: overrides.archive ?? buildArchive(),+ zipExportOptions: overrides.zipExportOptions,+ rewriteFn: overrides.rewriteFn ?? ((content) => content)+ };+ return new TestProvider(data);+}++describe("ZipExportProvider", () => {+ describe("constructor", () => {+ it("assigns every field from the provided data", () => {+ const archive = buildArchive();+ const getNoteTargetUrl = vi.fn(() => null);+ const rewriteFn = vi.fn((content: string) => content);+ const zipExportOptions = { skipHtmlTemplate: true };+ const branch = { branchId: "abc" } as unknown as ZipExportProviderData["branch"];++ const provider = buildProvider({+ branch,+ getNoteTargetUrl,+ archive,+ zipExportOptions,+ rewriteFn+ });++ expect(provider.branch).toBe(branch);+ expect(provider.getNoteTargetUrl).toBe(getNoteTargetUrl);+ expect(provider.archive).toBe(archive);+ expect(provider.zipExportOptions).toBe(zipExportOptions);+ expect(provider.rewriteFn).toBe(rewriteFn);+ });++ it("leaves zipExportOptions undefined when none are passed", () => {+ const provider = buildProvider({ zipExportOptions: undefined });+ expect(provider.zipExportOptions).toBeUndefined();+ });+ });++ describe("mapExtension", () => {+ const provider = buildProvider();++ it("forces md/html for text notes based on the requested format", () => {+ // These two win over any existing extension or mime detection.+ expect(provider.mapExtension("text", "text/html", ".bak", "markdown")).toBe("md");+ expect(provider.mapExtension("text", "anything", ".bak", "html")).toBe("html");+ });++ it("maps javascript mimes to js regardless of note type", () => {+ expect(provider.mapExtension("code", "application/x-javascript", "", "html")).toBe("js");+ expect(provider.mapExtension("code", "text/javascript", "", "html")).toBe("js");+ });++ it("maps canvas notes and json mimes to json", () => {+ expect(provider.mapExtension("canvas", "application/octet-stream", "", "html")).toBe("json");+ expect(provider.mapExtension("file", "application/json", "", "html")).toBe("json");+ });++ it("preserves an existing extension (returns null) ahead of jpg/mermaid/fallback handling", () => {+ // existingExtension is checked before the jpg/mermaid special cases,+ // so a set extension short-circuits even for those mimes.+ expect(provider.mapExtension("image", "image/png", ".png", "html")).toBeNull();+ expect(provider.mapExtension("image", "image/jpg", ".jpeg", "html")).toBeNull();+ expect(provider.mapExtension("code", "text/mermaid", ".mmd", "html")).toBeNull();+ });++ it("normalises image/jpg and text/mermaid special cases when no extension exists", () => {+ expect(provider.mapExtension("image", "image/jpg", "", "html")).toBe("jpg");+ expect(provider.mapExtension("image", " IMAGE/JPG ", "", "html")).toBe("jpg");+ expect(provider.mapExtension("code", "text/mermaid", "", "html")).toBe("txt");+ expect(provider.mapExtension("code", " Text/Mermaid ", "", "html")).toBe("txt");+ });++ it("falls back to the custom code-mime map for markdown mimes", () => {+ for (const mime of ["text/x-markdown", "text/markdown", "text/x-gfm"]) {+ expect(provider.mapExtension("code", mime, "", "html")).toBe("md");+ }+ });++ it("falls back to the mime-types lookup for recognised mimes", () => {+ expect(provider.mapExtension("image", "image/png", "", "html")).toBe("png");+ expect(provider.mapExtension("code", "text/css", "", "html")).toBe("css");+ });++ it("uses the 'dat' fallback when nothing else resolves", () => {+ expect(provider.mapExtension("file", "application/totally-unknown", "", "html")).toBe("dat");+ expect(provider.mapExtension(null, "", "", "html")).toBe("dat");+ });+ });+});diff --git a/packages/trilium-core/src/services/export/zip/html.spec.ts b/packages/trilium-core/src/services/export/zip/html.spec.tsnew file mode 100644index 0000000000..f20500d5bd--- /dev/null+++ b/packages/trilium-core/src/services/export/zip/html.spec.ts@@ -0,0 +1,258 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++import type { NoteMeta, NoteMetaFile } from "../../../meta.js";+import type { ZipArchive } from "../../zip_provider.js";+import HtmlExportProvider, { HtmlExportProviderOptions } from "./html.js";+import type { AdvancedExportOptions, ZipExportProviderData } from "./abstract_provider.js";++interface AppendCall {+ content: string | Uint8Array;+ name: string;+}++function buildArchive(calls: AppendCall[]): ZipArchive {+ return {+ append: (content, options) => calls.push({ content, name: options.name }),+ pipe: vi.fn(),+ finalize: vi.fn()+ };+}++function buildProvider(+ overrides: {+ zipExportOptions?: AdvancedExportOptions;+ getNoteTargetUrl?: ZipExportProviderData["getNoteTargetUrl"];+ rewriteFn?: ZipExportProviderData["rewriteFn"];+ options?: HtmlExportProviderOptions;+ } = {}+) {+ const appendCalls: AppendCall[] = [];+ const data: ZipExportProviderData = {+ // The provider never touches the branch in this module.+ branch: {} as ZipExportProviderData["branch"],+ getNoteTargetUrl: overrides.getNoteTargetUrl ?? ((targetNoteId) => `${targetNoteId}.html`),+ archive: buildArchive(appendCalls),+ zipExportOptions: overrides.zipExportOptions,+ rewriteFn: overrides.rewriteFn ?? ((content) => content)+ };+ const provider = new HtmlExportProvider(data, overrides.options);+ return { provider, appendCalls };+}++function buildMetaFile(): NoteMetaFile {+ return { formatVersion: 1, appVersion: "1.0.0", files: [] };+}++describe("HtmlExportProvider", () => {+ beforeEach(() => {+ vi.restoreAllMocks();+ });++ describe("prepareMeta", () => {+ it("registers navigation, index and style files in the meta", () => {+ const { provider } = buildProvider();+ const metaFile = buildMetaFile();++ provider.prepareMeta(metaFile);++ const dataFileNames = metaFile.files.map((f) => f.dataFileName);+ expect(dataFileNames).toEqual(["navigation.html", "index.html", "style.css"]);+ expect(metaFile.files.every((f) => f.noImport)).toBe(true);+ });++ it("skips extra files when skipExtraFiles is set", () => {+ const { provider } = buildProvider({ zipExportOptions: { skipExtraFiles: true } });+ const metaFile = buildMetaFile();++ provider.prepareMeta(metaFile);++ expect(metaFile.files).toHaveLength(0);+ });+ });++ describe("prepareContent", () => {+ it("wraps bare HTML content in a full template with escaped title and css path", () => {+ const rewriteFn = vi.fn((content: string, _noteMeta: NoteMeta) => content);+ const { provider } = buildProvider({ rewriteFn });+ const noteMeta: NoteMeta = {+ format: "html",+ notePath: ["root", "child", "leaf"]+ };++ const result = provider.prepareContent("A <b> & \"Title\"", "<p>Body</p>", noteMeta) as string;++ // notePath length 3 -> two "../" segments before style.css.+ expect(result).toContain('<link rel="stylesheet" href="../../style.css">');+ // Title is HTML-escaped in both the <title> and <h1>.+ expect(result).toContain("A <b> & "Title"");+ expect(result).not.toContain("<b> &");+ expect(result).toContain('<base target="_parent">');+ // Content is pretty-printed, so the body markup is preserved (line layout may differ).+ expect(result).toContain('<div class="ck-content">');+ expect(result).toContain("<p>Body</p>");+ expect(result).toContain('<h1 data-trilium-h1>');+ // rewriteFn is applied to the final content.+ expect(rewriteFn).toHaveBeenCalledTimes(1);+ expect(rewriteFn.mock.calls[0][1]).toBe(noteMeta);+ });++ it("uses a bare style.css path for a top-level note (notePath length 1)", () => {+ const { provider } = buildProvider();+ const result = provider.prepareContent("T", "<p>x</p>", {+ format: "html",+ notePath: ["root"]+ }) as string;++ expect(result).toContain('<link rel="stylesheet" href="style.css">');+ expect(result).not.toContain("../style.css");+ });++ it("throws when notePath is missing for a templated HTML note", () => {+ const { provider } = buildProvider();++ expect(() => provider.prepareContent("T", "<p>x</p>", { format: "html" }))+ .toThrow("Missing note path.");+ expect(() => provider.prepareContent("T", "<p>x</p>", { format: "html", notePath: [] }))+ .toThrow("Missing note path.");+ });++ it("does not wrap content that already contains an <html> tag", () => {+ const rewriteFn = vi.fn((content: string) => content);+ const { provider } = buildProvider({ rewriteFn });+ const original = "<html><body>already wrapped</body></html>";++ const result = provider.prepareContent("T", original, {+ format: "html",+ notePath: ["root"]+ }) as string;++ // No injected template title/base element.+ expect(result).not.toContain('<base target="_parent">');+ expect(result).toContain("already wrapped");+ expect(rewriteFn).toHaveBeenCalledTimes(1);+ });++ it("does not wrap content when skipHtmlTemplate is set, but still rewrites", () => {+ const rewriteFn = vi.fn((content: string) => `${content}<!--rw-->`);+ const { provider } = buildProvider({+ zipExportOptions: { skipHtmlTemplate: true },+ rewriteFn+ });++ const result = provider.prepareContent("T", "<p>plain</p>", {+ format: "html",+ // notePath is not required when skipping the template.+ }) as string;++ expect(result).not.toContain('<base target="_parent">');+ expect(result).toContain("<p>plain</p>");+ expect(result).toContain("<!--rw-->");+ });++ it("returns non-HTML content unchanged without invoking rewriteFn", () => {+ const rewriteFn = vi.fn((content: string) => content);+ const { provider } = buildProvider({ rewriteFn });++ const markdown = "# Heading";+ expect(provider.prepareContent("T", markdown, { format: "markdown" })).toBe(markdown);++ const binary = new Uint8Array([1, 2, 3]);+ expect(provider.prepareContent("T", binary, { format: "html" })).toBe(binary);++ expect(rewriteFn).not.toHaveBeenCalled();+ });++ it("does not pretty-print very large content but still wraps and rewrites it", () => {+ const rewriteFn = vi.fn((content: string) => content);+ const { provider } = buildProvider({ rewriteFn });+ const big = "<p>x</p>".repeat(20000); // well over the 100k pretty-print threshold++ const result = provider.prepareContent("T", big, {+ format: "html",+ notePath: ["root"]+ }) as string;++ expect(result).toContain('<base target="_parent">');+ expect(result.length).toBeGreaterThan(100_000);+ expect(rewriteFn).toHaveBeenCalledTimes(1);+ });+ });++ describe("afterDone", () => {+ function buildRootMeta(): NoteMeta {+ return {+ noteId: "root",+ title: "Root",+ dataFileName: "Root.html",+ children: [+ {+ noteId: "child1",+ title: "Child <One>",+ prefix: "P",+ dataFileName: "Child.html",+ children: []+ },+ {+ // No dataFileName/noteId -> rendered as plain (escaped) text.+ title: "Folder",+ children: []+ }+ ]+ };+ }++ it("appends navigation, index and css with rendered content", () => {+ const { provider, appendCalls } = buildProvider({+ getNoteTargetUrl: (noteId) => `notes/${noteId}.html`,+ options: { contentCss: "body { color: red; }" }+ });+ provider.prepareMeta(buildMetaFile());++ provider.afterDone(buildRootMeta());++ const byName = Object.fromEntries(+ appendCalls.map((c) => [c.name, c.content as string])+ );+ expect(Object.keys(byName).sort()).toEqual(["index.html", "navigation.html", "style.css"]);++ // Navigation links every note with a dataFileName + noteId, escapes titles & prefixes.+ expect(byName["navigation.html"]).toContain('href="notes/root.html"');+ expect(byName["navigation.html"]).toContain('href="notes/child1.html"');+ expect(byName["navigation.html"]).toContain("P - Child <One>");+ expect(byName["navigation.html"]).toContain("Folder");++ // Index frameset points at the first non-empty note's target URL.+ expect(byName["index.html"]).toContain("<frameset");+ expect(byName["index.html"]).toContain('src="notes/root.html"');++ // CSS is taken verbatim from options.contentCss.+ expect(byName["style.css"]).toBe("body { color: red; }");+ });++ it("omits the css file when no contentCss is provided", () => {+ const { provider, appendCalls } = buildProvider();+ provider.prepareMeta(buildMetaFile());++ provider.afterDone(buildRootMeta());++ expect(appendCalls.map((c) => c.name).sort()).toEqual(["index.html", "navigation.html"]);+ });++ it("throws when meta was never prepared", () => {+ const { provider } = buildProvider();++ expect(() => provider.afterDone(buildRootMeta())).toThrow("Missing meta.");+ });++ it("does nothing when skipExtraFiles is set", () => {+ const { provider, appendCalls } = buildProvider({+ zipExportOptions: { skipExtraFiles: true }+ });+ provider.prepareMeta(buildMetaFile());++ provider.afterDone(buildRootMeta());++ expect(appendCalls).toHaveLength(0);+ });+ });+});diff --git a/packages/trilium-core/src/services/export/zip/markdown.spec.ts b/packages/trilium-core/src/services/export/zip/markdown.spec.tsnew file mode 100644index 0000000000..c467b1cd73--- /dev/null+++ b/packages/trilium-core/src/services/export/zip/markdown.spec.ts@@ -0,0 +1,124 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++import type { NoteMeta, NoteMetaFile } from "../../../meta.js";+import type { ZipArchive } from "../../zip_provider.js";+import type { ZipExportProviderData } from "./abstract_provider.js";+import MarkdownExportProvider from "./markdown.js";++function buildArchive(): ZipArchive {+ return {+ append: vi.fn(),+ pipe: vi.fn(),+ finalize: vi.fn()+ };+}++function buildProvider(+ overrides: {+ rewriteFn?: ZipExportProviderData["rewriteFn"];+ } = {}+) {+ const data: ZipExportProviderData = {+ // The provider never touches the branch in this module.+ branch: {} as ZipExportProviderData["branch"],+ getNoteTargetUrl: (targetNoteId) => `${targetNoteId}.md`,+ archive: buildArchive(),+ zipExportOptions: undefined,+ rewriteFn: overrides.rewriteFn ?? ((content) => content)+ };+ return new MarkdownExportProvider(data);+}++describe("MarkdownExportProvider", () => {+ beforeEach(() => {+ vi.restoreAllMocks();+ });++ describe("prepareContent", () => {+ it("rewrites, converts HTML to markdown and prepends a title heading", () => {+ const rewriteFn = vi.fn((content: string, _noteMeta: NoteMeta) => content);+ const provider = buildProvider({ rewriteFn });+ const noteMeta: NoteMeta = { format: "markdown" };++ const result = provider.prepareContent("My Note", "<p>Hello <b>world</b></p>", noteMeta) as string;++ // rewriteFn is applied once with the original note meta.+ expect(rewriteFn).toHaveBeenCalledTimes(1);+ expect(rewriteFn.mock.calls[0][1]).toBe(noteMeta);+ // HTML was turned into markdown (bold becomes **world**) and the title heading prepended.+ expect(result.startsWith("# My Note\r\n")).toBe(true);+ expect(result).toContain("Hello **world**");+ expect(result).not.toContain("<p>");+ });++ it("does not prepend a title when the converted content already starts with a heading", () => {+ const provider = buildProvider();++ const result = provider.prepareContent("Ignored", "<h1>Existing Heading</h1>", {+ format: "markdown"+ }) as string;++ // toMarkdown renders the h1 as "# Existing Heading"; no extra "# Ignored" prefix.+ expect(result).toBe("# Existing Heading");+ expect(result.startsWith("# Ignored")).toBe(false);+ });++ it("does not prepend a title when the converted content is blank", () => {+ const provider = buildProvider();++ // Empty / whitespace-only HTML converts to an empty (trimmed) string.+ const result = provider.prepareContent("Empty", " ", { format: "markdown" }) as string;++ expect(result.includes("# Empty")).toBe(false);+ expect(result.trim().length).toBe(0);+ });++ it("returns non-markdown string content unchanged without rewriting or converting", () => {+ const rewriteFn = vi.fn((content: string) => content);+ const provider = buildProvider({ rewriteFn });++ const html = "<p>untouched</p>";+ expect(provider.prepareContent("T", html, { format: "html" })).toBe(html);+ expect(provider.prepareContent("T", html, {})).toBe(html);++ expect(rewriteFn).not.toHaveBeenCalled();+ });++ it("returns binary content unchanged even when the format is markdown", () => {+ const rewriteFn = vi.fn((content: string) => content);+ const provider = buildProvider({ rewriteFn });+ const binary = new Uint8Array([1, 2, 3]);++ expect(provider.prepareContent("T", binary, { format: "markdown" })).toBe(binary);+ expect(rewriteFn).not.toHaveBeenCalled();+ });++ it("applies the link rewrite before the markdown conversion", () => {+ // rewriteFn receives the raw HTML, so it can inject markup that toMarkdown then converts.+ const rewriteFn = vi.fn((_content: string) => "<p><em>rewritten</em></p>");+ const provider = buildProvider({ rewriteFn });++ const result = provider.prepareContent("Title", "<p>original</p>", {+ format: "markdown"+ }) as string;++ expect(result).toContain("_rewritten_");+ expect(result).not.toContain("original");+ expect(result.startsWith("# Title")).toBe(true);+ });+ });++ describe("prepareMeta / afterDone", () => {+ it("are inert and never touch the archive or meta", () => {+ const provider = buildProvider();+ const metaFile: NoteMetaFile = { formatVersion: 1, appVersion: "1.0.0", files: [] };+ const rootMeta: NoteMeta = { noteId: "root", title: "Root", children: [] };++ expect(() => provider.prepareMeta(metaFile)).not.toThrow();+ expect(() => provider.afterDone(rootMeta)).not.toThrow();++ expect(metaFile.files).toHaveLength(0);+ expect(provider.archive.append).not.toHaveBeenCalled();+ });+ });+});diff --git a/packages/trilium-core/src/services/export/zip_export_provider_factory.spec.ts b/packages/trilium-core/src/services/export/zip_export_provider_factory.spec.tsnew file mode 100644index 0000000000..53cb8ffcdf--- /dev/null+++ b/packages/trilium-core/src/services/export/zip_export_provider_factory.spec.ts@@ -0,0 +1,68 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++import type { ZipExportProvider, ZipExportProviderData } from "./zip/abstract_provider.js";+import type { ZipExportProviderFactory } from "./zip_export_provider_factory.js";++/**+ * The module keeps the registered factory in module-level state, so each test+ * re-imports it through a reset module registry to get a clean, uninitialized+ * starting point.+ */+async function freshModule() {+ vi.resetModules();+ return import("./zip_export_provider_factory.js");+}++describe("zip export provider factory", () => {+ beforeEach(() => {+ vi.resetModules();+ });++ it("throws a descriptive error when no factory has been registered", async () => {+ const { getZipExportProviderFactory } = await freshModule();++ expect(() => getZipExportProviderFactory()).toThrowError("ZipExportProviderFactory not initialized.");+ });++ it("returns the exact factory registered via initZipExportProviderFactory", async () => {+ const { initZipExportProviderFactory, getZipExportProviderFactory } = await freshModule();++ const provider = {} as ZipExportProvider;+ const factory: ZipExportProviderFactory = vi.fn(async () => provider);++ initZipExportProviderFactory(factory);++ const retrieved = getZipExportProviderFactory();+ expect(retrieved).toBe(factory);++ // The retrieved factory is the live function: invoking it forwards the+ // arguments and resolves to whatever the registered factory returns.+ const data = {} as ZipExportProviderData;+ await expect(retrieved("html", data)).resolves.toBe(provider);+ expect(factory).toHaveBeenCalledWith("html", data);+ });++ it("overwrites a previously registered factory on re-initialization", async () => {+ const { initZipExportProviderFactory, getZipExportProviderFactory } = await freshModule();++ const first: ZipExportProviderFactory = vi.fn(async () => ({}) as ZipExportProvider);+ const second: ZipExportProviderFactory = vi.fn(async () => ({}) as ZipExportProvider);++ initZipExportProviderFactory(first);+ initZipExportProviderFactory(second);++ expect(getZipExportProviderFactory()).toBe(second);+ });++ it("isolates state between module instances so a reset clears the factory", async () => {+ const initialized = await freshModule();+ initialized.initZipExportProviderFactory(vi.fn(async () => ({}) as ZipExportProvider));+ expect(initialized.getZipExportProviderFactory()).toBeDefined();++ // A fresh module registry must start uninitialized again.+ const reloaded = await freshModule();+ expect(() => reloaded.getZipExportProviderFactory()).toThrowError(+ "ZipExportProviderFactory not initialized."+ );+ });+});diff --git a/packages/trilium-core/src/services/hidden_subtree.spec.ts b/packages/trilium-core/src/services/hidden_subtree.spec.tsnew file mode 100644index 0000000000..927b6b0976--- /dev/null+++ b/packages/trilium-core/src/services/hidden_subtree.spec.ts@@ -0,0 +1,222 @@+import { beforeAll, describe, expect, it } from "vitest";++import becca from "../becca/becca.js";+import type BNote from "../becca/entities/bnote.js";+import { getContext } from "./context.js";+import hiddenSubtreeService, {+ LBTPL_BASE,+ LBTPL_COMMAND,+ LBTPL_CUSTOM_WIDGET,+ LBTPL_NOTE_LAUNCHER,+ LBTPL_ROOT,+ LBTPL_SCRIPT,+ LBTPL_SPACER,+ LBTPL_WIDGET+} from "./hidden_subtree.js";++/**+ * Entity mutations performed by checkHiddenSubtree (createNewNote, save,+ * markAsDeleted) require an initialised CLS context.+ */+function withContext<T>(fn: () => T): T {+ return getContext().init(fn);+}++function checkHiddenSubtree(force = false) {+ return withContext(() => hiddenSubtreeService.checkHiddenSubtree(force));+}++describe("hidden_subtree (real DB)", () => {+ beforeAll(() => {+ // Materialise the full hidden subtree in the shared in-memory fixture DB.+ checkHiddenSubtree();+ });++ describe("checkHiddenSubtree structure", () => {+ it("creates the hidden root and its top-level containers under the expected parents", () => {+ const hidden = becca.notes["_hidden"];+ expect(hidden).toBeDefined();+ expect(hidden.type).toBe("doc");+ // The hidden root must be parented directly under the tree root.+ expect(hidden.getParentBranches().some((b) => b.parentNoteId === "root")).toBe(true);++ // A representative set of the declared children must exist and sit+ // directly under _hidden.+ for (const childId of ["_search", "_options", "_help", "_taskStates", "_lbRoot"]) {+ const child = becca.notes[childId];+ expect(child, `${childId} should exist`).toBeDefined();+ expect(+ child.getParentBranches().some((b) => b.parentNoteId === "_hidden"),+ `${childId} should be parented under _hidden`+ ).toBe(true);+ }++ // Nested children are placed under their declared parent, not the root.+ const taskStateNone = becca.notes["_taskStateNone"];+ expect(taskStateNone).toBeDefined();+ expect(taskStateNone.getParentBranches().some((b) => b.parentNoteId === "_taskStates")).toBe(true);+ });++ it("derives an iconClass label from the item icon", () => {+ // _sqlConsole declares icon "bx-data"; the recursion turns the icon+ // into an iconClass label prefixed with "bx ".+ const sqlConsole = becca.notes["_sqlConsole"];+ expect(sqlConsole).toBeDefined();+ const iconClass = sqlConsole.getOwnedLabelValue("iconClass");+ expect(iconClass).toBeTruthy();+ expect(iconClass!.startsWith("bx ")).toBe(true);+ expect(iconClass).toContain("bx-data");+ });++ it("applies declared labels and relations, materialising launcher templates", () => {+ // The note launcher template carries a declared launcherType label.+ const noteLauncher = becca.notes[LBTPL_NOTE_LAUNCHER];+ expect(noteLauncher).toBeDefined();+ expect(noteLauncher.getOwnedLabelValue("launcherType")).toBe("note");++ // The command launcher template likewise advertises its launcherType.+ const commandLauncher = becca.notes[LBTPL_COMMAND];+ expect(commandLauncher).toBeDefined();+ expect(commandLauncher.getOwnedLabelValue("launcherType")).toBe("command");++ // Every declared launchbar template note exists under the template root.+ const templateRoot = becca.notes[LBTPL_ROOT];+ expect(templateRoot).toBeDefined();+ for (const tplId of [+ LBTPL_BASE,+ LBTPL_COMMAND,+ LBTPL_NOTE_LAUNCHER,+ LBTPL_SCRIPT,+ LBTPL_WIDGET,+ LBTPL_SPACER,+ LBTPL_CUSTOM_WIDGET+ ]) {+ const tpl = becca.notes[tplId];+ expect(tpl, `${tplId} should exist`).toBeDefined();+ expect(tpl.getParentBranches().some((b) => b.parentNoteId === LBTPL_ROOT)).toBe(true);+ }+ });+ });++ describe("enforceAttributes", () => {+ it("removes attributes that are not part of the definition on an enforced note", () => {+ const hidden = becca.notes["_hidden"];+ expect(hidden).toBeDefined();++ // Sanity: the declared docName label survives enforcement.+ expect(hidden.getOwnedLabelValue("docName")).toBe("hidden");++ // Inject a stray owned label, then re-run the integrity check.+ withContext(() => {+ hidden.addLabel("strayLabelXyz", "should-be-removed");+ });+ expect(hidden.hasOwnedLabel("strayLabelXyz")).toBe(true);++ checkHiddenSubtree();++ // _hidden has enforceAttributes: true, so the undefined label is purged+ // while the declared docName label is preserved.+ expect(hidden.hasOwnedLabel("strayLabelXyz")).toBe(false);+ expect(hidden.getOwnedLabelValue("docName")).toBe("hidden");+ });++ it("repairs a modified value on an enforced attribute", () => {+ const hidden = becca.notes["_hidden"];+ const docNameAttr = hidden.getOwnedAttributes("label", "docName")[0];+ expect(docNameAttr).toBeDefined();++ withContext(() => {+ docNameAttr.value = "tampered";+ docNameAttr.save();+ });+ expect(hidden.getOwnedLabelValue("docName")).toBe("tampered");++ checkHiddenSubtree();++ expect(hidden.getOwnedLabelValue("docName")).toBe("hidden");+ });+ });++ describe("enforceDeleted", () => {+ it("removes deprecated notes marked enforceDeleted", () => {+ // _optionsImages and _optionsAi are declared with enforceDeleted: true,+ // so they must never survive an integrity check.+ for (const deprecatedId of ["_optionsImages", "_optionsAi"]) {+ const note = becca.notes[deprecatedId] as BNote | undefined;+ expect(note, `${deprecatedId} should have been deleted`).toBeUndefined();+ }+ });++ it("re-deletes a deprecated note if it reappears", () => {+ const deprecatedId = "_optionsImages";+ expect(becca.notes[deprecatedId]).toBeUndefined();++ // The recursion still visits the deprecated entry and calls deleteNote+ // even on a fresh run, so a second check stays stable.+ checkHiddenSubtree();+ expect(becca.notes[deprecatedId]).toBeUndefined();+ });+ });++ describe("type and idempotency", () => {+ it("restores a note type that was changed away from the definition", () => {+ const options = becca.notes["_options"];+ expect(options).toBeDefined();+ // Declared as a book.+ expect(options.type).toBe("book");++ withContext(() => {+ options.type = "text";+ options.save();+ });+ expect(becca.notes["_options"].type).toBe("text");++ checkHiddenSubtree();++ expect(becca.notes["_options"].type).toBe("book");+ });++ it("is idempotent: a repeated forced check does not duplicate branches", () => {+ const searchNote = becca.notes["_search"];+ expect(searchNote).toBeDefined();++ const beforeParents = searchNote+ .getParentBranches()+ .filter((b) => !b.isDeleted)+ .map((b) => b.parentNoteId)+ .sort();++ checkHiddenSubtree(true);+ checkHiddenSubtree(true);++ const afterParents = becca.notes["_search"]+ .getParentBranches()+ .filter((b) => !b.isDeleted)+ .map((b) => b.parentNoteId)+ .sort();++ expect(afterParents).toEqual(beforeParents);+ expect(afterParents).toContain("_hidden");+ });+ });++ describe("exported launchbar template constants", () => {+ it("all exported ids follow the hidden-note underscore convention and are unique", () => {+ const ids = [+ LBTPL_ROOT,+ LBTPL_BASE,+ LBTPL_NOTE_LAUNCHER,+ LBTPL_WIDGET,+ LBTPL_COMMAND,+ LBTPL_SCRIPT,+ LBTPL_SPACER,+ LBTPL_CUSTOM_WIDGET+ ];++ for (const id of ids) {+ expect(id.startsWith("_")).toBe(true);+ }+ expect(new Set(ids).size).toBe(ids.length);+ });+ });+});diff --git a/packages/trilium-core/src/services/hidden_subtree_launcherbar.spec.ts b/packages/trilium-core/src/services/hidden_subtree_launcherbar.spec.tsnew file mode 100644index 0000000000..09dab9250d--- /dev/null+++ b/packages/trilium-core/src/services/hidden_subtree_launcherbar.spec.ts@@ -0,0 +1,190 @@+import type { HiddenSubtreeItem } from "@triliumnext/commons";+import { describe, expect, it } from "vitest";++import buildLaunchBarConfig from "./hidden_subtree_launcherbar.js";++function byId(items: HiddenSubtreeItem[], id: string): HiddenSubtreeItem {+ const item = items.find((i) => i.id === id);+ expect(item, `expected launcher ${id} to exist`).toBeDefined();+ return item!;+}++function labelValue(item: HiddenSubtreeItem, name: string): string | undefined {+ return item.attributes?.find((a) => a.type === "label" && a.name === name)?.value;+}++describe("buildLaunchBarConfig", () => {+ it("returns the four launcher groups, each non-empty and typed as launchers", () => {+ const config = buildLaunchBarConfig();++ const groups = [+ config.desktopAvailableLaunchers,+ config.desktopVisibleLaunchers,+ config.mobileAvailableLaunchers,+ config.mobileVisibleLaunchers+ ];++ for (const group of groups) {+ expect(Array.isArray(group)).toBe(true);+ expect(group.length).toBeGreaterThan(0);+ for (const launcher of group) {+ expect(launcher.type, launcher.id).toBe("launcher");+ expect(launcher.id, "every launcher has an id").toBeTruthy();+ expect(launcher.id.startsWith("_"), `${launcher.id} is a hidden-subtree id`).toBe(true);+ // Every launcher carries a title produced by the translation function.+ expect(typeof launcher.title, launcher.id).toBe("string");+ }+ }+ });++ it("assigns unique ids within each group", () => {+ const config = buildLaunchBarConfig();++ for (const group of [+ config.desktopAvailableLaunchers,+ config.desktopVisibleLaunchers,+ config.mobileAvailableLaunchers,+ config.mobileVisibleLaunchers+ ]) {+ const ids = group.map((l) => l.id);+ expect(new Set(ids).size, ids.join(",")).toBe(ids.length);+ }+ });++ it("exposes the expected desktop visible launcher ids in order", () => {+ const { desktopVisibleLaunchers } = buildLaunchBarConfig();++ expect(desktopVisibleLaunchers.map((l) => l.id)).toEqual([+ "_lbNewNote",+ "_lbSearch",+ "_lbJumpTo",+ "_lbNoteMap",+ "_lbLlmChat",+ "_lbCalendar",+ "_lbRecentChanges",+ "_lbSpacer1",+ "_lbBookmarks",+ "_lbToday",+ "_lbSpacer2",+ "_lbQuickSearch",+ "_lbProtectedSession",+ "_lbSyncStatus",+ "_lbSettings"+ ]);+ });++ it("exposes the expected mobile launcher ids", () => {+ const { mobileAvailableLaunchers, mobileVisibleLaunchers } = buildLaunchBarConfig();++ expect(mobileAvailableLaunchers.map((l) => l.id)).toEqual([+ "_lbMobileNewNote",+ "_lbMobileSearchNotes",+ "_lbMobileToday",+ "_lbMobileRecentChanges",+ "_lbMobileBookmarks",+ "_lbMobileSyncStatus"+ ]);+ expect(mobileVisibleLaunchers.map((l) => l.id)).toEqual([+ "_lbMobileBackInHistory",+ "_lbMobileForwardInHistory",+ "_lbMobileJumpTo",+ "_lbMobileCalendar",+ "_lbMobileTabSwitcher"+ ]);+ });++ it("wires command-driven launchers to their commands", () => {+ const config = buildLaunchBarConfig();++ expect(byId(config.desktopVisibleLaunchers, "_lbNewNote").command).toBe("createNoteIntoInbox");+ expect(byId(config.desktopVisibleLaunchers, "_lbSearch").command).toBe("searchNotes");+ expect(byId(config.desktopVisibleLaunchers, "_lbJumpTo").command).toBe("jumpToNote");+ expect(byId(config.desktopVisibleLaunchers, "_lbRecentChanges").command).toBe("showRecentChanges");+ expect(byId(config.desktopVisibleLaunchers, "_lbSettings").command).toBe("showOptions");+ expect(byId(config.desktopAvailableLaunchers, "_commandPalette").command).toBe("commandPalette");+ expect(byId(config.desktopAvailableLaunchers, "_zenMode").command).toBe("toggleZenMode");+ });++ it("wires builtin-widget launchers to their widgets", () => {+ const config = buildLaunchBarConfig();++ expect(byId(config.desktopVisibleLaunchers, "_lbCalendar").builtinWidget).toBe("calendar");+ expect(byId(config.desktopVisibleLaunchers, "_lbBookmarks").builtinWidget).toBe("bookmarks");+ expect(byId(config.desktopVisibleLaunchers, "_lbToday").builtinWidget).toBe("todayInJournal");+ expect(byId(config.desktopVisibleLaunchers, "_lbSyncStatus").builtinWidget).toBe("syncStatus");+ expect(byId(config.desktopVisibleLaunchers, "_lbQuickSearch").builtinWidget).toBe("quickSearch");+ expect(byId(config.desktopVisibleLaunchers, "_lbProtectedSession").builtinWidget).toBe("protectedSession");+ expect(byId(config.desktopAvailableLaunchers, "_lbSidebarChat").builtinWidget).toBe("sidebarChat");+ expect(byId(config.desktopAvailableLaunchers, "_lbBackInHistory").builtinWidget).toBe("backInHistoryButton");+ expect(byId(config.desktopAvailableLaunchers, "_lbForwardInHistory").builtinWidget).toBe("forwardInHistoryButton");+ });++ it("points target-note launchers at the right hidden notes", () => {+ const config = buildLaunchBarConfig();++ expect(byId(config.desktopAvailableLaunchers, "_lbBackendLog").targetNoteId).toBe("_backendLog");+ expect(byId(config.desktopVisibleLaunchers, "_lbNoteMap").targetNoteId).toBe("_globalNoteMap");+ });++ it("configures both spacers with distinct sizing", () => {+ const { desktopVisibleLaunchers } = buildLaunchBarConfig();++ const spacer1 = byId(desktopVisibleLaunchers, "_lbSpacer1");+ const spacer2 = byId(desktopVisibleLaunchers, "_lbSpacer2");++ expect(spacer1.builtinWidget).toBe("spacer");+ expect(spacer2.builtinWidget).toBe("spacer");+ expect(spacer1.baseSize).toBe("50");+ expect(spacer1.growthFactor).toBe("0");+ expect(spacer2.baseSize).toBe("0");+ expect(spacer2.growthFactor).toBe("1");+ });++ it("flags the deprecated LLM chat launcher as enforceDeleted with no widget", () => {+ const llmChat = byId(buildLaunchBarConfig().desktopVisibleLaunchers, "_lbLlmChat");++ expect(llmChat.enforceDeleted).toBe(true);+ expect(llmChat.command).toBeUndefined();+ expect(llmChat.builtinWidget).toBeUndefined();+ expect(llmChat.targetNoteId).toBeUndefined();+ });++ it("carries the docName / desktopOnly labels on the launchers that need them", () => {+ const config = buildLaunchBarConfig();++ expect(labelValue(byId(config.desktopAvailableLaunchers, "_lbBackInHistory"), "docName"))+ .toBe("launchbar_history_navigation");+ expect(labelValue(byId(config.desktopAvailableLaunchers, "_lbForwardInHistory"), "docName"))+ .toBe("launchbar_history_navigation");+ expect(labelValue(byId(config.desktopVisibleLaunchers, "_lbQuickSearch"), "docName"))+ .toBe("launchbar_quick_search");++ const jumpTo = byId(config.desktopVisibleLaunchers, "_lbJumpTo");+ expect(jumpTo.attributes?.some((a) => a.type === "label" && a.name === "desktopOnly")).toBe(true);+ });++ it("reuses the shared launcher definitions across desktop and mobile entries", () => {+ const config = buildLaunchBarConfig();++ const desktopNewNote = byId(config.desktopVisibleLaunchers, "_lbNewNote");+ const mobileNewNote = byId(config.mobileAvailableLaunchers, "_lbMobileNewNote");+ // Same shared definition (command + widget + icon), only the id differs.+ expect(mobileNewNote.command).toBe(desktopNewNote.command);+ expect(mobileNewNote.builtinWidget).toBe(desktopNewNote.builtinWidget);+ expect(mobileNewNote.icon).toBe(desktopNewNote.icon);++ const desktopSync = byId(config.desktopVisibleLaunchers, "_lbSyncStatus");+ const mobileSync = byId(config.mobileAvailableLaunchers, "_lbMobileSyncStatus");+ expect(mobileSync.builtinWidget).toBe(desktopSync.builtinWidget);+ });++ it("returns a fresh independent structure on each invocation", () => {+ const first = buildLaunchBarConfig();+ const second = buildLaunchBarConfig();++ expect(first).not.toBe(second);+ expect(first.desktopVisibleLaunchers).not.toBe(second.desktopVisibleLaunchers);+ expect(first.desktopVisibleLaunchers.map((l) => l.id))+ .toEqual(second.desktopVisibleLaunchers.map((l) => l.id));+ });+});diff --git a/packages/trilium-core/src/services/hidden_subtree_templates.spec.ts b/packages/trilium-core/src/services/hidden_subtree_templates.spec.tsnew file mode 100644index 0000000000..d3bd0720a1--- /dev/null+++ b/packages/trilium-core/src/services/hidden_subtree_templates.spec.ts@@ -0,0 +1,196 @@+import type { HiddenSubtreeItem } from "@triliumnext/commons";+import { describe, expect, it } from "vitest";++import buildHiddenSubtreeTemplates from "./hidden_subtree_templates.js";++function childById(root: HiddenSubtreeItem, id: string): HiddenSubtreeItem {+ const child = root.children?.find((c) => c.id === id);+ expect(child, `expected child ${id} to exist`).toBeDefined();+ return child!;+}++function viewTypeOf(item: HiddenSubtreeItem): string | undefined {+ return item.attributes?.find((a) => a.name === "viewType")?.value;+}++describe("buildHiddenSubtreeTemplates", () => {+ it("builds the _templates book root with enforced attributes", () => {+ const templates = buildHiddenSubtreeTemplates();++ expect(templates.id).toBe("_templates");+ expect(templates.type).toBe("book");+ expect(templates.enforceAttributes).toBe(true);+ expect(templates.children?.length).toBeGreaterThan(0);+ });++ it("marks every direct child template with enforceAttributes", () => {+ const templates = buildHiddenSubtreeTemplates();++ for (const child of templates.children ?? []) {+ expect(child.enforceAttributes, `child ${child.id}`).toBe(true);+ }+ });++ it("exposes the expected set of template ids exactly once", () => {+ const templates = buildHiddenSubtreeTemplates();+ const ids = (templates.children ?? []).map((c) => c.id);++ expect(ids).toEqual([+ "_template_text_snippet",+ "_template_list_view",+ "_template_grid_view",+ "_template_calendar",+ "_template_table",+ "_template_geo_map",+ "_template_board",+ "_template_presentation_slide",+ "_template_presentation"+ ]);+ // No duplicate ids.+ expect(new Set(ids).size).toBe(ids.length);+ });++ it("tags each collection template with its matching viewType label", () => {+ const templates = buildHiddenSubtreeTemplates();++ expect(viewTypeOf(childById(templates, "_template_list_view"))).toBe("list");+ expect(viewTypeOf(childById(templates, "_template_grid_view"))).toBe("grid");+ expect(viewTypeOf(childById(templates, "_template_calendar"))).toBe("calendar");+ expect(viewTypeOf(childById(templates, "_template_table"))).toBe("table");+ expect(viewTypeOf(childById(templates, "_template_geo_map"))).toBe("geoMap");+ expect(viewTypeOf(childById(templates, "_template_board"))).toBe("board");+ expect(viewTypeOf(childById(templates, "_template_presentation"))).toBe("presentation");+ });++ it("flags collection templates as templates and as collections", () => {+ const templates = buildHiddenSubtreeTemplates();+ const collectionIds = [+ "_template_list_view",+ "_template_grid_view",+ "_template_calendar",+ "_template_table",+ "_template_geo_map",+ "_template_board",+ "_template_presentation"+ ];++ for (const id of collectionIds) {+ const item = childById(templates, id);+ const names = (item.attributes ?? []).map((a) => a.name);+ expect(names, id).toContain("template");+ expect(names, id).toContain("collection");+ }+ });++ it("configures the text snippet template as a text note with promoted description", () => {+ const templates = buildHiddenSubtreeTemplates();+ const snippet = childById(templates, "_template_text_snippet");++ expect(snippet.type).toBe("text");+ const names = (snippet.attributes ?? []).map((a) => a.name);+ expect(names).toContain("template");+ expect(names).toContain("textSnippet");++ const descriptor = snippet.attributes?.find((a) => a.name === "label:textSnippetDescription");+ expect(descriptor?.type).toBe("label");+ expect(descriptor?.value).toContain("promoted");+ expect(descriptor?.value).toContain("single");+ expect(descriptor?.value).toContain("text");+ });++ it("applies the shared hidden-subtree label on the templates that hide their subtree", () => {+ const templates = buildHiddenSubtreeTemplates();+ const hidingIds = ["_template_calendar", "_template_table", "_template_geo_map", "_template_board"];++ for (const id of hidingIds) {+ const item = childById(templates, id);+ const attr = item.attributes?.find((a) => a.name === "subtreeHidden");+ expect(attr, id).toBeDefined();+ expect(attr?.type, id).toBe("label");+ expect(attr?.value, id).toBe("false");+ }++ // The list/grid views intentionally do NOT hide their subtree.+ for (const id of ["_template_list_view", "_template_grid_view"]) {+ const item = childById(templates, id);+ expect(item.attributes?.some((a) => a.name === "subtreeHidden"), id).toBe(false);+ }+ });++ it("declares the calendar's inheritable promoted date/time attributes", () => {+ const templates = buildHiddenSubtreeTemplates();+ const calendar = childById(templates, "_template_calendar");++ for (const name of ["label:startDate", "label:endDate", "label:startTime", "label:endTime"]) {+ const attr = calendar.attributes?.find((a) => a.name === name);+ expect(attr, name).toBeDefined();+ expect(attr?.isInheritable, name).toBe(true);+ expect(attr?.value, name).toContain("promoted");+ }+ });++ it("builds the board template with three seeded child notes carrying status labels", () => {+ const templates = buildHiddenSubtreeTemplates();+ const board = childById(templates, "_template_board");++ const statusDefinition = board.attributes?.find((a) => a.name === "label:status");+ expect(statusDefinition?.isInheritable).toBe(true);++ const childIds = (board.children ?? []).map((c) => c.id);+ expect(childIds).toEqual([+ "_template_board_first",+ "_template_board_second",+ "_template_board_third"+ ]);++ for (const child of board.children ?? []) {+ expect(child.type).toBe("text");+ const statusLabel = child.attributes?.find((a) => a.name === "status");+ expect(statusLabel?.type, child.id).toBe("label");+ expect(statusLabel?.value, child.id).toBeTruthy();+ }+ });++ it("wires the presentation template to its slide template via a child:template relation", () => {+ const templates = buildHiddenSubtreeTemplates();+ const presentation = childById(templates, "_template_presentation");++ const childTemplate = presentation.attributes?.find((a) => a.name === "child:template");+ expect(childTemplate?.type).toBe("relation");+ expect(childTemplate?.value).toBe("_template_presentation_slide");++ const slideChildIds = (presentation.children ?? []).map((c) => c.id);+ expect(slideChildIds).toEqual([+ "_template_presentation_first",+ "_template_presentation_second"+ ]);++ for (const slide of presentation.children ?? []) {+ expect(slide.type).toBe("text");+ const templateRelation = slide.attributes?.find((a) => a.name === "template");+ expect(templateRelation?.type, slide.id).toBe("relation");+ expect(templateRelation?.value, slide.id).toBe("_template_presentation_slide");+ }+ });++ it("exposes the presentation slide template with a promoted background color attribute", () => {+ const templates = buildHiddenSubtreeTemplates();+ const slide = childById(templates, "_template_presentation_slide");++ expect(slide.type).toBe("text");+ expect(slide.attributes?.some((a) => a.name === "slide")).toBe(true);++ const background = slide.attributes?.find((a) => a.name === "label:slide:background");+ expect(background?.type).toBe("label");+ expect(background?.value).toContain("color");+ });++ it("returns a fresh independent structure on each invocation", () => {+ const first = buildHiddenSubtreeTemplates();+ const second = buildHiddenSubtreeTemplates();++ expect(first).not.toBe(second);+ expect(first.children).not.toBe(second.children);+ expect(first.children?.length).toBe(second.children?.length);+ });+});diff --git a/packages/trilium-core/src/services/hoisted_note.spec.ts b/packages/trilium-core/src/services/hoisted_note.spec.tsnew file mode 100644index 0000000000..85ee85baaa--- /dev/null+++ b/packages/trilium-core/src/services/hoisted_note.spec.ts@@ -0,0 +1,119 @@+import { describe, expect, it } from "vitest";++import becca from "../becca/becca.js";+import type BNote from "../becca/entities/bnote.js";+import { getContext } from "./context.js";+import hoistedNoteService from "./hoisted_note.js";+import noteService from "./notes.js";++/**+ * The real `cls` `ExecutionContext` is installed by `initializeCore` (run once+ * in the server spec `setup.ts`). `getHoistedNoteId()` reads `hoistedNoteId`+ * from that context, defaulting to `"root"`. Each `init()` runs in a fresh+ * store, so the hoisted note id set inside one block is isolated from others.+ */+function withHoisted<T>(hoistedNoteId: string, fn: () => T): T {+ return getContext().init(() => {+ getContext().set("hoistedNoteId", hoistedNoteId);+ return fn();+ });+}++let counter = 0;++/** Creates a fresh text note under root in the real in-memory DB. */+function createNote(): BNote {+ counter++;+ return getContext().init(() =>+ noteService.createNewNote({+ parentNoteId: "root",+ title: `hoisted-note-spec-${counter}`,+ content: "<p>hello</p>",+ type: "text"+ }).note+ );+}++describe("hoisted_note service (real DB)", () => {+ describe("getHoistedNoteId", () => {+ it("defaults to 'root' and reflects an explicitly set value", () => {+ // No hoisted note set -> falls back to "root".+ getContext().init(() => {+ expect(hoistedNoteService.getHoistedNoteId()).toBe("root");+ });++ withHoisted("someNoteId", () => {+ expect(hoistedNoteService.getHoistedNoteId()).toBe("someNoteId");+ });+ });+ });++ describe("isHoistedInHiddenSubtree", () => {+ it("returns false when hoisted on root", () => {+ withHoisted("root", () => {+ expect(hoistedNoteService.isHoistedInHiddenSubtree()).toBe(false);+ });+ });++ it("returns true when hoisted directly on the _hidden subtree root", () => {+ withHoisted("_hidden", () => {+ expect(hoistedNoteService.isHoistedInHiddenSubtree()).toBe(true);+ });+ });++ it("reflects isHiddenCompletely() of a real hoisted note", () => {+ // A note cloned directly under root is NOT hidden completely.+ const visible = createNote();+ expect(visible.isHiddenCompletely()).toBe(false);++ withHoisted(visible.noteId, () => {+ expect(hoistedNoteService.isHoistedInHiddenSubtree()).toBe(false);+ });+ });++ it("throws when the hoisted note cannot be found in becca", () => {+ withHoisted("nonExistentNote123", () => {+ expect(() => hoistedNoteService.isHoistedInHiddenSubtree()).toThrow(+ /Cannot find hoisted note 'nonExistentNote123'/+ );+ });+ });+ });++ describe("getWorkspaceNote", () => {+ it("returns the root note when hoisted on root", () => {+ withHoisted("root", () => {+ const workspace = hoistedNoteService.getWorkspaceNote();+ expect(workspace).toBe(becca.getRoot());+ expect(workspace?.noteId).toBe("root");+ });+ });++ it("returns the hoisted note itself when it carries the 'workspace' label", () => {+ const note = createNote();+ getContext().init(() => note.addLabel("workspace"));++ withHoisted(note.noteId, () => {+ expect(hoistedNoteService.getWorkspaceNote()).toBe(note);+ });+ });++ it("falls back to the root note when the hoisted note is not a workspace", () => {+ // A plain note (no 'workspace' label, not root) is not itself a workspace.+ const note = createNote();+ expect(note.hasLabel("workspace")).toBe(false);++ withHoisted(note.noteId, () => {+ const workspace = hoistedNoteService.getWorkspaceNote();+ expect(workspace).toBe(becca.getRoot());+ expect(workspace?.noteId).toBe("root");+ });+ });++ it("falls back to the root note when the hoisted note does not exist", () => {+ withHoisted("nonExistentNote123", () => {+ expect(hoistedNoteService.getWorkspaceNote()).toBe(becca.getRoot());+ });+ });+ });+});diff --git a/packages/trilium-core/src/services/image.spec.ts b/packages/trilium-core/src/services/image.spec.tsnew file mode 100644index 0000000000..3de43c7e9a--- /dev/null+++ b/packages/trilium-core/src/services/image.spec.ts@@ -0,0 +1,239 @@+import { afterEach, describe, expect, it, vi } from "vitest";++import becca from "../becca/becca.js";+import type BNote from "../becca/entities/bnote.js";+import { getContext } from "./context.js";+import imageService from "./image.js";+import { getImageProvider } from "./image_provider.js";+import type { ProcessedImage } from "./image_provider.js";+import protectedSessionService from "./protected_session.js";++/**+ * `image.ts` runs against the real in-memory fixture DB booted by the server+ * spec setup. The image *processing* itself (compression / format detection)+ * is delegated to the platform `ImageProvider` and happens asynchronously in a+ * fire-and-forget `.then()`. To make those async branches deterministic we spy+ * on `getImageProvider().processImage` and resolve it with a controlled+ * `ProcessedImage`, then flush microtasks before asserting on the persisted+ * note / attachment.+ */++let counter = 0;++function withContext<T>(fn: () => T): T {+ return getContext().init(fn);+}++const fakeBuffer = new Uint8Array([0xde, 0xad, 0xbe, 0xef]);++/**+ * Replaces the provider's processImage with one that resolves to the given+ * processed image, so the async persistence branch runs deterministically.+ */+function stubProcessImage(format: { ext: string }, buffer: Uint8Array = fakeBuffer) {+ const processed: ProcessedImage = {+ buffer,+ format: { ext: format.ext, mime: `image/${format.ext}` }+ };+ return vi.spyOn(getImageProvider(), "processImage").mockResolvedValue(processed);+}++/** Allow the fire-and-forget `.then()` chain (two awaited ticks) to settle. */+async function flushAsync() {+ await Promise.resolve();+ await Promise.resolve();+ await new Promise((resolve) => setTimeout(resolve, 0));+}++/** `getContent()` returns a Node Buffer; compare the raw bytes regardless of wrapper. */+function bytesOf(content: string | Uint8Array): number[] {+ return Array.from(typeof content === "string" ? Buffer.from(content) : content);+}++describe("image service (real DB)", () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });++ describe("saveImage", () => {+ it("creates an image note under the parent and returns the upload metadata synchronously", () => {+ counter++;+ const originalName = `pic ${counter}.png`;+ const result = withContext(() =>+ imageService.saveImage("root", fakeBuffer, originalName, false)+ );++ expect(result.noteId).toBeTruthy();+ expect(result.fileName).toBe(originalName);+ // The URL embeds the (URL-encoded) sanitized file name.+ expect(result.url).toBe(+ `api/images/${result.noteId}/${encodeURIComponent(result.fileName)}`+ );++ const note = becca.getNote(result.noteId);+ expect(note).not.toBeNull();+ expect(note!.type).toBe("image");+ // The original (unsanitized-for-filename) name is recorded as a label.+ expect(note!.getOwnedLabelValue("originalFileName")).toBe(originalName);+ // It is placed under the requested parent.+ expect(note!.getParentNotes().some((p) => p.noteId === "root")).toBe(true);+ });++ it("trims an over-long file name to 'image' only when trimFilename is set", () => {+ const longName = "a".repeat(45) + ".png";++ const trimmed = withContext(() =>+ imageService.saveImage("root", fakeBuffer, longName, false, true)+ );+ expect(trimmed.fileName).toBe("image");+ expect(becca.getNote(trimmed.noteId)!.getOwnedLabelValue("originalFileName")).toBe("image");++ const untrimmed = withContext(() =>+ imageService.saveImage("root", fakeBuffer, longName, false, false)+ );+ expect(untrimmed.fileName).toBe(longName);+ });++ it("throws when the parent note does not exist", () => {+ expect(() =>+ withContext(() =>+ imageService.saveImage("missingParent123", fakeBuffer, "x.png", false)+ )+ ).toThrow("Unable to find parent note.");+ });++ it("persists the detected mime and content once the async processing resolves", async () => {+ stubProcessImage({ ext: "png" });+ counter++;++ const result = withContext(() =>+ imageService.saveImage("root", fakeBuffer, `async-${counter}.png`, true)+ );+ await flushAsync();++ const note = becca.getNote(result.noteId)!;+ expect(note.mime).toBe("image/png");+ expect(bytesOf(note.getContent())).toEqual(Array.from(fakeBuffer));+ });++ it("maps the svg extension to the svg+xml mime and appends the extension when missing", async () => {+ stubProcessImage({ ext: "svg" });+ counter++;+ const baseName = `nodotsvg${counter}`;++ const result = withContext(() =>+ imageService.saveImage("root", fakeBuffer, baseName, true)+ );+ await flushAsync();++ const note = becca.getNote(result.noteId)!;+ expect(note.mime).toBe("image/svg+xml");+ // The name had no extension, so the detected one is appended to the label and title.+ expect(note.getOwnedLabelValue("originalFileName")).toBe(`${baseName}.svg`);+ expect(note.title).toBe(`${baseName}.svg`);+ });+ });++ describe("saveImageToAttachment", () => {+ /** Reuse saveImage to obtain a real, persisted note to attach to. */+ function createTargetNote(): BNote {+ counter++;+ const { noteId } = withContext(() =>+ imageService.saveImage("root", fakeBuffer, `host-${counter}.png`, false)+ );+ return becca.getNote(noteId)!;+ }++ it("creates an image attachment on the note and returns its title synchronously", () => {+ const host = createTargetNote();++ const att = withContext(() =>+ imageService.saveImageToAttachment(host.noteId, fakeBuffer, "att.png", false)+ );++ expect(att.attachmentId).toBeTruthy();+ expect(att.title).toBe("att.png");++ const attachment = becca.getAttachment(att.attachmentId!);+ expect(attachment).not.toBeNull();+ expect(attachment!.role).toBe("image");+ expect(attachment!.ownerId).toBe(host.noteId);+ });++ it("throws when the owner note does not exist", () => {+ expect(() =>+ withContext(() =>+ imageService.saveImageToAttachment("missingNote123", fakeBuffer, "x.png", false)+ )+ ).toThrow();+ });++ it("updates the attachment mime/content and appends a missing extension asynchronously", async () => {+ const host = createTargetNote();+ stubProcessImage({ ext: "jpg" });++ const att = withContext(() =>+ imageService.saveImageToAttachment(host.noteId, fakeBuffer, "nodotattach", false)+ );+ await flushAsync();++ const attachment = becca.getAttachment(att.attachmentId!)!;+ expect(attachment.mime).toBe("image/jpg");+ expect(attachment.title).toBe("nodotattach.jpg");+ expect(bytesOf(attachment.getContent())).toEqual(Array.from(fakeBuffer));+ });+ });++ describe("updateImage", () => {+ it("throws when the note does not exist", () => {+ expect(() =>+ withContext(() =>+ imageService.updateImage("missingNote456", fakeBuffer, "x.png")+ )+ ).toThrow("Unable to find note.");+ });++ it("saves a revision, sets the originalFileName label, and updates mime/content on resolve", async () => {+ // The persisted content is the provider's *processed* output, so drive+ // it with a distinct buffer. Stub before creating so the note-creation's+ // own async branch also resolves to png and doesn't clobber the mime.+ const processedBuffer = new Uint8Array([1, 2, 3]);+ stubProcessImage({ ext: "png" }, processedBuffer);++ // Start from a freshly created image note we can mutate.+ counter++;+ const { noteId } = withContext(() =>+ imageService.saveImage("root", fakeBuffer, `update-${counter}.png`, false)+ );+ await flushAsync();++ const revisionSpy = vi.spyOn(becca.getNote(noteId)!, "saveRevision");++ withContext(() => imageService.updateImage(noteId, fakeBuffer, "renamed.png"));+ await flushAsync();++ const note = becca.getNote(noteId)!;+ expect(revisionSpy).toHaveBeenCalledTimes(1);+ expect(note.getOwnedLabelValue("originalFileName")).toBe("renamed.png");+ expect(note.mime).toBe("image/png");+ // Content is the processed buffer the provider returned, not the raw upload.+ expect(bytesOf(note.getContent())).toEqual(Array.from(processedBuffer));+ });+ });++ describe("protected note handling in saveImage", () => {+ it("creates a protected image note only when a protected session is available", () => {+ // Build a protected parent so the protection inheritance branch is taken.+ vi.spyOn(protectedSessionService, "isProtectedSessionAvailable").mockReturnValue(false);+ counter++;++ const result = withContext(() =>+ imageService.saveImage("root", fakeBuffer, `prot-${counter}.png`, false)+ );++ // Parent (root) is not protected and no session is available, so the+ // child must not be protected either.+ expect(becca.getNote(result.noteId)!.isProtected).toBe(false);+ });+ });+});diff --git a/packages/trilium-core/src/services/import/opml.spec.ts b/packages/trilium-core/src/services/import/opml.spec.tsnew file mode 100644index 0000000000..53e8706b8f--- /dev/null+++ b/packages/trilium-core/src/services/import/opml.spec.ts@@ -0,0 +1,183 @@+import { beforeAll, describe, expect, it } from "vitest";++import becca from "../../becca/becca.js";+import type BNote from "../../becca/entities/bnote.js";+import { getContext } from "../context.js";+import noteService from "../notes.js";+import sql_init from "../sql_init.js";+import TaskContext from "../task_context.js";+import { decodeUtf8 } from "../utils/binary.js";+import opml from "./opml.js";++/**+ * Wraps a callback in a CLS context. Entity mutations (createNewNote) require+ * CLS to be initialised. The callback may return a Promise, which is passed+ * straight through.+ */+function withContext<T>(fn: () => T): T {+ return getContext().init(fn);+}++let counter = 0;++/**+ * Creates a fresh parent note under root for an import so each `it()` works on+ * an isolated subtree of the shared fixture DB.+ */+function createParent(): BNote {+ counter++;+ return withContext(() =>+ noteService.createNewNote({+ parentNoteId: "root",+ title: `opml-spec-parent-${counter}`,+ content: "",+ type: "text"+ }).note+ );+}++function getTaskContext() {+ // "no-progress-reporting" suppresses the WebSocket broadcast in increaseProgressCount.+ return TaskContext.getInstance("no-progress-reporting", "importNotes", {});+}++function runImport(xml: string, parent: BNote) {+ return withContext(() => opml.importOpml(getTaskContext(), xml, parent));+}++describe("importOpml (real DB)", () => {+ beforeAll(async () => {+ sql_init.initializeDb();+ await sql_init.dbReady;+ });++ it("rejects unsupported OPML versions with a 400 tuple", async () => {+ const parent = createParent();+ const xml = `<?xml version="1.0"?>+ <opml version="9.9">+ <body>+ <outline title="Nope" text="Nope" />+ </body>+ </opml>`;++ const result = (await runImport(xml, parent)) as [number, string];++ expect(Array.isArray(result)).toBe(true);+ expect(result[0]).toBe(400);+ expect(result[1]).toContain("9.9");+ // Nothing should have been imported when the version is rejected.+ expect(parent.getChildNotes()).toHaveLength(0);+ });++ it("imports a v1.0 outline tree, wrapping text in <p> and nesting children", async () => {+ const parent = createParent();+ const xml = `<?xml version="1.0"?>+ <opml version="1.0">+ <body>+ <outline title="Parent" text="line one line two">+ <outline title="Child" text="child text" />+ </outline>+ </body>+ </opml>`;++ const returnNote = (await runImport(xml, parent)) as BNote;++ // The returned note is the first top-level outline.+ expect(returnNote.title).toBe("Parent");+ expect(becca.notes[returnNote.noteId]).toBe(returnNote);++ // v1 derives content from `text`, joining newlines into separate <p> blocks.+ expect(decodeUtf8(returnNote.getContent())).toBe("<p>line one</p><p>line two</p>");++ // The single top-level outline is placed under the import parent.+ const topLevel = parent.getChildNotes();+ expect(topLevel).toHaveLength(1);+ expect(topLevel[0].noteId).toBe(returnNote.noteId);++ // The nested outline becomes a child note.+ const children = returnNote.getChildNotes();+ expect(children).toHaveLength(1);+ expect(children[0].title).toBe("Child");+ expect(decodeUtf8(children[0].getContent())).toBe("<p>child text</p>");+ });++ it("falls back to text as the title (with empty content) when a v1 outline has a blank title", async () => {+ const parent = createParent();+ const xml = `<?xml version="1.0"?>+ <opml version="1.0">+ <body>+ <outline title=" " text="the only text" />+ </body>+ </opml>`;++ const returnNote = (await runImport(xml, parent)) as BNote;++ // Blank/whitespace title triggers the issue-1862 fallback.+ expect(returnNote.title).toBe("the only text");+ expect(decodeUtf8(returnNote.getContent())).toBe("");+ });++ it("imports a v2.0 outline using text as title and _note as raw HTML content", async () => {+ const parent = createParent();+ const xml = `<?xml version="1.0"?>+ <opml version="2.0">+ <body>+ <outline text="First" _note="<p>first body</p>" />+ <outline text="Second" _note="<p>second body</p>" />+ </body>+ </opml>`;++ const returnNote = (await runImport(xml, parent)) as BNote;++ // Only the first created note is returned/activated.+ expect(returnNote.title).toBe("First");+ expect(decodeUtf8(returnNote.getContent())).toBe("<p>first body</p>");++ // Both top-level outlines are imported in order.+ const topLevel = parent.getChildNotes();+ expect(topLevel.map((n) => n.title)).toEqual(["First", "Second"]);++ const second = topLevel.find((n) => n.title === "Second")!;+ expect(decodeUtf8(second.getContent())).toBe("<p>second body</p>");+ });++ it("sanitizes dangerous markup out of v2 _note content", async () => {+ const parent = createParent();+ // <script> is not in the allowed-tags list, so the sanitizer must strip it.+ const xml = `<?xml version="1.0"?>+ <opml version="2.0">+ <body>+ <outline text="XSS" _note="<p>safe</p><script>alert(1)</script>" />+ </body>+ </opml>`;++ const returnNote = (await runImport(xml, parent)) as BNote;++ const content = decodeUtf8(returnNote.getContent());+ // The safe paragraph survives; the disallowed <script> tag is stripped+ // (sanitize-html keeps the text node but drops the executable element).+ expect(content).toContain("<p>safe</p>");+ expect(content).not.toContain("<script");+ expect(content).not.toContain("</script>");+ });++ it("returns null and imports nothing when the OPML body has no outlines", async () => {+ const parent = createParent();+ const xml = `<?xml version="1.0"?>+ <opml version="2.0">+ <body></body>+ </opml>`;++ const returnNote = await runImport(xml, parent);++ expect(returnNote).toBeNull();+ expect(parent.getChildNotes()).toHaveLength(0);+ });++ it("rejects malformed XML by throwing", async () => {+ const parent = createParent();+ const xml = "<opml version=\"1.0\"><body><outline></body></opml>";++ await expect(runImport(xml, parent)).rejects.toThrow();+ });+}, 60_000);diff --git a/packages/trilium-core/src/services/instance_id.spec.ts b/packages/trilium-core/src/services/instance_id.spec.tsnew file mode 100644index 0000000000..3b5476418a--- /dev/null+++ b/packages/trilium-core/src/services/instance_id.spec.ts@@ -0,0 +1,51 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++import getInstanceId from "./instance_id.js";++describe("instance_id", () => {+ it("returns a 12-character string id", () => {+ const id = getInstanceId();++ expect(typeof id).toBe("string");+ expect(id).toHaveLength(12);+ });++ it("memoizes the id so repeated calls return the same value", () => {+ // The module caches the generated id in module-level state, so every+ // subsequent call within the process must yield the identical string.+ const first = getInstanceId();+ const second = getInstanceId();+ const third = getInstanceId();++ expect(second).toBe(first);+ expect(third).toBe(first);+ });++ describe("lazy generation (isolated module)", () => {+ beforeEach(() => {+ vi.resetModules();+ vi.doUnmock("./utils");+ });++ it("generates the id exactly once via randomString(12) and caches it", async () => {+ // Mock the underlying random source so we can both assert the+ // requested length and verify the value is generated lazily, only+ // on the first call, then reused from the cache.+ const randomString = vi.fn((length: number) => "X".repeat(length));+ vi.doMock("./utils", () => ({ randomString }));++ const freshGetInstanceId = (await import("./instance_id.js")).default;++ // Not generated until first access.+ expect(randomString).not.toHaveBeenCalled();++ const a = freshGetInstanceId();+ const b = freshGetInstanceId();++ expect(randomString).toHaveBeenCalledTimes(1);+ expect(randomString).toHaveBeenCalledWith(12);+ expect(a).toBe("XXXXXXXXXXXX");+ expect(b).toBe(a);+ });+ });+});diff --git a/packages/trilium-core/src/services/note_types.spec.ts b/packages/trilium-core/src/services/note_types.spec.tsnew file mode 100644index 0000000000..9d7137ba7e--- /dev/null+++ b/packages/trilium-core/src/services/note_types.spec.ts@@ -0,0 +1,57 @@+import { describe, expect, it } from "vitest";++import noteTypeService from "./note_types.js";++const { getNoteTypeNames, getDefaultMimeForNoteType } = noteTypeService;++describe("getNoteTypeNames", () => {+ it("returns all known note type names without duplicates", () => {+ const names = getNoteTypeNames();++ expect(names).toContain("text");+ expect(names).toContain("code");+ expect(names).toContain("mermaid");+ expect(names).toContain("llmChat");+ expect(new Set(names).size).toBe(names.length);+ });++ it("returns a fresh array on each call so callers cannot mutate the source", () => {+ const first = getNoteTypeNames();+ const second = getNoteTypeNames();++ expect(first).not.toBe(second);+ expect(first).toEqual(second);++ first.push("mutated");+ expect(getNoteTypeNames()).not.toContain("mutated");+ });+});++describe("getDefaultMimeForNoteType", () => {+ it("returns the configured default MIME for known types", () => {+ expect(getDefaultMimeForNoteType("text")).toBe("text/html");+ expect(getDefaultMimeForNoteType("code")).toBe("text/plain");+ expect(getDefaultMimeForNoteType("file")).toBe("application/octet-stream");+ expect(getDefaultMimeForNoteType("relationMap")).toBe("application/json");+ expect(getDefaultMimeForNoteType("mermaid")).toBe("text/vnd.mermaid");+ });++ it("returns an empty string for types without a default MIME", () => {+ expect(getDefaultMimeForNoteType("render")).toBe("");+ expect(getDefaultMimeForNoteType("image")).toBe("");+ expect(getDefaultMimeForNoteType("book")).toBe("");+ });++ it("exposes a default MIME for every name reported by getNoteTypeNames", () => {+ for (const name of getNoteTypeNames()) {+ expect(typeof getDefaultMimeForNoteType(name)).toBe("string");+ }+ });++ it("throws for an unknown note type", () => {+ expect(() => getDefaultMimeForNoteType("nonExistentType")).toThrow(+ "Cannot find note type 'nonExistentType'"+ );+ expect(() => getDefaultMimeForNoteType("")).toThrow(/Cannot find note type/);+ });+});diff --git a/packages/trilium-core/src/services/notes.spec.ts b/packages/trilium-core/src/services/notes.spec.tsnew file mode 100644index 0000000000..6d4e9e69dd--- /dev/null+++ b/packages/trilium-core/src/services/notes.spec.ts@@ -0,0 +1,302 @@+import { beforeAll, describe, expect, it } from "vitest";++import becca from "../becca/becca.js";+import type BBranch from "../becca/entities/bbranch.js";+import type BNote from "../becca/entities/bnote.js";+import { getContext } from "./context.js";+import noteService, { saveLinks } from "./notes.js";+import { getSql } from "./sql/index.js";++/**+ * The pure link-extraction helpers (findBookmarks, findLlmChatLinks) and the+ * becca-mocked checkImageAttachments path are already covered by+ * apps/server/src/services/notes.spec.ts. This file exercises the real-DB+ * write paths (note creation, update, duplication) which that spec stubs out.+ */++/**+ * Wraps a callback in a CLS context. Entity mutations (createNewNote,+ * setContent, BAttribute.save(), etc.) require CLS to be initialised.+ */+function withContext<T>(fn: () => T): T {+ return getContext().init(fn);+}++let counter = 0;++/**+ * Creates a fresh text note under the given parent in the real in-memory DB.+ * Each call uses a unique title since the same fixture DB is shared between+ * the `it()`s in this file.+ */+function createNote(parentNoteId: string, overrides: Partial<Parameters<typeof noteService.createNewNote>[0]> = {}): {+ note: BNote;+ branch: BBranch;+} {+ counter++;+ return withContext(() =>+ noteService.createNewNote({+ parentNoteId,+ title: `notes-spec-${counter}`,+ content: "<p>hello</p>",+ type: "text",+ ...overrides+ })+ );+}++describe("notes service (real DB)", () => {+ beforeAll(() => {+ // The in-memory fixture DB and initializeCore are booted by the+ // server suite setup (apps/server/spec/setup.ts), through which+ // co-located trilium-core specs run.+ });++ describe("createNewNote", () => {+ it("creates a text note under root with content, branch and derived mime", () => {+ const { note, branch } = createNote("root", { title: "spec-create-basic", content: "<p>body</p>" });++ expect(becca.notes[note.noteId]).toBe(note);+ expect(note.title).toBe("spec-create-basic");+ expect(note.type).toBe("text");+ expect(note.mime).toBe("text/html");+ expect(note.getContent()).toBe("<p>body</p>");++ expect(branch.parentNoteId).toBe("root");+ expect(branch.noteId).toBe(note.noteId);+ // position derives from MAX existing position + 10 and is therefore positive.+ expect(branch.notePosition).toBeGreaterThan(0);++ // The note row is persisted in the DB, not just becca.+ const row = getSql().getRow<{ title: string }>("SELECT title FROM notes WHERE noteId = ?", [note.noteId]);+ expect(row.title).toBe("spec-create-basic");+ });++ it("honours an explicit notePosition and creates atomic attributes", () => {+ const { note, branch } = createNote("root", {+ title: "spec-create-attrs",+ content: "",+ notePosition: 1234,+ attributes: [+ { type: "label", name: "myLabel", value: "v1", isInheritable: false, position: 10 },+ { type: "label", name: "secondLabel", value: "v2", isInheritable: false, position: 20 }+ ]+ });++ expect(branch.notePosition).toBe(1234);+ expect(note.getLabelValue("myLabel")).toBe("v1");+ expect(note.getLabelValue("secondLabel")).toBe("v2");+ });++ it("throws when the parent note does not exist", () => {+ expect(() => createNote("noSuchParent00", { title: "spec-bad-parent" })).toThrow(+ /Parent note 'noSuchParent00' was not found/+ );+ });++ it("throws when the content is null/undefined", () => {+ expect(() =>+ withContext(() =>+ noteService.createNewNote({+ parentNoteId: "root",+ title: "spec-null-content",+ // deliberately invalid content to hit the guard+ content: null as unknown as string,+ type: "text"+ })+ )+ ).toThrow(/Note content must be set/);+ });++ it("refuses to create notes under a forbidden parent like _hidden", () => {+ expect(() => createNote("_hidden", { title: "spec-hidden-child" })).toThrow(+ /Creating child notes into '_hidden' is not allowed/+ );+ });++ it("inherits the template's mime and adds a template relation when creating from a template", () => {+ const template = createNote("root", { title: "spec-template", content: "<p>tmpl</p>" });+ // Give the template a non-default mime so we can verify inheritance.+ withContext(() => {+ template.note.mime = "text/special";+ template.note.save();+ });++ const { note } = createNote("root", {+ title: "spec-from-template",+ content: "<p>child</p>",+ templateNoteId: template.note.noteId+ });++ expect(note.mime).toBe("text/special");+ expect(note.getRelationValue("template")).toBe(template.note.noteId);+ });+ });++ describe("createNewNoteWithTarget", () => {+ it("defaults the type from the parent and creates the note for 'into'", () => {+ const parent = createNote("root", { title: "spec-into-parent" });++ const { note, branch } = withContext(() =>+ noteService.createNewNoteWithTarget("into", undefined, {+ parentNoteId: parent.note.noteId,+ title: "spec-into-child",+ content: "<p>x</p>",+ // type intentionally left unset so it is derived from the parent+ type: undefined as unknown as "text"+ })+ );++ expect(note.type).toBe("text");+ expect(branch.parentNoteId).toBe(parent.note.noteId);+ });++ it("positions a note after an existing sibling branch", () => {+ const parent = createNote("root", { title: "spec-after-parent" });+ const first = createNote(parent.note.noteId, { title: "spec-after-first" });++ const { branch } = withContext(() =>+ noteService.createNewNoteWithTarget("after", first.branch.branchId, {+ parentNoteId: parent.note.noteId,+ title: "spec-after-second",+ content: "<p>x</p>",+ type: "text"+ })+ );++ expect(branch.notePosition).toBe(first.branch.notePosition + 10);+ });++ it("throws on an unknown target", () => {+ expect(() =>+ withContext(() =>+ noteService.createNewNoteWithTarget("sideways" as "into", undefined, {+ parentNoteId: "root",+ title: "spec-bad-target",+ content: "",+ type: "text"+ })+ )+ ).toThrow(/Unknown target/);+ });+ });++ describe("saveLinks", () => {+ it("creates internal-link relations to existing target notes and strips absolute hrefs", () => {+ const target = createNote("root", { title: "spec-link-target" });+ const source = createNote("root", { title: "spec-link-source" });++ const content = `<p>link <a href="http://example.com/#root/${target.note.noteId}">here</a></p>`;++ const { content: newContent } = withContext(() => saveLinks(source.note, content));++ // Absolute href is rewritten to a relative #root reference.+ expect(newContent).toContain(`href="#root/${target.note.noteId}"`);+ expect(newContent).not.toContain("http://example.com");++ const relation = source.note.getRelations().find((r) => r.name === "internalLink");+ expect(relation).toBeDefined();+ expect(relation!.value).toBe(target.note.noteId);+ });++ it("removes link relations that are no longer present in the content", () => {+ const target = createNote("root", { title: "spec-unused-target" });+ const source = createNote("root", { title: "spec-unused-source" });++ // First, create the link.+ withContext(() => saveLinks(source.note, `<a href="#root/${target.note.noteId}">x</a>`));+ expect(source.note.getRelations().some((r) => r.name === "internalLink")).toBe(true);++ // Then save content without the link; the relation should be marked deleted.+ withContext(() => saveLinks(source.note, "<p>no links anymore</p>"));+ expect(source.note.getRelations().some((r) => r.name === "internalLink" && !r.isDeleted)).toBe(false);+ });++ it("is a no-op for note types it does not scan", () => {+ const code = createNote("root", {+ title: "spec-code",+ content: "let x = 1;",+ type: "code",+ mime: "application/javascript"+ });++ const content = `<a href="#root/root">x</a>`;+ const res = withContext(() => saveLinks(code.note, content));++ expect(res).toEqual({ forceFrontendReload: false, content });+ expect(code.note.getRelations().some((r) => r.name === "internalLink")).toBe(false);+ });+ });++ describe("updateNoteData", () => {+ it("persists new content and extracts link relations", () => {+ const target = createNote("root", { title: "spec-update-target" });+ const note = createNote("root", { title: "spec-update", content: "<p>old</p>" }).note;++ const content = `<p>new <a href="#root/${target.note.noteId}">link</a></p>`;+ withContext(() => noteService.updateNoteData(note.noteId, content));++ expect(note.getContent()).toContain("new");+ expect(+ note.getRelations().some((r) => r.name === "internalLink" && r.value === target.note.noteId)+ ).toBe(true);+ });++ it("throws when the note is not available", () => {+ expect(() => withContext(() => noteService.updateNoteData("doesNotExist99", "<p>x</p>"))).toThrow(+ /not available for change/+ );+ });+ });++ describe("duplicateSubtree", () => {+ it("duplicates a note and its descendants, remapping internal relations and appending a suffix", () => {+ const root = createNote("root", { title: "spec-dup-root" });+ const child = createNote(root.note.noteId, { title: "spec-dup-child" });++ // Add a relation from the parent to its own child so we can verify remapping.+ withContext(() => root.note.setRelation("myRel", child.note.noteId));++ const { note: dupNote } = withContext(() => noteService.duplicateSubtree(root.note.noteId, "root"));++ // A brand new note id is allocated.+ expect(dupNote.noteId).not.toBe(root.note.noteId);+ // The duplicate gets the "(dup)" suffix in its title.+ expect(dupNote.title).not.toBe(root.note.title);++ // The internal relation now points at the duplicated child, not the original.+ const dupChildren = dupNote.getChildNotes();+ expect(dupChildren).toHaveLength(1);+ expect(dupNote.getRelationValue("myRel")).toBe(dupChildren[0].noteId);+ expect(dupChildren[0].noteId).not.toBe(child.note.noteId);+ });++ it("refuses to duplicate the root note", () => {+ expect(() => withContext(() => noteService.duplicateSubtree("root", "root"))).toThrow(+ /Duplicating root is not possible/+ );+ });+ });++ describe("saveRevisionIfNeeded", () => {+ it("does nothing for notes with disableVersioning", () => {+ const note = createNote("root", {+ title: "spec-no-revision",+ content: "<p>x</p>",+ attributes: [+ { type: "label", name: "disableVersioning", value: "", isInheritable: false, position: 10 }+ ]+ }).note;++ const before = getSql().getValue<number>("SELECT COUNT(*) FROM revisions WHERE noteId = ?", [+ note.noteId+ ]);+ withContext(() => noteService.saveRevisionIfNeeded(note));+ const after = getSql().getValue<number>("SELECT COUNT(*) FROM revisions WHERE noteId = ?", [+ note.noteId+ ]);++ expect(after).toBe(before);+ });+ });+});diff --git a/packages/trilium-core/src/services/one_time_timer.spec.ts b/packages/trilium-core/src/services/one_time_timer.spec.tsnew file mode 100644index 0000000000..63949e9c24--- /dev/null+++ b/packages/trilium-core/src/services/one_time_timer.spec.ts@@ -0,0 +1,87 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import oneTimeTimer from "./one_time_timer.js";++describe("oneTimeTimer", () => {+ beforeEach(() => {+ vi.useFakeTimers();+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ describe("scheduleExecution", () => {+ it("runs the callback only after the delay has elapsed", () => {+ const cb = vi.fn();++ oneTimeTimer.scheduleExecution("after-delay", 100, cb);++ vi.advanceTimersByTime(99);+ expect(cb).not.toHaveBeenCalled();++ vi.advanceTimersByTime(1);+ expect(cb).toHaveBeenCalledTimes(1);+ });++ it("ignores subsequent calls with the same name and keeps the first scheduled time", () => {+ const first = vi.fn();+ const second = vi.fn();++ oneTimeTimer.scheduleExecution("same-name", 100, first);+ // A later call must not move the timer to the future nor replace the callback.+ oneTimeTimer.scheduleExecution("same-name", 1000, second);++ vi.advanceTimersByTime(100);++ expect(first).toHaveBeenCalledTimes(1);+ expect(second).not.toHaveBeenCalled();+ });++ it("frees the name after execution so it can be scheduled again", () => {+ const first = vi.fn();+ const second = vi.fn();++ oneTimeTimer.scheduleExecution("reusable", 100, first);+ vi.advanceTimersByTime(100);+ expect(first).toHaveBeenCalledTimes(1);++ // After the first execution the slot is released, so a new schedule is honored.+ oneTimeTimer.scheduleExecution("reusable", 100, second);+ vi.advanceTimersByTime(100);+ expect(second).toHaveBeenCalledTimes(1);+ });++ it("schedules independent timers for different names", () => {+ const cbA = vi.fn();+ const cbB = vi.fn();++ oneTimeTimer.scheduleExecution("name-a", 100, cbA);+ oneTimeTimer.scheduleExecution("name-b", 200, cbB);++ vi.advanceTimersByTime(100);+ expect(cbA).toHaveBeenCalledTimes(1);+ expect(cbB).not.toHaveBeenCalled();++ vi.advanceTimersByTime(100);+ expect(cbB).toHaveBeenCalledTimes(1);+ });++ it("allows re-scheduling the same name from within the callback", () => {+ const inner = vi.fn();+ const outer = vi.fn(() => {+ // The slot is freed before the callback runs, so this re-schedule takes effect.+ oneTimeTimer.scheduleExecution("self-reschedule", 50, inner);+ });++ oneTimeTimer.scheduleExecution("self-reschedule", 50, outer);++ vi.advanceTimersByTime(50);+ expect(outer).toHaveBeenCalledTimes(1);+ expect(inner).not.toHaveBeenCalled();++ vi.advanceTimersByTime(50);+ expect(inner).toHaveBeenCalledTimes(1);+ });+ });+});diff --git a/packages/trilium-core/src/services/options.spec.ts b/packages/trilium-core/src/services/options.spec.tsnew file mode 100644index 0000000000..98ace814fb--- /dev/null+++ b/packages/trilium-core/src/services/options.spec.ts@@ -0,0 +1,151 @@+import { describe, expect, it } from "vitest";++import becca from "../becca/becca.js";+import { getContext } from "./context.js";+import optionService from "./options.js";+import { getSql } from "./sql/index.js";++/**+ * Wraps a callback in a CLS context. Entity mutations (BOption.save() via+ * setOption/createOption) emit entity-change records which require CLS.+ */+function withContext<T>(fn: () => T): T {+ return getContext().init(fn);+}++let counter = 0;++/** Returns an option name that is guaranteed unique within this shared fixture DB. */+function uniqueName(): string {+ counter++;+ return `optionsSpecTmp${counter}`;+}++function readFromDb(name: string): string | null {+ const row = getSql().getRowOrNull<{ value: string }>(+ "SELECT value FROM options WHERE name = ?",+ [name]+ );+ return row?.value ?? null;+}++describe("options service (real DB)", () => {+ describe("getOptionOrNull / getOption", () => {+ it("returns the stored value for a seeded option", () => {+ // The fixture DB seeds standard options such as mainFontSize.+ const value = optionService.getOptionOrNull("mainFontSize" as any);+ expect(value).not.toBeNull();+ expect(optionService.getOption("mainFontSize" as any)).toBe(value);+ });++ it("returns null from getOptionOrNull for a non-existent option", () => {+ expect(optionService.getOptionOrNull("doesNotExistOption" as any)).toBeNull();+ });++ it("throws from getOption for a non-existent option", () => {+ expect(() => optionService.getOption("doesNotExistOption" as any)).toThrow(+ /doesn't exist/+ );+ });+ });++ describe("getOptionInt", () => {+ it("parses an integer-valued option", () => {+ const name = uniqueName();+ withContext(() => optionService.createOption(name as any, "42", false));++ expect(optionService.getOptionInt(name as any)).toBe(42);+ });++ it("returns the supplied default when the value cannot be parsed", () => {+ const name = uniqueName();+ withContext(() => optionService.createOption(name as any, "not-a-number", false));++ expect(optionService.getOptionInt(name as any, 7)).toBe(7);+ });++ it("throws when the value cannot be parsed and no default is given", () => {+ const name = uniqueName();+ withContext(() => optionService.createOption(name as any, "garbage", false));++ expect(() => optionService.getOptionInt(name as any)).toThrow(/into integer/);+ });+ });++ describe("getOptionBool", () => {+ it("parses 'true' and 'false' into booleans", () => {+ const trueName = uniqueName();+ const falseName = uniqueName();+ withContext(() => {+ optionService.createOption(trueName as any, "true", false);+ optionService.createOption(falseName as any, "false", false);+ });++ expect(optionService.getOptionBool(trueName as any)).toBe(true);+ expect(optionService.getOptionBool(falseName as any)).toBe(false);+ });++ it("throws for a value that is neither 'true' nor 'false'", () => {+ const name = uniqueName();+ withContext(() => optionService.createOption(name as any, "yes", false));++ expect(() => optionService.getOptionBool(name as any)).toThrow(/into boolean/);+ });+ });++ describe("createOption", () => {+ it("persists a new option with its sync flag in becca and the DB", () => {+ const syncedName = uniqueName();+ const localName = uniqueName();++ withContext(() => {+ optionService.createOption(syncedName as any, "synced-value", true);+ optionService.createOption(localName as any, "local-value", false);+ });++ expect(becca.getOption(syncedName)?.value).toBe("synced-value");+ expect(becca.getOption(syncedName)?.isSynced).toBe(true);+ expect(becca.getOption(localName)?.isSynced).toBe(false);++ expect(readFromDb(syncedName)).toBe("synced-value");+ expect(readFromDb(localName)).toBe("local-value");+ });+ });++ describe("setOption", () => {+ it("updates the value of an existing option", () => {+ const name = uniqueName();+ withContext(() => optionService.createOption(name as any, "initial", false));++ withContext(() => optionService.setOption(name as any, "changed"));++ expect(optionService.getOption(name as any)).toBe("changed");+ expect(readFromDb(name)).toBe("changed");+ });++ it("creates the option (local-only) when it does not yet exist", () => {+ const name = uniqueName();++ withContext(() => optionService.setOption(name as any, "created-by-set"));++ expect(optionService.getOption(name as any)).toBe("created-by-set");+ expect(becca.getOption(name)?.isSynced).toBe(false);+ expect(readFromDb(name)).toBe("created-by-set");+ });+ });++ describe("getOptions / getOptionMap", () => {+ it("includes a freshly created option in both the list and the map", () => {+ const name = uniqueName();+ withContext(() => optionService.createOption(name as any, "in-collection", false));++ const all = optionService.getOptions();+ expect(all.some((o) => o.name === name && o.value === "in-collection")).toBe(true);++ const map = optionService.getOptionMap();+ expect(map[name as keyof typeof map]).toBe("in-collection");+ // Map and list expose the same set of option names.+ expect(Object.keys(map).length).toBe(all.length);+ });+ });+});diff --git a/packages/trilium-core/src/services/promoted_attribute_definition_parser.spec.ts b/packages/trilium-core/src/services/promoted_attribute_definition_parser.spec.tsnew file mode 100644index 0000000000..0423b4ad51--- /dev/null+++ b/packages/trilium-core/src/services/promoted_attribute_definition_parser.spec.ts@@ -0,0 +1,88 @@+import { describe, expect, it, vi } from "vitest";+import promotedAttributeDefinitionParser from "./promoted_attribute_definition_parser.js";++const { parse } = promotedAttributeDefinitionParser;++describe("promoted attribute definition parser", () => {+ it("parses the 'promoted' flag", () => {+ expect(parse("promoted")).toEqual({ isPromoted: true });+ });++ it("parses every recognized label type", () => {+ for (const labelType of ["text", "textarea", "number", "boolean", "date", "datetime", "time", "url", "color"]) {+ expect(parse(labelType)).toEqual({ labelType });+ }+ });++ it("parses both multiplicity values", () => {+ expect(parse("single")).toEqual({ multiplicity: "single" });+ expect(parse("multi")).toEqual({ multiplicity: "multi" });+ });++ it("parses numeric precision and yields NaN when it is missing or malformed", () => {+ expect(parse("precision=2")).toEqual({ numberPrecision: 2 });+ // parseInt tolerates trailing characters.+ expect(parse("precision=3px")).toEqual({ numberPrecision: 3 });+ // Missing value -> parseInt(undefined) -> NaN.+ expect(parse("precision")).toEqual({ numberPrecision: NaN });+ });++ it("parses the promoted alias verbatim", () => {+ expect(parse("alias=My Label")).toEqual({ promotedAlias: "My Label" });+ // Missing value yields undefined rather than throwing.+ expect(parse("alias")).toEqual({ promotedAlias: undefined });+ });++ it("parses the inverse relation and strips disallowed characters", () => {+ // Allowed: letters, numbers, underscore and colon.+ expect(parse("inverse=isParentOf")).toEqual({ inverseRelation: "isParentOf" });+ expect(parse("inverse=is:parent_of2")).toEqual({ inverseRelation: "is:parent_of2" });+ // Disallowed characters (spaces, punctuation, dashes) are removed.+ expect(parse("inverse=is parent-of!")).toEqual({ inverseRelation: "isparentof" });+ });++ it("combines multiple comma-separated tokens into one definition", () => {+ expect(parse("promoted,single,text,precision=4,alias=Foo")).toEqual({+ isPromoted: true,+ multiplicity: "single",+ labelType: "text",+ numberPrecision: 4,+ promotedAlias: "Foo"+ });+ });++ it("trims surrounding whitespace from each token", () => {+ expect(parse(" promoted , number , precision=1 ")).toEqual({+ isPromoted: true,+ labelType: "number",+ numberPrecision: 1+ });+ });++ it("lets later tokens of the same kind override earlier ones", () => {+ expect(parse("text,number")).toEqual({ labelType: "number" });+ expect(parse("single,multi")).toEqual({ multiplicity: "multi" });+ });++ it("ignores unrecognized tokens (and logs them) while still parsing valid ones", () => {+ const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});+ try {+ expect(parse("bogus,promoted")).toEqual({ isPromoted: true });+ expect(logSpy).toHaveBeenCalledWith("Unrecognized attribute definition token:", "bogus");+ } finally {+ logSpy.mockRestore();+ }+ });++ it("returns an empty definition for an empty string and ignores empty tokens", () => {+ const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});+ try {+ // An empty string splits into a single empty token, which is unrecognized.+ expect(parse("")).toEqual({});+ // Trailing comma produces an extra empty token that is ignored.+ expect(parse("promoted,")).toEqual({ isPromoted: true });+ } finally {+ logSpy.mockRestore();+ }+ });+});diff --git a/packages/trilium-core/src/services/protected_session.spec.ts b/packages/trilium-core/src/services/protected_session.spec.tsnew file mode 100644index 0000000000..8dd258b51b--- /dev/null+++ b/packages/trilium-core/src/services/protected_session.spec.ts@@ -0,0 +1,129 @@+import { afterEach, beforeEach, describe, expect, it } from "vitest";++import { decodeUtf8, encodeUtf8 } from "./utils/binary.js";+import protectedSession from "./protected_session.js";++// The global server spec setup (apps/server/spec/setup.ts) calls initializeCore,+// which wires up the Node.js crypto provider that data_encryption (used by+// encrypt/decrypt/decryptString below) relies on via getCrypto(). No DB/becca+// access is needed here, so there's no CLS requirement. The module keeps a single+// module-level data key, so each test resets it to avoid cross-test leakage.++const KEY = encodeUtf8("0123456789abcdef"); // exactly 16 bytes++describe("protected_session", () => {+ beforeEach(() => {+ protectedSession.resetDataKey();+ });++ afterEach(() => {+ protectedSession.resetDataKey();+ });++ describe("data key lifecycle / availability", () => {+ it("is unavailable until a key is set and available afterwards", () => {+ expect(protectedSession.isProtectedSessionAvailable()).toBe(false);++ protectedSession.setDataKey(KEY);+ expect(protectedSession.isProtectedSessionAvailable()).toBe(true);+ });++ it("resetDataKey makes the session unavailable again", () => {+ protectedSession.setDataKey(KEY);+ expect(protectedSession.isProtectedSessionAvailable()).toBe(true);++ protectedSession.resetDataKey();+ expect(protectedSession.isProtectedSessionAvailable()).toBe(false);+ });++ it("setDataKey copies the input so later mutation of the caller's array is ignored", () => {+ const mutable = Uint8Array.from(KEY);+ protectedSession.setDataKey(mutable);++ const cipherText = protectedSession.encrypt("copy check") as string;++ // Mutating the caller's array after setDataKey must not affect the stored key.+ mutable.fill(0);++ const decrypted = protectedSession.decryptString(cipherText);+ expect(decrypted).toBe("copy check");+ });+ });++ describe("encrypt / decrypt / decryptString without a key", () => {+ it("returns null for encrypt, decrypt and decryptString when no key is set", () => {+ expect(protectedSession.encrypt("anything")).toBeNull();+ expect(protectedSession.decrypt("anything")).toBeNull();+ expect(protectedSession.decryptString("anything")).toBeNull();+ });++ it("encrypt returns null for null plaintext even after a key is set", () => {+ protectedSession.setDataKey(KEY);+ expect(protectedSession.encrypt(null as unknown as string)).toBeNull();+ });++ it("decrypt returns null for null ciphertext even after a key is set", () => {+ protectedSession.setDataKey(KEY);+ expect(protectedSession.decrypt(null as unknown as string)).toBeNull();+ });+ });++ describe("encrypt / decrypt round-trip with a key", () => {+ beforeEach(() => {+ protectedSession.setDataKey(KEY);+ });++ it("round-trips a plain string via encrypt + decrypt", () => {+ const cipherText = protectedSession.encrypt("hello world") as string;+ expect(typeof cipherText).toBe("string");++ const decrypted = protectedSession.decrypt(cipherText);+ expect(decrypted).not.toBeNull();+ expect(decodeUtf8(decrypted as Uint8Array)).toBe("hello world");+ });++ it("round-trips a Uint8Array payload (binary content)", () => {+ const payload = Uint8Array.from([0, 1, 2, 254, 255, 10, 13]);+ const cipherText = protectedSession.encrypt(payload) as string;++ const decrypted = protectedSession.decrypt(cipherText) as Uint8Array;+ expect(Array.from(decrypted)).toEqual(Array.from(payload));+ });++ it("decryptString returns the original string for a string round-trip", () => {+ const cipherText = protectedSession.encrypt("decrypt me") as string;+ expect(protectedSession.decryptString(cipherText)).toBe("decrypt me");+ });+ });++ describe("touchProtectedSession / getLastProtectedSessionOperationDate", () => {+ it("does not record an operation date while the session is unavailable", () => {+ protectedSession.touchProtectedSession();+ // resetDataKey only clears the key, not the recorded date, so the only way to+ // assert "did not touch" is that touching while unavailable is a no-op: set a+ // baseline with a key, reset, then touch while unavailable and confirm the date+ // is unchanged.+ protectedSession.setDataKey(KEY);+ protectedSession.touchProtectedSession();+ const baseline = protectedSession.getLastProtectedSessionOperationDate();+ expect(baseline).not.toBeNull();++ protectedSession.resetDataKey();+ protectedSession.touchProtectedSession();+ expect(protectedSession.getLastProtectedSessionOperationDate()).toBe(baseline);+ });++ it("records the current time when touched while the session is available", () => {+ protectedSession.setDataKey(KEY);++ const before = Date.now();+ protectedSession.touchProtectedSession();+ const after = Date.now();++ const date = protectedSession.getLastProtectedSessionOperationDate();+ expect(date).not.toBeNull();+ expect(date as number).toBeGreaterThanOrEqual(before);+ expect(date as number).toBeLessThanOrEqual(after);+ });+ });+});diff --git a/packages/trilium-core/src/services/revisions.spec.ts b/packages/trilium-core/src/services/revisions.spec.tsnew file mode 100644index 0000000000..7212cf9d46--- /dev/null+++ b/packages/trilium-core/src/services/revisions.spec.ts@@ -0,0 +1,187 @@+import { afterEach, describe, expect, it, vi } from "vitest";++import { getLog } from "./log.js";+import protectedSessionService from "./protected_session.js";+import revisionService from "./revisions.js";+import type BNote from "../becca/entities/bnote.js";++/**+ * `protectRevisions` only ever calls a handful of methods on the note, its+ * revisions and their attachments. It performs no SQL of its own (the writes+ * happen inside the entities' `setContent`), so the behaviour can be exercised+ * with lightweight fakes that record the calls made against them. The only+ * external dependency that needs taming is the protected-session availability+ * check, which we drive via a spy.+ */++interface SetContentCall {+ content: string | Uint8Array;+ opts?: { forceSave?: boolean };+}++function fakeAttachment(opts: { isProtected: boolean; content?: string; throwOnSet?: boolean }) {+ const setContentCalls: SetContentCall[] = [];++ return {+ attachmentId: "att1",+ isProtected: opts.isProtected,+ getContent: vi.fn(() => opts.content ?? "att-content"),+ setContent: vi.fn(function (this: { isProtected: boolean }, content: string | Uint8Array, o?: { forceSave?: boolean }) {+ if (opts.throwOnSet) {+ throw new Error("attachment setContent boom");+ }+ setContentCalls.push({ content, opts: o });+ }),+ setContentCalls+ };+}++type FakeAttachment = ReturnType<typeof fakeAttachment>;++function fakeRevision(opts: {+ isProtected: boolean;+ content?: string;+ attachments?: FakeAttachment[];+ throwOnSet?: boolean;+}) {+ const setContentCalls: SetContentCall[] = [];+ const attachments = opts.attachments ?? [];++ return {+ revisionId: "rev1",+ isProtected: opts.isProtected,+ getContent: vi.fn(() => opts.content ?? "rev-content"),+ setContent: vi.fn(function (this: { isProtected: boolean }, content: string | Uint8Array, o?: { forceSave?: boolean }) {+ if (opts.throwOnSet) {+ throw new Error("revision setContent boom");+ }+ setContentCalls.push({ content, opts: o });+ }),+ getAttachments: vi.fn(() => attachments),+ setContentCalls+ };+}++type FakeRevision = ReturnType<typeof fakeRevision>;++function fakeNote(opts: { isProtected: boolean; revisions?: FakeRevision[] }): BNote {+ return {+ noteId: "note1",+ isProtected: opts.isProtected,+ getRevisions: vi.fn(() => opts.revisions ?? [])+ } as unknown as BNote;+}++describe("revisions.protectRevisions", () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });++ it("throws and touches nothing when no protected session is available", () => {+ vi.spyOn(protectedSessionService, "isProtectedSessionAvailable").mockReturnValue(false);++ const revision = fakeRevision({ isProtected: false });+ const note = fakeNote({ isProtected: true, revisions: [revision] });++ expect(() => revisionService.protectRevisions(note)).toThrow(/active protected session/);+ // The note's revisions must not even be enumerated when the guard fails.+ expect((note.getRevisions as any)).not.toHaveBeenCalled();+ expect(revision.setContent).not.toHaveBeenCalled();+ });++ it("re-protects revisions and attachments whose flag differs from the note (force save, copies content)", () => {+ vi.spyOn(protectedSessionService, "isProtectedSessionAvailable").mockReturnValue(true);++ const attachment = fakeAttachment({ isProtected: false, content: "att-body" });+ const revision = fakeRevision({ isProtected: false, content: "rev-body", attachments: [attachment] });+ const note = fakeNote({ isProtected: true, revisions: [revision] });++ revisionService.protectRevisions(note);++ // Content is read once, then re-saved with forceSave so de/encryption runs.+ expect(revision.getContent).toHaveBeenCalledTimes(1);+ expect(revision.isProtected).toBe(true);+ expect(revision.setContentCalls).toEqual([{ content: "rev-body", opts: { forceSave: true } }]);++ expect(attachment.getContent).toHaveBeenCalledTimes(1);+ expect(attachment.isProtected).toBe(true);+ expect(attachment.setContentCalls).toEqual([{ content: "att-body", opts: { forceSave: true } }]);+ });++ it("flips both directions: an unprotected note de-protects its previously protected revision", () => {+ vi.spyOn(protectedSessionService, "isProtectedSessionAvailable").mockReturnValue(true);++ const attachment = fakeAttachment({ isProtected: true });+ const revision = fakeRevision({ isProtected: true, attachments: [attachment] });+ const note = fakeNote({ isProtected: false, revisions: [revision] });++ revisionService.protectRevisions(note);++ expect(revision.isProtected).toBe(false);+ expect(revision.setContent).toHaveBeenCalledTimes(1);+ expect(attachment.isProtected).toBe(false);+ expect(attachment.setContent).toHaveBeenCalledTimes(1);+ });++ it("skips entities already matching the note's protection state", () => {+ vi.spyOn(protectedSessionService, "isProtectedSessionAvailable").mockReturnValue(true);++ const matchingAttachment = fakeAttachment({ isProtected: true });+ const differingAttachment = fakeAttachment({ isProtected: false });+ const revision = fakeRevision({+ isProtected: true,+ attachments: [matchingAttachment, differingAttachment]+ });+ const note = fakeNote({ isProtected: true, revisions: [revision] });++ revisionService.protectRevisions(note);++ // Revision already matches -> not re-encrypted.+ expect(revision.getContent).not.toHaveBeenCalled();+ expect(revision.setContent).not.toHaveBeenCalled();++ // Only the attachment whose flag differs gets updated.+ expect(matchingAttachment.setContent).not.toHaveBeenCalled();+ expect(differingAttachment.setContent).toHaveBeenCalledTimes(1);+ expect(differingAttachment.isProtected).toBe(true);+ });++ it("processes every revision of the note", () => {+ vi.spyOn(protectedSessionService, "isProtectedSessionAvailable").mockReturnValue(true);++ const revA = fakeRevision({ isProtected: false });+ const revB = fakeRevision({ isProtected: false });+ const note = fakeNote({ isProtected: true, revisions: [revA, revB] });++ revisionService.protectRevisions(note);++ expect(revA.setContent).toHaveBeenCalledTimes(1);+ expect(revB.setContent).toHaveBeenCalledTimes(1);+ });++ it("rethrows and logs when a revision's setContent fails", () => {+ vi.spyOn(protectedSessionService, "isProtectedSessionAvailable").mockReturnValue(true);+ const errorSpy = vi.spyOn(getLog(), "error").mockImplementation(() => {});++ const revision = fakeRevision({ isProtected: false, throwOnSet: true });+ const note = fakeNote({ isProtected: true, revisions: [revision] });++ expect(() => revisionService.protectRevisions(note)).toThrow("revision setContent boom");+ // isProtected is mutated to the target value before the failing setContent.+ expect(revision.isProtected).toBe(true);+ expect(errorSpy).toHaveBeenCalled();+ });++ it("rethrows and logs when an attachment's setContent fails", () => {+ vi.spyOn(protectedSessionService, "isProtectedSessionAvailable").mockReturnValue(true);+ const errorSpy = vi.spyOn(getLog(), "error").mockImplementation(() => {});++ const attachment = fakeAttachment({ isProtected: false, throwOnSet: true });+ const revision = fakeRevision({ isProtected: true, attachments: [attachment] });+ const note = fakeNote({ isProtected: true, revisions: [revision] });++ expect(() => revisionService.protectRevisions(note)).toThrow("attachment setContent boom");+ expect(attachment.isProtected).toBe(true);+ expect(errorSpy).toHaveBeenCalled();+ });+});diff --git a/packages/trilium-core/src/services/script_context.spec.ts b/packages/trilium-core/src/services/script_context.spec.tsnew file mode 100644index 0000000000..416e27604e--- /dev/null+++ b/packages/trilium-core/src/services/script_context.spec.ts@@ -0,0 +1,80 @@+import { beforeEach, describe, expect, it } from "vitest";++import becca from "../becca/becca.js";+import { buildNote } from "../test/becca_easy_mocking.js";+import BackendScriptApi from "./backend_script_api.js";+import ScriptContext from "./script_context.js";++describe("ScriptContext", () => {+ beforeEach(() => {+ becca.reset();+ });++ it("maps every note into the notes and apis objects keyed by noteId", () => {+ const noteA = buildNote({ title: "A" });+ const noteB = buildNote({ title: "B" });++ const ctx = new ScriptContext([noteA, noteB], { startNote: noteA });++ expect((ctx.notes as Record<string, unknown>)[noteA.noteId]).toBe(noteA);+ expect((ctx.notes as Record<string, unknown>)[noteB.noteId]).toBe(noteB);++ const apis = ctx.apis as Record<string, unknown>;+ expect(apis[noteA.noteId]).toBeInstanceOf(BackendScriptApi);+ expect(apis[noteB.noteId]).toBeInstanceOf(BackendScriptApi);+ expect(apis[noteA.noteId]).not.toBe(apis[noteB.noteId]);++ expect(ctx.allNotes).toEqual([noteA, noteB]);+ expect(ctx.modules).toEqual({});+ });++ it("starts with empty maps when there are no notes", () => {+ const ctx = new ScriptContext([], {});++ expect(ctx.notes).toEqual({});+ expect(ctx.apis).toEqual({});+ expect(ctx.allNotes).toEqual([]);+ });++ it("require() resolves a registered module by matching note title", () => {+ const moduleNote = buildNote({ title: "myModule" });+ const ctx = new ScriptContext([moduleNote], { startNote: moduleNote });++ const exportsValue = { greet: () => "hi" };+ ctx.modules[moduleNote.noteId] = { exports: exportsValue as any };++ const resolved = ctx.require([moduleNote.noteId])("myModule");+ expect(resolved).toBe(exportsValue);+ });++ it("require() only considers note ids passed in moduleNoteIds", () => {+ const included = buildNote({ title: "shared" });+ const excluded = buildNote({ title: "shared" });+ const ctx = new ScriptContext([included, excluded], { startNote: included });++ ctx.modules[included.noteId] = { exports: ["included-exports"] };+ ctx.modules[excluded.noteId] = { exports: ["excluded-exports"] };++ // Only `included` is whitelisted, so its exports must be returned even+ // though both notes share the same title.+ const resolved = ctx.require([included.noteId])("shared");+ expect(resolved).toEqual(["included-exports"]);+ });++ it("require() falls back to native require when no note title matches", () => {+ const moduleNote = buildNote({ title: "myModule" });+ const ctx = new ScriptContext([moduleNote], { startNote: moduleNote });++ // "path" is not a Trilium module note, so it must resolve via Node's require.+ const path = ctx.require([moduleNote.noteId])("path");+ expect(typeof (path as { join?: unknown }).join).toBe("function");+ });++ it("require() throws when falling back to a non-existent native module", () => {+ const moduleNote = buildNote({ title: "myModule" });+ const ctx = new ScriptContext([moduleNote], { startNote: moduleNote });++ expect(() => ctx.require([moduleNote.noteId])("this-module-does-not-exist-xyz"))+ .toThrow();+ });+});diff --git a/packages/trilium-core/src/services/search/expressions/ancestor.spec.ts b/packages/trilium-core/src/services/search/expressions/ancestor.spec.tsnew file mode 100644index 0000000000..3240a90476--- /dev/null+++ b/packages/trilium-core/src/services/search/expressions/ancestor.spec.ts@@ -0,0 +1,160 @@+import { beforeEach, describe, expect, it } from "vitest";++import becca from "../../../becca/becca.js";+import BBranch from "../../../becca/entities/bbranch.js";+import BNote from "../../../becca/entities/bnote.js";+import { note, NoteBuilder } from "../../../test/becca_mocking.js";+import NoteSet from "../note_set.js";+import AncestorExp from "./ancestor.js";++// SearchContext-like argument is unused by execute(), so we pass an empty object.+const dummySearchContext = {} as any;++/** Build a NoteSet that contains every note currently registered in becca. */+function allNotesSet() {+ return new NoteSet(Object.values(becca.notes));+}++function execute(exp: AncestorExp, inputNoteSet = allNotesSet()) {+ return exp.execute(inputNoteSet, {}, dummySearchContext);+}++function noteIds(noteSet: NoteSet) {+ return noteSet.notes.map((n) => n.noteId).sort();+}++let rootNote: NoteBuilder;++describe("AncestorExp", () => {+ beforeEach(() => {+ becca.reset();++ rootNote = new NoteBuilder(new BNote({ noteId: "root", title: "root", type: "text" }));+ new BBranch({+ branchId: "none_root",+ noteId: "root",+ parentNoteId: "none",+ notePosition: 10+ });+ });++ describe("getComparator", () => {+ it("returns null when no depth condition is given", () => {+ const exp = new AncestorExp("root");+ expect(exp.getComparator()).toBeNull();+ expect(exp.getComparator("")).toBeNull();+ });++ it("builds an eq/gt/lt comparator that compares against the parsed depth", () => {+ const exp = new AncestorExp("root");++ const eq = exp.getComparator("eq2")!;+ expect(eq(1)).toBe(false);+ expect(eq(2)).toBe(true);+ expect(eq(3)).toBe(false);++ const gt = exp.getComparator("gt2")!;+ expect(gt(2)).toBe(false);+ expect(gt(3)).toBe(true);++ const lt = exp.getComparator("lt2")!;+ expect(lt(2)).toBe(false);+ expect(lt(1)).toBe(true);+ });++ it("returns null for an unrecognized condition prefix", () => {+ const exp = new AncestorExp("root");+ expect(exp.getComparator("ne2")).toBeNull();+ });+ });++ it("returns an empty set when the ancestor note does not exist", () => {+ const child = note("Child");+ rootNote.child(child);++ const exp = new AncestorExp("doesNotExist");+ const result = execute(exp);++ expect(result.notes).toHaveLength(0);+ });++ it("returns the ancestor subtree intersected with the input set when no depth is given", () => {+ const parent = note("Parent");+ const child = note("Child");+ const grandchild = note("Grandchild");+ const sibling = note("Sibling");+ parent.child(child.child(grandchild));+ rootNote.child(parent).child(sibling);++ const exp = new AncestorExp(parent.note.noteId);+ const result = execute(exp);++ // The subtree of "parent" is parent + child + grandchild; the unrelated+ // sibling and root must be excluded.+ expect(noteIds(result)).toEqual(+ [parent.note.noteId, child.note.noteId, grandchild.note.noteId].sort()+ );+ });++ it("intersects the subtree with the provided input set", () => {+ const parent = note("Parent");+ const child = note("Child");+ const grandchild = note("Grandchild");+ parent.child(child.child(grandchild));+ rootNote.child(parent);++ const exp = new AncestorExp(parent.note.noteId);++ // Restrict the input to just the grandchild; the rest of the subtree must+ // be dropped by the intersection.+ const restricted = new NoteSet([grandchild.note]);+ expect(noteIds(execute(exp, restricted))).toEqual([grandchild.note.noteId]);+ });++ it("filters by distance to the ancestor using the depth comparator", () => {+ const parent = note("Parent");+ const child = note("Child");+ const grandchild = note("Grandchild");+ parent.child(child.child(grandchild));+ rootNote.child(parent);++ // depth eq1 -> only direct children (the ancestor itself is distance 0).+ const eqExp = new AncestorExp(parent.note.noteId, "eq1");+ expect(noteIds(execute(eqExp))).toEqual([child.note.noteId]);++ // depth eq0 -> only the ancestor note itself.+ const selfExp = new AncestorExp(parent.note.noteId, "eq0");+ expect(noteIds(execute(selfExp))).toEqual([parent.note.noteId]);++ // depth gt1 -> notes strictly deeper than the direct children.+ const gtExp = new AncestorExp(parent.note.noteId, "gt1");+ expect(noteIds(execute(gtExp))).toEqual([grandchild.note.noteId]);++ // depth lt2 -> the ancestor and its direct children.+ const ltExp = new AncestorExp(parent.note.noteId, "lt2");+ expect(noteIds(execute(ltExp))).toEqual(+ [parent.note.noteId, child.note.noteId].sort()+ );+ });++ it("ignores the depth filter when the depth condition is unrecognized", () => {+ const parent = note("Parent");+ const child = note("Child");+ parent.child(child);+ rootNote.child(parent);++ // An invalid condition yields a null comparator, so the whole subtree is returned.+ const exp = new AncestorExp(parent.note.noteId, "bogus");+ expect(noteIds(execute(exp))).toEqual(+ [parent.note.noteId, child.note.noteId].sort()+ );+ });++ it("exposes the raw depth string for debugging", () => {+ const parent = note("Parent");+ rootNote.child(parent);++ const exp = new AncestorExp(parent.note.noteId, "eq3");+ expect(exp.ancestorDepth).toBe("eq3");+ });+});diff --git a/packages/trilium-core/src/services/search/expressions/and.spec.ts b/packages/trilium-core/src/services/search/expressions/and.spec.tsnew file mode 100644index 0000000000..6add4c213a--- /dev/null+++ b/packages/trilium-core/src/services/search/expressions/and.spec.ts@@ -0,0 +1,102 @@+import { describe, expect, it } from "vitest";++import type NoteSet from "../note_set.js";+import type SearchContext from "../search_context.js";+import AndExp from "./and.js";+import Expression from "./expression.js";+import TrueExp from "./true.js";++// execute() never inspects the SearchContext, so an empty object is enough.+const dummySearchContext = {} as SearchContext;++/**+ * Minimal Expression stub that records every NoteSet it receives and returns a+ * (possibly different) NoteSet, letting us observe the chaining order.+ */+class RecordingExp extends Expression {+ received: NoteSet[] = [];++ constructor(private readonly output?: NoteSet) {+ super();+ }++ execute(inputNoteSet: NoteSet): NoteSet {+ this.received.push(inputNoteSet);+ return this.output ?? inputNoteSet;+ }+}++describe("AndExp", () => {+ describe("of()", () => {+ it("returns a TrueExp when given no (truthy) sub-expressions", () => {+ expect(AndExp.of([])).toBeInstanceOf(TrueExp);+ expect(AndExp.of([null, undefined])).toBeInstanceOf(TrueExp);+ });++ it("returns the single sub-expression unwrapped instead of an AndExp", () => {+ const only = new RecordingExp();++ // The lone real expression is returned directly...+ expect(AndExp.of([only])).toBe(only);+ // ...and nullish entries are filtered before counting.+ expect(AndExp.of([null, only, undefined])).toBe(only);+ });++ it("wraps two or more sub-expressions in an AndExp, dropping nullish ones", () => {+ const a = new RecordingExp();+ const b = new RecordingExp();++ const result = AndExp.of([a, null, b, undefined]);++ expect(result).toBeInstanceOf(AndExp);+ expect((result as AndExp).subExpressions).toEqual([a, b]);+ });+ });++ describe("execute()", () => {+ it("feeds each sub-expression's output into the next and returns the last", () => {+ const first = new RecordingExp({ marker: "after-first" } as unknown as NoteSet);+ const second = new RecordingExp({ marker: "after-second" } as unknown as NoteSet);+ const input = { marker: "input" } as unknown as NoteSet;++ const exp = new AndExp([first, second]);+ const result = exp.execute(input, {}, dummySearchContext);++ // first sees the original input, second sees first's output.+ expect(first.received).toEqual([input]);+ expect(second.received).toEqual([{ marker: "after-first" }]);+ // the final return value is the last sub-expression's output.+ expect(result).toEqual({ marker: "after-second" });+ });++ it("returns the input note set unchanged when there are no sub-expressions", () => {+ const input = { marker: "input" } as unknown as NoteSet;++ const result = new AndExp([]).execute(input, {}, dummySearchContext);++ expect(result).toBe(input);+ });++ it("acts as identity when every sub-expression passes the set through", () => {+ const passthroughA = new RecordingExp();+ const passthroughB = new RecordingExp();+ const input = { marker: "input" } as unknown as NoteSet;++ const result = new AndExp([passthroughA, passthroughB]).execute(+ input,+ {},+ dummySearchContext+ );++ expect(result).toBe(input);+ expect(passthroughA.received).toEqual([input]);+ expect(passthroughB.received).toEqual([input]);+ });+ });++ it("stores the provided sub-expressions on construction", () => {+ const subExpressions = [new RecordingExp(), new RecordingExp()];++ expect(new AndExp(subExpressions).subExpressions).toBe(subExpressions);+ });+});diff --git a/packages/trilium-core/src/services/search/expressions/attribute_exists.spec.ts b/packages/trilium-core/src/services/search/expressions/attribute_exists.spec.tsnew file mode 100644index 0000000000..c1699c053f--- /dev/null+++ b/packages/trilium-core/src/services/search/expressions/attribute_exists.spec.ts@@ -0,0 +1,187 @@+import { beforeEach, describe, expect, it } from "vitest";++import becca from "../../../becca/becca.js";+import BBranch from "../../../becca/entities/bbranch.js";+import BNote from "../../../becca/entities/bnote.js";+import { note, NoteBuilder } from "../../../test/becca_mocking.js";+import NoteSet from "../note_set.js";+import AttributeExistsExp from "./attribute_exists.js";++// SearchContext-like argument is unused by execute(), so we pass an empty object.+const dummySearchContext = {} as any;++/** Build a NoteSet that contains every note currently registered in becca. */+function allNotesSet() {+ return new NoteSet(Object.values(becca.notes));+}++function execute(exp: AttributeExistsExp, inputNoteSet = allNotesSet()) {+ return exp.execute(inputNoteSet, {}, dummySearchContext);+}++function noteIds(noteSet: NoteSet) {+ return noteSet.notes.map((n) => n.noteId).sort();+}++let rootNote: NoteBuilder;++describe("AttributeExistsExp", () => {+ beforeEach(() => {+ becca.reset();++ rootNote = new NoteBuilder(new BNote({ noteId: "root", title: "root", type: "text" }));+ new BBranch({+ branchId: "none_root",+ noteId: "root",+ parentNoteId: "none",+ notePosition: 10+ });+ });++ it("flags template labels in the constructor, leaving plain labels unmarked", () => {+ const plain = new AttributeExistsExp("label", "tag", false);+ expect(plain.attributeType).toBe("label");+ expect(plain.attributeName).toBe("tag");++ // `template` / `workspacetemplate` labels are markers and must not be treated+ // as inheritable; that decision is observed through execute() below.+ const template = new AttributeExistsExp("label", "template", false);+ const workspaceTemplate = new AttributeExistsExp("label", "workspacetemplate", false);+ const relationNamedTemplate = new AttributeExistsExp("relation", "template", false);++ const tmpl = note("Template").label("template", "", /* isInheritable */ true);+ const child = note("Child");+ tmpl.child(child);+ rootNote.child(tmpl);++ // A real (inheritable) `template` label is found but only the note itself is added.+ expect(noteIds(execute(template))).toEqual([tmpl.note.noteId]);+ // The other expressions simply find nothing matching.+ expect(execute(workspaceTemplate).notes).toHaveLength(0);+ expect(execute(relationNamedTemplate).notes).toHaveLength(0);+ });++ it("matches notes that own the attribute, regardless of value", () => {+ const austria = note("Austria").label("capital", "Vienna");+ const germany = note("Germany").label("capital");+ const plain = note("Plain");+ rootNote.child(austria).child(germany).child(plain);++ const exp = new AttributeExistsExp("label", "capital", false);+ expect(noteIds(execute(exp))).toEqual([austria.note.noteId, germany.note.noteId].sort());+ });++ it("returns an empty set when no note owns the attribute", () => {+ rootNote.child(note("Plain"));++ const exp = new AttributeExistsExp("label", "missing", false);+ expect(execute(exp).notes).toHaveLength(0);+ });++ it("respects the attribute type, distinguishing labels from relations", () => {+ const target = note("Target");+ const withRelation = note("WithRelation").relation("ref", target.note);+ const withLabel = note("WithLabel").label("ref", "value");+ rootNote.child(target).child(withRelation).child(withLabel);++ const labelExp = new AttributeExistsExp("label", "ref", false);+ expect(noteIds(execute(labelExp))).toEqual([withLabel.note.noteId]);++ const relationExp = new AttributeExistsExp("relation", "ref", false);+ expect(noteIds(execute(relationExp))).toEqual([withRelation.note.noteId]);+ });++ it("matches the attribute name case-insensitively", () => {+ const tagged = note("Tagged").label("capital", "Vienna");+ rootNote.child(tagged);++ // becca lowercases/normalizes attribute names, so an upper-case query still matches.+ const exp = new AttributeExistsExp("label", "Capital", false);+ expect(noteIds(execute(exp))).toEqual([tagged.note.noteId]);+ });++ it("only returns notes that are present in the input note set", () => {+ const austria = note("Austria").label("capital", "Vienna");+ const germany = note("Germany").label("capital", "Berlin");+ rootNote.child(austria).child(germany);++ const exp = new AttributeExistsExp("label", "capital", false);++ const restricted = new NoteSet([austria.note]);+ expect(noteIds(execute(exp, restricted))).toEqual([austria.note.noteId]);+ });++ it("adds the whole subtree (including templated notes) for an inheritable attribute", () => {+ const parent = note("Parent").label("tag", "x", /* isInheritable */ true);+ const child = note("Child");+ const grandchild = note("Grandchild");+ parent.child(child.child(grandchild));+ rootNote.child(parent);++ const exp = new AttributeExistsExp("label", "tag", false);+ expect(noteIds(execute(exp))).toEqual(+ [parent.note.noteId, child.note.noteId, grandchild.note.noteId].sort()+ );+ });++ it("adds inheriting notes when the owning note is used as a template", () => {+ const template = note("Template").label("tag", "x");+ const consumer = note("Consumer").relation("template", template.note);+ rootNote.child(template).child(consumer);++ const exp = new AttributeExistsExp("label", "tag", false);+ // getInheritingNotes() returns the note itself plus notes inheriting from it.+ expect(noteIds(execute(exp))).toEqual([template.note.noteId, consumer.note.noteId].sort());+ });++ it("adds only the note itself when the attribute is neither inheritable nor inherited", () => {+ const plain = note("Plain").label("tag", "x");+ rootNote.child(plain);++ const exp = new AttributeExistsExp("label", "tag", false);+ expect(noteIds(execute(exp))).toEqual([plain.note.noteId]);+ });++ it("never expands template/workspacetemplate labels even when inheritable or inherited", () => {+ // An inheritable `template` label would normally pull in the whole subtree,+ // but the template-marker short-circuit limits it to the note itself.+ const inheritableTemplate = note("InheritableTemplate").label(+ "template",+ "",+ /* isInheritable */ true+ );+ const child = note("TemplateChild");+ inheritableTemplate.child(child);+ rootNote.child(inheritableTemplate);++ // A `workspacetemplate` label whose note is itself targeted by a template relation+ // would normally pull in inheriting notes, but is likewise limited to the note.+ const workspaceTemplate = note("WorkspaceTemplate").label("workspacetemplate");+ const consumer = note("WsConsumer").relation("template", workspaceTemplate.note);+ rootNote.child(workspaceTemplate).child(consumer);++ const templateExp = new AttributeExistsExp("label", "template", false);+ expect(noteIds(execute(templateExp))).toEqual([inheritableTemplate.note.noteId]);++ const workspaceExp = new AttributeExistsExp("label", "workspacetemplate", false);+ expect(noteIds(execute(workspaceExp))).toEqual([workspaceTemplate.note.noteId]);+ });++ it("matches attributes by name prefix when prefixMatch is enabled", () => {+ const archived = note("Archived").label("archived");+ const archivedDeep = note("ArchivedDeep").label("archiveDepth", "3");+ const unrelated = note("Unrelated").label("category", "misc");+ rootNote.child(archived).child(archivedDeep).child(unrelated);++ // Prefix "archiv" matches both `archived` and `archivedepth` (names are lowercased),+ // but not the unrelated `category` label.+ const prefixExp = new AttributeExistsExp("label", "archiv", true);+ expect(noteIds(execute(prefixExp))).toEqual(+ [archived.note.noteId, archivedDeep.note.noteId].sort()+ );++ // Without prefix matching the same partial name matches nothing exactly.+ const exactExp = new AttributeExistsExp("label", "archiv", false);+ expect(execute(exactExp).notes).toHaveLength(0);+ });+});diff --git a/packages/trilium-core/src/services/search/expressions/child_of.spec.ts b/packages/trilium-core/src/services/search/expressions/child_of.spec.tsnew file mode 100644index 0000000000..65323cc729--- /dev/null+++ b/packages/trilium-core/src/services/search/expressions/child_of.spec.ts@@ -0,0 +1,163 @@+import { beforeEach, describe, expect, it } from "vitest";++import becca from "../../../becca/becca.js";+import BBranch from "../../../becca/entities/bbranch.js";+import BNote from "../../../becca/entities/bnote.js";+import { note, NoteBuilder } from "../../../test/becca_mocking.js";+import ChildOfExp from "./child_of.js";+import Expression from "./expression.js";+import NoteSet from "../note_set.js";++// SearchContext-like argument is unused by execute(), so we pass an empty object.+const dummySearchContext = {} as any;++/** A stub sub-expression that records its inputs and returns a predetermined note set. */+class StubExp extends Expression {+ calls: { inputNoteSet: NoteSet; executionContext: {} }[] = [];++ constructor(private result: NoteSet) {+ super();+ }++ execute(inputNoteSet: NoteSet, executionContext: {}) {+ this.calls.push({ inputNoteSet, executionContext });+ return this.result;+ }+}++function noteIds(noteSet: NoteSet) {+ return noteSet.notes.map((n) => n.noteId).sort();+}++let rootNote: NoteBuilder;++describe("ChildOfExp", () => {+ beforeEach(() => {+ becca.reset();++ rootNote = new NoteBuilder(new BNote({ noteId: "root", title: "root", type: "text" }));+ new BBranch({+ branchId: "none_root",+ noteId: "root",+ parentNoteId: "none",+ notePosition: 10+ });+ });++ it("returns input notes whose parent is matched by the sub-expression", () => {+ const parent = note("Parent");+ const child = note("Child");+ const sibling = note("Sibling");+ parent.child(child);+ rootNote.child(parent).child(sibling);++ // The sub-expression matches only "parent"; its children present in the input set+ // (just "child") should come back.+ const exp = new ChildOfExp(new StubExp(new NoteSet([parent.note])));+ const input = new NoteSet([parent.note, child.note, sibling.note]);++ expect(noteIds(exp.execute(input, {}, dummySearchContext))).toEqual([child.note.noteId]);+ });++ it("feeds the parents of the input set to the sub-expression", () => {+ const parentA = note("ParentA");+ const parentB = note("ParentB");+ const childA = note("ChildA");+ const childB = note("ChildB");+ parentA.child(childA);+ parentB.child(childB);+ rootNote.child(parentA).child(parentB);++ const stub = new StubExp(new NoteSet());+ const exp = new ChildOfExp(stub);++ const executionContext = { marker: true };+ exp.execute(new NoteSet([childA.note, childB.note]), executionContext, dummySearchContext);++ // The sub-expression is invoked exactly once with the de-duplicated set of parents+ // (each child has "root"-less parents parentA/parentB respectively).+ expect(stub.calls).toHaveLength(1);+ expect(noteIds(stub.calls[0].inputNoteSet)).toEqual(+ [parentA.note.noteId, parentB.note.noteId].sort()+ );+ // The execution context is threaded through unchanged.+ expect(stub.calls[0].executionContext).toBe(executionContext);+ });++ it("only returns children that are also present in the input set", () => {+ const parent = note("Parent");+ const includedChild = note("Included");+ const excludedChild = note("Excluded");+ parent.child(includedChild).child(excludedChild);+ rootNote.child(parent);++ // Sub-expression matches the parent, but the input set omits one of its children,+ // so that child must be filtered out of the result.+ const exp = new ChildOfExp(new StubExp(new NoteSet([parent.note])));+ const input = new NoteSet([includedChild.note]);++ expect(noteIds(exp.execute(input, {}, dummySearchContext))).toEqual([+ includedChild.note.noteId+ ]);+ });++ it("de-duplicates a child reachable through multiple matched parents (clones)", () => {+ const parentA = note("ParentA");+ const parentB = note("ParentB");+ const child = note("Child");+ // The same child is cloned under both parents.+ parentA.child(child);+ parentB.child(child);+ rootNote.child(parentA).child(parentB);++ const exp = new ChildOfExp(new StubExp(new NoteSet([parentA.note, parentB.note])));+ const input = new NoteSet([child.note]);++ const result = exp.execute(input, {}, dummySearchContext);+ // NoteSet.add de-duplicates, so the cloned child appears only once.+ expect(noteIds(result)).toEqual([child.note.noteId]);+ expect(result.notes).toHaveLength(1);+ });++ it("returns an empty set when the sub-expression matches no parent", () => {+ const parent = note("Parent");+ const child = note("Child");+ parent.child(child);+ rootNote.child(parent);++ const exp = new ChildOfExp(new StubExp(new NoteSet()));+ const result = exp.execute(new NoteSet([child.note]), {}, dummySearchContext);++ expect(result).toBeInstanceOf(NoteSet);+ expect(result.notes).toHaveLength(0);+ });++ it("returns an empty set when the matched parent's children are absent from the input", () => {+ const parent = note("Parent");+ const child = note("Child");+ parent.child(child);+ rootNote.child(parent);++ // Parent is matched, but the input set contains only the parent (not its child).+ const exp = new ChildOfExp(new StubExp(new NoteSet([parent.note])));+ const result = exp.execute(new NoteSet([parent.note]), {}, dummySearchContext);++ expect(result.notes).toHaveLength(0);+ });++ it("propagates an error thrown by the sub-expression", () => {+ const boom = new (class extends Expression {+ execute(): NoteSet {+ throw new Error("sub-expression failure");+ }+ })();+ const child = note("Child");+ rootNote.child(child);++ const exp = new ChildOfExp(boom);++ expect(() => exp.execute(new NoteSet([child.note]), {}, dummySearchContext)).toThrow(+ "sub-expression failure"+ );+ });+});diff --git a/packages/trilium-core/src/services/search/expressions/descendant_of.spec.ts b/packages/trilium-core/src/services/search/expressions/descendant_of.spec.tsnew file mode 100644index 0000000000..c62ce3f36f--- /dev/null+++ b/packages/trilium-core/src/services/search/expressions/descendant_of.spec.ts@@ -0,0 +1,181 @@+import { beforeEach, describe, expect, it } from "vitest";++import becca from "../../../becca/becca.js";+import BBranch from "../../../becca/entities/bbranch.js";+import BNote from "../../../becca/entities/bnote.js";+import { note, NoteBuilder } from "../../../test/becca_mocking.js";+import DescendantOfExp from "./descendant_of.js";+import Expression from "./expression.js";+import NoteSet from "../note_set.js";++// SearchContext-like argument is unused by execute(), so we pass an empty object.+const dummySearchContext = {} as any;++/** A stub sub-expression that records its inputs and returns a predetermined note set. */+class StubExp extends Expression {+ calls: { inputNoteSet: NoteSet; executionContext: {} }[] = [];++ constructor(private result: NoteSet) {+ super();+ }++ execute(inputNoteSet: NoteSet, executionContext: {}) {+ this.calls.push({ inputNoteSet, executionContext });+ return this.result;+ }+}++function noteIds(noteSet: NoteSet) {+ return noteSet.notes.map((n) => n.noteId).sort();+}++/** A NoteSet containing every note currently registered in becca. */+function allNotesSet() {+ return new NoteSet(Object.values(becca.notes));+}++let rootNote: NoteBuilder;++describe("DescendantOfExp", () => {+ beforeEach(() => {+ becca.reset();++ rootNote = new NoteBuilder(new BNote({ noteId: "root", title: "root", type: "text" }));+ new BBranch({+ branchId: "none_root",+ noteId: "root",+ parentNoteId: "none",+ notePosition: 10+ });+ });++ it("returns input notes located in the subtree of a note matched by the sub-expression", () => {+ const ancestor = note("Ancestor");+ const child = note("Child");+ const grandchild = note("Grandchild");+ const outside = note("Outside");+ ancestor.child(child.child(grandchild));+ rootNote.child(ancestor).child(outside);++ // The sub-expression matches "ancestor"; its descendants present in the input set come+ // back, but the ancestor itself and unrelated notes are excluded.+ const exp = new DescendantOfExp(new StubExp(new NoteSet([ancestor.note])));+ const input = new NoteSet([child.note, grandchild.note, outside.note]);++ expect(noteIds(exp.execute(input, {}, dummySearchContext))).toEqual(+ [child.note.noteId, grandchild.note.noteId].sort()+ );+ });++ it("feeds the sub-expression every note in becca, not just the input set", () => {+ const ancestor = note("Ancestor");+ const child = note("Child");+ ancestor.child(child);+ rootNote.child(ancestor);++ const stub = new StubExp(new NoteSet());+ const exp = new DescendantOfExp(stub);++ const executionContext = { marker: true };+ // The input set deliberately omits most notes; the sub-expression must still see all of+ // becca (root, ancestor, child) so it can locate ancestors anywhere in the tree.+ exp.execute(new NoteSet([child.note]), executionContext, dummySearchContext);++ expect(stub.calls).toHaveLength(1);+ expect(noteIds(stub.calls[0].inputNoteSet)).toEqual(+ ["root", ancestor.note.noteId, child.note.noteId].sort()+ );+ // The execution context is threaded through unchanged.+ expect(stub.calls[0].executionContext).toBe(executionContext);+ });++ it("includes the matched note itself when it is part of the input set", () => {+ const ancestor = note("Ancestor");+ const child = note("Child");+ ancestor.child(child);+ rootNote.child(ancestor);++ // getSubtree() includes the subtree root, so a matched note present in the input set is+ // returned alongside its descendants.+ const exp = new DescendantOfExp(new StubExp(new NoteSet([ancestor.note])));+ const input = new NoteSet([ancestor.note, child.note]);++ expect(noteIds(exp.execute(input, {}, dummySearchContext))).toEqual(+ [ancestor.note.noteId, child.note.noteId].sort()+ );+ });++ it("only returns descendants that are also present in the input set", () => {+ const ancestor = note("Ancestor");+ const included = note("Included");+ const excluded = note("Excluded");+ ancestor.child(included).child(excluded);+ rootNote.child(ancestor);++ const exp = new DescendantOfExp(new StubExp(new NoteSet([ancestor.note])));+ const input = new NoteSet([included.note]);++ expect(noteIds(exp.execute(input, {}, dummySearchContext))).toEqual([included.note.noteId]);+ });++ it("de-duplicates a descendant reachable through multiple matched ancestors (clones)", () => {+ const ancestorA = note("AncestorA");+ const ancestorB = note("AncestorB");+ const child = note("Child");+ // The same child is cloned under both matched ancestors.+ ancestorA.child(child);+ ancestorB.child(child);+ rootNote.child(ancestorA).child(ancestorB);++ const exp = new DescendantOfExp(new StubExp(new NoteSet([ancestorA.note, ancestorB.note])));+ const input = new NoteSet([child.note]);++ const result = exp.execute(input, {}, dummySearchContext);+ // NoteSet.add de-duplicates, so the cloned child appears only once.+ expect(noteIds(result)).toEqual([child.note.noteId]);+ expect(result.notes).toHaveLength(1);+ });++ it("returns an empty set when the sub-expression matches no note", () => {+ const ancestor = note("Ancestor");+ const child = note("Child");+ ancestor.child(child);+ rootNote.child(ancestor);++ const exp = new DescendantOfExp(new StubExp(new NoteSet()));+ const result = exp.execute(new NoteSet([child.note]), {}, dummySearchContext);++ expect(result).toBeInstanceOf(NoteSet);+ expect(result.notes).toHaveLength(0);+ });++ it("returns an empty set when no descendant of the matched note is in the input", () => {+ const ancestor = note("Ancestor");+ const child = note("Child");+ const unrelated = note("Unrelated");+ ancestor.child(child);+ rootNote.child(ancestor).child(unrelated);++ // Ancestor is matched, but the input set holds only an unrelated note.+ const exp = new DescendantOfExp(new StubExp(new NoteSet([ancestor.note])));+ const result = exp.execute(new NoteSet([unrelated.note]), {}, dummySearchContext);++ expect(result.notes).toHaveLength(0);+ });++ it("propagates an error thrown by the sub-expression", () => {+ const boom = new (class extends Expression {+ execute(): NoteSet {+ throw new Error("sub-expression failure");+ }+ })();+ const child = note("Child");+ rootNote.child(child);++ const exp = new DescendantOfExp(boom);++ expect(() => exp.execute(new NoteSet([child.note]), {}, dummySearchContext)).toThrow(+ "sub-expression failure"+ );+ });+});diff --git a/packages/trilium-core/src/services/search/expressions/is_hidden.spec.ts b/packages/trilium-core/src/services/search/expressions/is_hidden.spec.tsnew file mode 100644index 0000000000..e00a9b852b--- /dev/null+++ b/packages/trilium-core/src/services/search/expressions/is_hidden.spec.ts@@ -0,0 +1,126 @@+import { beforeEach, describe, expect, it } from "vitest";++import becca from "../../../becca/becca.js";+import BBranch from "../../../becca/entities/bbranch.js";+import BNote from "../../../becca/entities/bnote.js";+import { note, NoteBuilder } from "../../../test/becca_mocking.js";+import NoteSet from "../note_set.js";+import IsHiddenExp from "./is_hidden.js";++// SearchContext-like argument is unused by execute(), so we pass an empty object.+const dummySearchContext = {} as any;++/** Build a NoteSet that contains every note currently registered in becca. */+function allNotesSet() {+ return new NoteSet(Object.values(becca.notes));+}++function execute(exp: IsHiddenExp, inputNoteSet = allNotesSet()) {+ return exp.execute(inputNoteSet, {}, dummySearchContext);+}++function noteIds(noteSet: NoteSet) {+ return noteSet.notes.map((n) => n.noteId).sort();+}++let rootNote: NoteBuilder;+let hiddenNote: NoteBuilder;++describe("IsHiddenExp", () => {+ beforeEach(() => {+ becca.reset();++ rootNote = new NoteBuilder(new BNote({ noteId: "root", title: "root", type: "text" }));+ new BBranch({+ branchId: "none_root",+ noteId: "root",+ parentNoteId: "none",+ notePosition: 10+ });++ // The hidden subtree root; notes living only under it are "hidden completely".+ hiddenNote = note("hidden", { noteId: "_hidden" });+ rootNote.child(hiddenNote);+ });++ it("keeps only notes that live entirely inside the hidden subtree", () => {+ const visible = note("Visible");+ const hidden = note("Hidden");+ rootNote.child(visible);+ hiddenNote.child(hidden);++ const result = execute(new IsHiddenExp());++ // The _hidden subtree root sits directly under root, so it is the visible+ // boundary and is not itself hidden; only its descendants are.+ expect(noteIds(result)).toEqual([hidden.note.noteId]);+ expect(result.hasNoteId(visible.note.noteId)).toBe(false);+ expect(result.hasNoteId("_hidden")).toBe(false);+ });++ it("never treats the root note as hidden", () => {+ const result = execute(new IsHiddenExp());++ expect(result.hasNoteId("root")).toBe(false);+ });++ it("treats descendants of the hidden subtree as hidden", () => {+ const child = note("HiddenChild");+ const grandchild = note("HiddenGrandchild");+ hiddenNote.child(child.child(grandchild));++ const result = execute(new IsHiddenExp());++ expect(result.hasNoteId(child.note.noteId)).toBe(true);+ expect(result.hasNoteId(grandchild.note.noteId)).toBe(true);+ });++ it("does not treat a note as hidden when it is also cloned into the visible tree", () => {+ // A note reachable from root through a non-hidden path is visible even if it+ // also has a parent in the hidden subtree.+ const cloned = note("Cloned");+ hiddenNote.child(cloned);+ rootNote.child(cloned);++ const result = execute(new IsHiddenExp());++ expect(result.hasNoteId(cloned.note.noteId)).toBe(false);+ });++ it("treats a note hidden only because its sole visible-looking parent is itself hidden", () => {+ // hiddenParent lives under _hidden, so it is hidden completely; its child has no+ // other path, so it inherits the hidden state recursively.+ const hiddenParent = note("HiddenParent");+ const child = note("Child");+ hiddenNote.child(hiddenParent.child(child));++ const result = execute(new IsHiddenExp());++ expect(result.hasNoteId(hiddenParent.note.noteId)).toBe(true);+ expect(result.hasNoteId(child.note.noteId)).toBe(true);+ });++ it("only considers notes present in the input note set", () => {+ const hiddenA = note("HiddenA");+ const hiddenB = note("HiddenB");+ hiddenNote.child(hiddenA).child(hiddenB);++ // Restrict the input set to just hiddenA; hiddenB must be excluded even though it+ // is also hidden.+ const restricted = new NoteSet([hiddenA.note]);+ const result = execute(new IsHiddenExp(), restricted);++ expect(noteIds(result)).toEqual([hiddenA.note.noteId]);+ });++ it("returns an empty set when no input note is hidden", () => {+ const a = note("A");+ const b = note("B");+ rootNote.child(a).child(b);++ const restricted = new NoteSet([a.note, b.note]);+ const result = execute(new IsHiddenExp(), restricted);++ expect(result.notes).toHaveLength(0);+ });+});diff --git a/packages/trilium-core/src/services/search/expressions/label_comparison.spec.ts b/packages/trilium-core/src/services/search/expressions/label_comparison.spec.tsnew file mode 100644index 0000000000..b046f7f84b--- /dev/null+++ b/packages/trilium-core/src/services/search/expressions/label_comparison.spec.ts@@ -0,0 +1,157 @@+import { beforeEach, describe, expect, it } from "vitest";++import becca from "../../../becca/becca.js";+import BBranch from "../../../becca/entities/bbranch.js";+import BNote from "../../../becca/entities/bnote.js";+import { note, NoteBuilder } from "../../../test/becca_mocking.js";+import NoteSet from "../note_set.js";+import LabelComparisonExp from "./label_comparison.js";++// SearchContext-like argument is unused by execute(), so we pass an empty object.+const dummySearchContext = {} as any;++/** Build a NoteSet that contains every note currently registered in becca. */+function allNotesSet() {+ return new NoteSet(Object.values(becca.notes));+}++function execute(exp: LabelComparisonExp, inputNoteSet = allNotesSet()) {+ return exp.execute(inputNoteSet, {}, dummySearchContext);+}++function noteIds(noteSet: NoteSet) {+ return noteSet.notes.map((n) => n.noteId).sort();+}++let rootNote: NoteBuilder;++describe("LabelComparisonExp", () => {+ beforeEach(() => {+ becca.reset();++ rootNote = new NoteBuilder(new BNote({ noteId: "root", title: "root", type: "text" }));+ new BBranch({+ branchId: "none_root",+ noteId: "root",+ parentNoteId: "none",+ notePosition: 10+ });+ });++ it("lowercases the attribute name in the constructor", () => {+ const exp = new LabelComparisonExp("label", "Capital", () => true);+ expect(exp.attributeName).toBe("capital");+ expect(exp.attributeType).toBe("label");+ });++ it("matches notes whose label value satisfies the comparator", () => {+ const austria = note("Austria").label("capital", "Vienna");+ const germany = note("Germany").label("capital", "Berlin");+ rootNote.child(austria).child(germany);++ const exp = new LabelComparisonExp("label", "capital", (value) => value === "vienna");+ const result = execute(exp);++ expect(noteIds(result)).toEqual([austria.note.noteId]);+ });++ it("returns an empty set when the comparator rejects every value", () => {+ const austria = note("Austria").label("capital", "Vienna");+ rootNote.child(austria);++ const exp = new LabelComparisonExp("label", "capital", () => false);+ const result = execute(exp);++ expect(result.notes).toHaveLength(0);+ });++ it("compares against a lowercased value (case-insensitive matching)", () => {+ const austria = note("Austria").label("capital", "VIENNA");+ rootNote.child(austria);++ // The comparator receives the lowercased value, so an uppercase target never matches...+ const upper = new LabelComparisonExp("label", "capital", (value) => value === "VIENNA");+ expect(execute(upper).notes).toHaveLength(0);++ // ...while the lowercased equivalent does.+ const lower = new LabelComparisonExp("label", "capital", (value) => value === "vienna");+ expect(noteIds(execute(lower))).toEqual([austria.note.noteId]);+ });++ it("only considers notes present in the input note set", () => {+ const austria = note("Austria").label("capital", "Vienna");+ const germany = note("Germany").label("capital", "Berlin");+ rootNote.child(austria).child(germany);++ const exp = new LabelComparisonExp("label", "capital", () => true);++ // Restrict the input set to just Austria; Germany must be excluded even though+ // it also carries a matching label.+ const restricted = new NoteSet([austria.note]);+ expect(noteIds(execute(exp, restricted))).toEqual([austria.note.noteId]);+ });++ it("respects the attribute type, ignoring relations with the same name", () => {+ const target = note("Target");+ const withRelation = note("WithRelation").relation("ref", target.note);+ const withLabel = note("WithLabel").label("ref", "value");+ rootNote.child(target).child(withRelation).child(withLabel);++ const labelExp = new LabelComparisonExp("label", "ref", () => true);+ expect(noteIds(execute(labelExp))).toEqual([withLabel.note.noteId]);++ const relationExp = new LabelComparisonExp("relation", "ref", () => true);+ expect(noteIds(execute(relationExp))).toEqual([withRelation.note.noteId]);+ });++ it("handles labels with an empty value by passing an empty string to the comparator", () => {+ const empty = note("Empty").label("flag");+ rootNote.child(empty);++ const received: string[] = [];+ const exp = new LabelComparisonExp("label", "flag", (value) => {+ received.push(value);+ return value === "";+ });++ expect(noteIds(execute(exp))).toEqual([empty.note.noteId]);+ expect(received).toEqual([""]);+ });++ it("adds the whole subtree (including templated notes) for an inheritable label", () => {+ const parent = note("Parent").label("tag", "x", /* isInheritable */ true);+ const child = note("Child");+ const grandchild = note("Grandchild");+ parent.child(child.child(grandchild));+ rootNote.child(parent);++ const exp = new LabelComparisonExp("label", "tag", () => true);+ const result = execute(exp);++ expect(noteIds(result)).toEqual(+ [parent.note.noteId, child.note.noteId, grandchild.note.noteId].sort()+ );+ });++ it("adds inheriting notes when the labelled note is used as a template", () => {+ const template = note("Template").label("tag", "x");+ const consumer = note("Consumer").relation("template", template.note);+ rootNote.child(template).child(consumer);++ const exp = new LabelComparisonExp("label", "tag", () => true);+ const result = execute(exp);++ // getInheritingNotes() returns the note itself plus notes inheriting from it.+ expect(noteIds(result)).toEqual([template.note.noteId, consumer.note.noteId].sort());+ });++ it("adds only the note itself when the label is neither inheritable nor inherited", () => {+ const plain = note("Plain").label("tag", "x");+ rootNote.child(plain);++ const exp = new LabelComparisonExp("label", "tag", () => true);+ const result = execute(exp);++ expect(noteIds(result)).toEqual([plain.note.noteId]);+ });+});diff --git a/packages/trilium-core/src/services/search/expressions/not.spec.ts b/packages/trilium-core/src/services/search/expressions/not.spec.tsnew file mode 100644index 0000000000..4d25c12295--- /dev/null+++ b/packages/trilium-core/src/services/search/expressions/not.spec.ts@@ -0,0 +1,119 @@+import { beforeEach, describe, expect, it } from "vitest";++import becca from "../../../becca/becca.js";+import type BNote from "../../../becca/entities/bnote.js";+import { note } from "../../../test/becca_mocking.js";+import NoteSet from "../note_set.js";+import type SearchContext from "../search_context.js";+import Expression from "./expression.js";+import NotExp from "./not.js";++// execute() ignores the executionContext / searchContext arguments, so dummies suffice.+const dummySearchContext = {} as SearchContext;++/** A stub sub-expression that always returns a fixed NoteSet, recording its inputs. */+class StubExp extends Expression {+ result: NoteSet;+ calls: Array<{ inputNoteSet: NoteSet; executionContext: {}; searchContext: SearchContext }> = [];++ constructor(result: NoteSet) {+ super();+ this.result = result;+ }++ execute(inputNoteSet: NoteSet, executionContext: {}, searchContext: SearchContext) {+ this.calls.push({ inputNoteSet, executionContext, searchContext });+ return this.result;+ }+}++function noteIds(noteSet: NoteSet) {+ return noteSet.notes.map((n) => n.noteId).sort();+}++let a: BNote, b: BNote, c: BNote;++describe("NotExp", () => {+ beforeEach(() => {+ becca.reset();++ a = note("A").note;+ b = note("B").note;+ c = note("C").note;+ });++ it("stores the sub-expression passed to the constructor", () => {+ const sub = new StubExp(new NoteSet());+ const exp = new NotExp(sub);++ expect(exp.subExpression).toBe(sub);+ // Inherited from Expression: name is the runtime constructor name.+ expect(exp.name).toBe("NotExp");+ });++ it("returns the input notes that are NOT matched by the sub-expression", () => {+ const input = new NoteSet([a, b, c]);+ // Sub-expression matches only B, so the result should be A and C.+ const exp = new NotExp(new StubExp(new NoteSet([b])));++ const result = exp.execute(input, {}, dummySearchContext);++ expect(noteIds(result)).toEqual([a.noteId, c.noteId].sort());+ });++ it("returns the full input set when the sub-expression matches nothing", () => {+ const input = new NoteSet([a, b, c]);+ const exp = new NotExp(new StubExp(new NoteSet()));++ const result = exp.execute(input, {}, dummySearchContext);++ expect(noteIds(result)).toEqual([a.noteId, b.noteId, c.noteId].sort());+ });++ it("returns an empty set when the sub-expression matches the entire input", () => {+ const input = new NoteSet([a, b, c]);+ const exp = new NotExp(new StubExp(new NoteSet([a, b, c])));++ const result = exp.execute(input, {}, dummySearchContext);++ expect(result.notes).toHaveLength(0);+ });++ it("ignores sub-expression matches that are not part of the input set", () => {+ const input = new NoteSet([a, b]);+ // The sub-expression also matches C, which is not in the input and must not affect the result.+ const exp = new NotExp(new StubExp(new NoteSet([b, c])));++ const result = exp.execute(input, {}, dummySearchContext);++ expect(noteIds(result)).toEqual([a.noteId]);+ });++ it("forwards the input note set and contexts to the sub-expression and returns a fresh NoteSet", () => {+ const input = new NoteSet([a, b]);+ const executionContext = { marker: true };+ const sub = new StubExp(new NoteSet([a]));+ const exp = new NotExp(sub);++ const result = exp.execute(input, executionContext, dummySearchContext);++ // The sub-expression is invoked exactly once with the same arguments NotExp received.+ expect(sub.calls).toHaveLength(1);+ expect(sub.calls[0].inputNoteSet).toBe(input);+ expect(sub.calls[0].executionContext).toBe(executionContext);+ expect(sub.calls[0].searchContext).toBe(dummySearchContext);++ // minus() builds a new NoteSet rather than mutating the input.+ expect(result).not.toBe(input);+ expect(noteIds(result)).toEqual([b.noteId]);+ expect(noteIds(input)).toEqual([a.noteId, b.noteId].sort());+ });++ it("returns an empty set for an empty input set", () => {+ const exp = new NotExp(new StubExp(new NoteSet([a, b, c])));++ const result = exp.execute(new NoteSet(), {}, dummySearchContext);++ expect(result.notes).toHaveLength(0);+ });+});diff --git a/packages/trilium-core/src/services/search/expressions/note_flat_text.spec.ts b/packages/trilium-core/src/services/search/expressions/note_flat_text.spec.tsnew file mode 100644index 0000000000..3becc3ee60--- /dev/null+++ b/packages/trilium-core/src/services/search/expressions/note_flat_text.spec.ts@@ -0,0 +1,247 @@+import { beforeEach, describe, expect, it } from "vitest";++import becca from "../../../becca/becca.js";+import BBranch from "../../../becca/entities/bbranch.js";+import BNote from "../../../becca/entities/bnote.js";+import { note, NoteBuilder } from "../../../test/becca_mocking.js";+import NoteSet from "../note_set.js";+import NoteFlatTextExp from "./note_flat_text.js";++/**+ * Minimal SearchContext stand-in. execute() only reads `autocomplete`,+ * `enableFuzzyMatching` and `highlightedTokens`, so a plain object suffices.+ */+function searchContext(overrides: Record<string, unknown> = {}) {+ return {+ autocomplete: false,+ enableFuzzyMatching: false,+ highlightedTokens: [] as string[],+ ...overrides+ } as any;+}++/** Build a NoteSet containing every note currently registered in becca. */+function allNotesSet() {+ return new NoteSet(Object.values(becca.notes));+}++function execute(exp: NoteFlatTextExp, ctx = searchContext(), inputNoteSet = allNotesSet()) {+ const executionContext = { noteIdToNotePath: {} as Record<string, string[]> };+ const result = exp.execute(inputNoteSet, executionContext, ctx);+ return { result, executionContext };+}++function noteIds(noteSet: NoteSet) {+ return noteSet.notes.map((n) => n.noteId).sort();+}++let rootNote: NoteBuilder;++describe("NoteFlatTextExp", () => {+ beforeEach(() => {+ becca.reset();++ rootNote = new NoteBuilder(new BNote({ noteId: "root", title: "root", type: "text" }));+ new BBranch({+ branchId: "none_root",+ noteId: "root",+ parentNoteId: "none",+ notePosition: 10+ });+ });++ it("normalizes tokens in the constructor (lowercasing and stripping diacritics)", () => {+ const exp = new NoteFlatTextExp(["Café", "HELLO"]);+ expect(exp.tokens).toEqual(["cafe", "hello"]);+ });++ it("matches notes by a title token and records the resolved note path", () => {+ const austria = note("Austria");+ const germany = note("Germany");+ rootNote.child(austria).child(germany);++ const exp = new NoteFlatTextExp(["austria"]);+ const { result, executionContext } = execute(exp);++ expect(noteIds(result)).toEqual([austria.note.noteId]);+ // The path is recorded for the matched note and ends at that note.+ const recordedPath = executionContext.noteIdToNotePath[austria.note.noteId];+ expect(recordedPath[recordedPath.length - 1]).toBe(austria.note.noteId);+ expect(recordedPath[0]).toBe("root");+ });++ it("returns an empty set when no candidate note contains any token", () => {+ rootNote.child(note("Austria"));++ const { result } = execute(new NoteFlatTextExp(["nonexistenttoken"]));++ expect(result.notes).toHaveLength(0);+ });++ it("requires every token to be matched along the path towards the root", () => {+ // "europe" lives on the parent, "austria" on the child; both tokens together+ // are only satisfied by walking the child's path up to its parent.+ const europe = note("Europe");+ const austria = note("Austria");+ const asia = note("Asia");+ rootNote.child(europe.child(austria)).child(asia);++ const both = new NoteFlatTextExp(["europe", "austria"]);+ expect(noteIds(execute(both).result)).toEqual([austria.note.noteId]);++ // A token that appears on neither the note nor its ancestors yields nothing,+ // even though one of the two tokens does match.+ const partial = new NoteFlatTextExp(["austria", "africa"]);+ expect(execute(partial).result.notes).toHaveLength(0);+ });++ it("matches by attribute name and value", () => {+ const tagged = note("Plain").label("country", "austria");+ rootNote.child(tagged);++ // matches on the label value...+ expect(noteIds(execute(new NoteFlatTextExp(["austria"])).result)).toEqual([+ tagged.note.noteId+ ]);+ // ...and on the label name.+ expect(noteIds(execute(new NoteFlatTextExp(["country"])).result)).toEqual([+ tagged.note.noteId+ ]);+ });++ it("matches by note type and mime", () => {+ const code = note("Snippet", { type: "code", mime: "application/javascript" });+ rootNote.child(code);++ expect(noteIds(execute(new NoteFlatTextExp(["javascript"])).result)).toEqual([+ code.note.noteId+ ]);+ });++ it("finds a note by its noteId for a single token (leaf lookup)", () => {+ const target = note("Hidden Title", { noteId: "abcdef0123" });+ rootNote.child(target);++ const exp = new NoteFlatTextExp(["abcdef0123"]);+ const { result, executionContext } = execute(exp);++ expect(noteIds(result)).toEqual(["abcdef0123"]);+ expect(executionContext.noteIdToNotePath["abcdef0123"]).toBeDefined();+ });++ it("uses the single-token autocomplete fast path", () => {+ const austria = note("Austria");+ const australia = note("Australia");+ rootNote.child(austria).child(australia);++ const exp = new NoteFlatTextExp(["austr"]);+ const { result, executionContext } = execute(exp, searchContext({ autocomplete: true }));++ // Both notes contain "austr" in their flat text, so both are returned and+ // each gets a best note path recorded.+ expect(noteIds(result)).toEqual([australia.note.noteId, austria.note.noteId].sort());+ expect(executionContext.noteIdToNotePath[austria.note.noteId]).toBeDefined();+ expect(executionContext.noteIdToNotePath[australia.note.noteId]).toBeDefined();+ });++ it("does not return duplicate notes when a note is matched via multiple parents", () => {+ const austria = note("Austria");+ const europe = note("Europe");+ const continent = note("Continent");+ // Clone austria under two different parents.+ rootNote.child(europe.child(austria)).child(continent.child(austria));++ const { result } = execute(new NoteFlatTextExp(["austria"]));++ const matches = result.notes.filter((n) => n.noteId === austria.note.noteId);+ expect(matches).toHaveLength(1);+ });++ it("restricts results to notes present in the input note set", () => {+ const austria = note("Austria");+ const australia = note("Australia");+ rootNote.child(austria).child(australia);++ const exp = new NoteFlatTextExp(["austr"]);+ const restricted = new NoteSet([austria.note]);+ const { result } = execute(exp, searchContext(), restricted);++ expect(noteIds(result)).toEqual([austria.note.noteId]);+ });++ it("supports fuzzy matching only when enabled and records the highlighted word", () => {+ const austria = note("Austria");+ rootNote.child(austria);++ // Typo "austira" (>= 4 chars) should not match with fuzzy matching disabled.+ const noFuzzy = new NoteFlatTextExp(["austira"]);+ expect(execute(noFuzzy, searchContext({ enableFuzzyMatching: false })).result.notes)+ .toHaveLength(0);++ // With fuzzy matching enabled it matches and the matched word is tracked.+ const ctx = searchContext({ enableFuzzyMatching: true });+ const fuzzy = new NoteFlatTextExp(["austira"]);+ const { result } = execute(fuzzy, ctx);+ expect(noteIds(result)).toEqual([austria.note.noteId]);+ expect(ctx.highlightedTokens).toContain("austria");+ });++ describe("getNotePath", () => {+ it("throws when the taken path is empty", () => {+ const austria = note("Austria");+ rootNote.child(austria);++ const exp = new NoteFlatTextExp(["austria"]);+ expect(() => exp.getNotePath(austria.note, [])).toThrow(/empty/);+ });++ it("returns the best note path when the taken path is just the note itself", () => {+ const austria = note("Austria");+ rootNote.child(austria);++ const exp = new NoteFlatTextExp(["austria"]);+ const path = exp.getNotePath(austria.note, [austria.note.noteId]);+ expect(path[path.length - 1]).toBe(austria.note.noteId);+ expect(path[0]).toBe("root");+ });++ it("prefixes the best path of the top-most matching note for a longer taken path", () => {+ const europe = note("Europe");+ const austria = note("Austria");+ rootNote.child(europe.child(austria));++ const exp = new NoteFlatTextExp(["europe"]);+ // takenPath: [child, ...] where the first element is the closest-to-root match.+ const path = exp.getNotePath(europe.note, [europe.note.noteId, austria.note.noteId]);+ expect(path[0]).toBe("root");+ expect(path[path.length - 1]).toBe(austria.note.noteId);+ expect(path).toContain(europe.note.noteId);+ });+ });++ describe("getCandidateNotes", () => {+ it("returns notes whose flat text matches at least one token", () => {+ const austria = note("Austria");+ const germany = note("Germany");+ rootNote.child(austria).child(germany);++ const exp = new NoteFlatTextExp(["austria"]);+ const candidates = exp.getCandidateNotes(allNotesSet(), searchContext());++ expect(candidates.map((n) => n.noteId)).toContain(austria.note.noteId);+ expect(candidates.map((n) => n.noteId)).not.toContain(germany.note.noteId);+ });++ it("only considers notes within the supplied note set when it is a subset", () => {+ const austria = note("Austria");+ const australia = note("Australia");+ rootNote.child(austria).child(australia);++ const exp = new NoteFlatTextExp(["austr"]);+ const subset = new NoteSet([australia.note]);+ const candidates = exp.getCandidateNotes(subset, searchContext());++ expect(candidates.map((n) => n.noteId)).toEqual([australia.note.noteId]);+ });+ });+});diff --git a/packages/trilium-core/src/services/search/expressions/ocr_content.spec.ts b/packages/trilium-core/src/services/search/expressions/ocr_content.spec.tsnew file mode 100644index 0000000000..bdce882d41--- /dev/null+++ b/packages/trilium-core/src/services/search/expressions/ocr_content.spec.ts@@ -0,0 +1,210 @@+import { describe, expect, it } from "vitest";++import becca from "../../../becca/becca.js";+import type BNote from "../../../becca/entities/bnote.js";+import { getContext } from "../../context.js";+import noteService from "../../notes.js";+import { getSql } from "../../sql/index.js";+import NoteSet from "../note_set.js";+import SearchContext from "../search_context.js";+import OCRContentExpression from "./ocr_content.js";++/**+ * Wraps a callback in a CLS context. Entity mutations (createNewNote,+ * saveAttachment, setContent) require CLS to be initialised.+ */+function withContext<T>(fn: () => T): T {+ return getContext().init(fn);+}++let counter = 0;++/**+ * Creates a fresh text note under root in the real in-memory DB and sets the+ * textRepresentation of its own blob to the given OCR text. Each call uses a+ * unique title since the fixture DB is shared between the `it()`s in this file.+ */+function createNoteWithOcrText(ocrText: string): BNote {+ counter++;+ const { note } = withContext(() =>+ noteService.createNewNote({+ parentNoteId: "root",+ // Unique content per note: blobs are keyed by content hash, so+ // identical content would make notes share a single blob row.+ content: `image-binary-placeholder-${counter}`,+ title: `ocr-spec-${counter}`,+ type: "image",+ mime: "image/png"+ })+ );++ setTextRepresentationForBlob(note.blobId!, ocrText);++ return note;+}++/**+ * Creates a fresh text note that owns an attachment whose blob carries the+ * given OCR text. The note's own blob is left without any textRepresentation.+ */+function createNoteWithOcrAttachment(ocrText: string): BNote {+ counter++;+ const { note } = withContext(() =>+ noteService.createNewNote({+ parentNoteId: "root",+ title: `ocr-spec-${counter}`,+ content: "<p>no ocr here</p>",+ type: "text"+ })+ );++ const attachment = withContext(() =>+ note.saveAttachment({+ role: "image",+ mime: "image/png",+ title: `ocr-attachment-${counter}`,+ content: `attachment-binary-placeholder-${counter}`+ })+ );++ setTextRepresentationForBlob(attachment.blobId!, ocrText);++ return note;+}++function setTextRepresentationForBlob(blobId: string, textRepresentation: string) {+ getSql().execute("UPDATE blobs SET textRepresentation = ? WHERE blobId = ?", [+ textRepresentation,+ blobId+ ]);+}++/** Build a NoteSet that contains every note currently registered in becca. */+function allNotesSet() {+ return new NoteSet(Object.values(becca.notes));+}++function execute(+ exp: OCRContentExpression,+ inputNoteSet = allNotesSet(),+ searchContext = new SearchContext()+) {+ return exp.execute(inputNoteSet, {}, searchContext);+}++function noteIds(noteSet: NoteSet) {+ return noteSet.notes.map((n) => n.noteId).sort();+}++describe("OCRContentExpression (real DB)", () => {+ it("matches a note whose own blob OCR text contains the token", () => {+ const note = createNoteWithOcrText("Invoice total amount due");++ const exp = new OCRContentExpression(["invoice"]);+ const result = execute(exp);++ expect(result.hasNote(note)).toBe(true);+ });++ it("matches case-insensitively because tokens are stored lowercase by the query", () => {+ // The LIKE pattern uses the token verbatim; SQLite's LIKE is+ // case-insensitive for ASCII, so an upper-case OCR word still matches a+ // lower-case token.+ const note = createNoteWithOcrText("PASSPORT NUMBER 12345");++ const exp = new OCRContentExpression(["passport"]);+ expect(execute(exp).hasNote(note)).toBe(true);+ });++ it("requires every token to be present (AND semantics)", () => {+ const both = createNoteWithOcrText("red apple and green banana");+ const onlyOne = createNoteWithOcrText("red apple only");++ const exp = new OCRContentExpression(["apple", "banana"]);+ const result = execute(exp);++ expect(result.hasNote(both)).toBe(true);+ expect(result.hasNote(onlyOne)).toBe(false);+ });++ it("matches a note via the OCR text of one of its attachments", () => {+ const note = createNoteWithOcrAttachment("Scanned receipt grand total");++ const exp = new OCRContentExpression(["receipt"]);+ const result = execute(exp);++ expect(result.hasNote(note)).toBe(true);+ });++ it("intersects with the input note set, excluding matches outside it", () => {+ const inSet = createNoteWithOcrText("shared keyword alpha");+ const outOfSet = createNoteWithOcrText("shared keyword alpha");++ const exp = new OCRContentExpression(["keyword"]);++ // Restrict the input set to only `inSet`; `outOfSet` carries the same+ // OCR text but must be excluded because it is not in the input set.+ const restricted = new NoteSet([inSet]);+ const result = execute(exp, restricted);++ expect(noteIds(result)).toEqual([inSet.noteId]);+ expect(result.hasNote(outOfSet)).toBe(false);+ });++ it("returns an empty set when no OCR text matches", () => {+ createNoteWithOcrText("totally unrelated content");++ const exp = new OCRContentExpression(["zzznonexistenttokenzzz"]);+ const result = execute(exp);++ expect(result.notes).toHaveLength(0);+ });++ it("returns an empty set for an empty token list without touching the DB", () => {+ const exp = new OCRContentExpression([]);+ const result = execute(exp);++ expect(result.notes).toHaveLength(0);+ });++ it("pushes lowercased tokens longer than 2 chars to highlightedTokens on a hit", () => {+ // OCR text contains both the long token and the short "ab" so the AND+ // query matches; the highlight filter then keeps only the long token.+ createNoteWithOcrText("ab highlighting Demonstration text");++ const searchContext = new SearchContext();+ const exp = new OCRContentExpression(["Demonstration", "ab"]);+ const result = execute(exp, allNotesSet(), searchContext);++ expect(result.notes.length).toBeGreaterThan(0);+ // The long token is lowercased and added; the 2-char token is filtered out.+ expect(searchContext.highlightedTokens).toContain("demonstration");+ expect(searchContext.highlightedTokens).not.toContain("ab");+ });++ it("does not modify highlightedTokens when there is no match", () => {+ const searchContext = new SearchContext();+ const exp = new OCRContentExpression(["definitelymissingtoken"]);+ execute(exp, allNotesSet(), searchContext);++ expect(searchContext.highlightedTokens).toHaveLength(0);+ });++ it("ignores deleted notes and matches against live ones only", () => {+ const note = createNoteWithOcrText("uniquedeletionmarker phrase");++ // Soft-delete the note row directly; findNoteIdsWithMatchingOCR filters+ // on notes.isDeleted = 0.+ getSql().execute("UPDATE notes SET isDeleted = 1 WHERE noteId = ?", [note.noteId]);++ const exp = new OCRContentExpression(["uniquedeletionmarker"]);+ const result = execute(exp);++ expect(result.hasNote(note)).toBe(false);+ });++ it("renders a readable toString with the joined tokens", () => {+ const exp = new OCRContentExpression(["foo", "bar"]);+ expect(exp.toString()).toBe("OCRContent('foo', 'bar')");+ });+});diff --git a/packages/trilium-core/src/services/search/expressions/or.spec.ts b/packages/trilium-core/src/services/search/expressions/or.spec.tsnew file mode 100644index 0000000000..f61abae16f--- /dev/null+++ b/packages/trilium-core/src/services/search/expressions/or.spec.ts@@ -0,0 +1,136 @@+import { beforeEach, describe, expect, it } from "vitest";++import becca from "../../../becca/becca.js";+import type BNote from "../../../becca/entities/bnote.js";+import { note } from "../../../test/becca_mocking.js";+import Expression from "./expression.js";+import NoteSet from "../note_set.js";+import OrExp from "./or.js";+import TrueExp from "./true.js";++// SearchContext-like argument is unused by execute(), so we pass an empty object.+const dummySearchContext = {} as any;++/** A stub expression that records its inputs and returns a predetermined note set. */+class StubExp extends Expression {+ calls: { inputNoteSet: NoteSet }[] = [];++ constructor(private result: NoteSet) {+ super();+ }++ execute(inputNoteSet: NoteSet) {+ this.calls.push({ inputNoteSet });+ return this.result;+ }+}++function noteIds(noteSet: NoteSet) {+ return noteSet.notes.map((n) => n.noteId).sort();+}++let a: BNote;+let b: BNote;+let c: BNote;++describe("OrExp", () => {+ beforeEach(() => {+ becca.reset();++ a = note("A").note;+ b = note("B").note;+ c = note("C").note;+ });++ describe("of()", () => {+ it("returns a TrueExp when there are no sub-expressions", () => {+ expect(OrExp.of([])).toBeInstanceOf(TrueExp);+ });++ it("returns a TrueExp when every sub-expression is falsy", () => {+ // Falsy entries are filtered out, leaving nothing behind.+ expect(OrExp.of([undefined as any, null as any])).toBeInstanceOf(TrueExp);+ });++ it("unwraps to the single sub-expression instead of wrapping it", () => {+ const only = new StubExp(new NoteSet([a]));++ // A lone expression is returned directly (no OrExp wrapper).+ expect(OrExp.of([only])).toBe(only);++ // Falsy entries are dropped first, so a single real expression also unwraps.+ expect(OrExp.of([null as any, only, undefined as any])).toBe(only);+ });++ it("wraps multiple sub-expressions in an OrExp", () => {+ const first = new StubExp(new NoteSet([a]));+ const second = new StubExp(new NoteSet([b]));++ const exp = OrExp.of([first, second]);++ expect(exp).toBeInstanceOf(OrExp);+ expect((exp as OrExp).subExpressions).toEqual([first, second]);+ });++ it("filters falsy entries before deciding how to wrap", () => {+ const first = new StubExp(new NoteSet([a]));+ const second = new StubExp(new NoteSet([b]));++ const exp = OrExp.of([first, null as any, second, undefined as any]);++ expect(exp).toBeInstanceOf(OrExp);+ expect((exp as OrExp).subExpressions).toEqual([first, second]);+ });+ });++ describe("execute()", () => {+ it("returns the union of all sub-expression results", () => {+ const exp = new OrExp([+ new StubExp(new NoteSet([a, b])),+ new StubExp(new NoteSet([b, c]))+ ]);++ const result = exp.execute(new NoteSet([a, b, c]), {}, dummySearchContext);++ // Overlapping note b appears only once (mergeIn de-duplicates).+ expect(noteIds(result)).toEqual([a.noteId, b.noteId, c.noteId].sort());+ });++ it("returns a fresh, empty NoteSet when there are no sub-expressions", () => {+ const input = new NoteSet([a, b, c]);+ const exp = new OrExp([]);++ const result = exp.execute(input, {}, dummySearchContext);++ expect(result).toBeInstanceOf(NoteSet);+ expect(result).not.toBe(input);+ expect(result.notes).toHaveLength(0);+ });++ it("passes the input note set and context through to each sub-expression", () => {+ const first = new StubExp(new NoteSet([a]));+ const second = new StubExp(new NoteSet([b]));+ const input = new NoteSet([a, b, c]);++ new OrExp([first, second]).execute(input, {}, dummySearchContext);++ expect(first.calls).toHaveLength(1);+ expect(first.calls[0].inputNoteSet).toBe(input);+ expect(second.calls).toHaveLength(1);+ expect(second.calls[0].inputNoteSet).toBe(input);+ });++ it("propagates an error thrown by any sub-expression", () => {+ const boom = new (class extends Expression {+ execute(): NoteSet {+ throw new Error("sub-expression failure");+ }+ })();+ const exp = new OrExp([new StubExp(new NoteSet([a])), boom]);++ expect(() => exp.execute(new NoteSet([a]), {}, dummySearchContext)).toThrow(+ "sub-expression failure"+ );+ });+ });+});diff --git a/packages/trilium-core/src/services/search/expressions/order_by_and_limit.spec.ts b/packages/trilium-core/src/services/search/expressions/order_by_and_limit.spec.tsnew file mode 100644index 0000000000..0fb76b524c--- /dev/null+++ b/packages/trilium-core/src/services/search/expressions/order_by_and_limit.spec.ts@@ -0,0 +1,205 @@+import { beforeEach, describe, expect, it } from "vitest";++import becca from "../../../becca/becca.js";+import type BNote from "../../../becca/entities/bnote.js";+import { note } from "../../../test/becca_mocking.js";+import NoteSet from "../note_set.js";+import Expression from "./expression.js";+import OrderByAndLimitExp from "./order_by_and_limit.js";++// SearchContext-like argument is unused by execute(), so we pass an empty object.+const dummySearchContext = {} as any;++/** A subexpression that simply returns the note set it is configured with. */+class StubExpression extends Expression {+ constructor(private result: NoteSet) {+ super();+ }++ execute() {+ return this.result;+ }+}++function run(exp: OrderByAndLimitExp, notes: BNote[]) {+ exp.subExpression = new StubExpression(new NoteSet(notes));+ return exp.execute(new NoteSet(notes), {}, dummySearchContext);+}++/** Build a value extractor keyed off the note title via a lookup table. */+function extractorFor(values: Record<string, number | string | null>) {+ return {+ valueExtractor: {+ extract: (n: BNote) => values[n.title]+ }+ };+}++describe("OrderByAndLimitExp", () => {+ beforeEach(() => {+ becca.reset();+ });++ it("derives smaller/larger comparison signs from the direction", () => {+ const asc = new OrderByAndLimitExp([{ direction: "asc", valueExtractor: { extract: () => 0 } }]);+ const desc = new OrderByAndLimitExp([{ direction: "desc", valueExtractor: { extract: () => 0 } }]);+ const fallback = new OrderByAndLimitExp([{ valueExtractor: { extract: () => 0 } }]);++ // The fields aren't part of the public type, but the constructor sets them.+ expect((asc as any).orderDefinitions[0].smaller).toBe(-1);+ expect((asc as any).orderDefinitions[0].larger).toBe(1);++ // Anything other than "asc" (including missing direction) is treated as descending.+ expect((desc as any).orderDefinitions[0].smaller).toBe(1);+ expect((desc as any).orderDefinitions[0].larger).toBe(-1);+ expect((fallback as any).orderDefinitions[0].smaller).toBe(1);+ expect((fallback as any).orderDefinitions[0].larger).toBe(-1);+ });++ it("defaults the limit to 0 when none is provided", () => {+ expect(new OrderByAndLimitExp([], 5).limit).toBe(5);+ expect(new OrderByAndLimitExp([]).limit).toBe(0);+ });++ it("throws when executed without a subexpression", () => {+ const exp = new OrderByAndLimitExp([{ direction: "asc", valueExtractor: { extract: () => 0 } }]);+ expect(() => exp.execute(new NoteSet([]), {}, dummySearchContext)).toThrow("Missing subexpression");+ });++ it("returns a sorted note set flagged as sorted (defaulting to descending order)", () => {+ const a = note("A").note;+ const b = note("B").note;+ // No direction => treated as descending, so the larger value comes first.+ const exp = new OrderByAndLimitExp([extractorFor({ A: 2, B: 1 })]);++ const result = run(exp, [a, b]);++ expect(result.sorted).toBe(true);+ expect(result.notes.map((n) => n.title)).toEqual(["A", "B"]);+ });++ it("sorts ascending and descending numeric values", () => {+ const a = note("A").note;+ const b = note("B").note;+ const c = note("C").note;+ const values = { A: 3, B: 1, C: 2 };++ const asc = new OrderByAndLimitExp([{ direction: "asc", valueExtractor: { extract: (n) => values[n.title as keyof typeof values] } }]);+ expect(run(asc, [a, b, c]).notes.map((n) => n.title)).toEqual(["B", "C", "A"]);++ const desc = new OrderByAndLimitExp([{ direction: "desc", valueExtractor: { extract: (n) => values[n.title as keyof typeof values] } }]);+ expect(run(desc, [a, b, c]).notes.map((n) => n.title)).toEqual(["A", "C", "B"]);+ });++ it("parses numeric strings for numerical (not lexicographic) comparison", () => {+ const a = note("A").note;+ const b = note("B").note;+ // Lexicographically "10" < "9", but numerically 9 < 10.+ const exp = new OrderByAndLimitExp([{ direction: "asc", valueExtractor: { extract: (n) => (n.title === "A" ? "10" : "9") } }]);++ expect(run(exp, [a, b]).notes.map((n) => n.title)).toEqual(["B", "A"]);+ });++ it("parses date strings for chronological comparison", () => {+ const a = note("A").note;+ const b = note("B").note;+ const exp = new OrderByAndLimitExp([{ direction: "asc", valueExtractor: { extract: (n) => (n.title === "A" ? "2024-12-31" : "2020-01-01") } }]);++ expect(run(exp, [a, b]).notes.map((n) => n.title)).toEqual(["B", "A"]);+ });++ it("sorts a null value last when ascending and first when descending", () => {+ const a = note("A").note;+ const b = note("B").note;+ const c = note("C").note;++ // A has no value (null). Ascending pushes null to the bottom...+ const asc = new OrderByAndLimitExp([{ direction: "asc", valueExtractor: { extract: (n) => ({ A: null, B: 1, C: 2 } as Record<string, number | null>)[n.title] } }]);+ expect(run(asc, [a, b, c]).notes.map((n) => n.title)).toEqual(["B", "C", "A"]);++ // ...while descending pulls null to the top.+ const desc = new OrderByAndLimitExp([{ direction: "desc", valueExtractor: { extract: (n) => ({ A: null, B: 1, C: 2 } as Record<string, number | null>)[n.title] } }]);+ expect(run(desc, [a, b, c]).notes.map((n) => n.title)).toEqual(["A", "C", "B"]);+ });++ it("treats undefined the same as null and keeps both null-valued notes' relative order", () => {+ const a = note("A").note;+ const b = note("B").note;+ // valueExtractor returns undefined for unknown titles; both are missing.+ const exp = new OrderByAndLimitExp([{ direction: "asc", valueExtractor: { extract: () => undefined as any } }]);++ // When both values are null, the comparator returns 0 and the original order is preserved.+ expect(run(exp, [a, b]).notes.map((n) => n.title)).toEqual(["A", "B"]);+ });++ it("falls through to the next order definition when the first compares equal", () => {+ const a = note("A").note;+ const b = note("B").note;+ const c = note("C").note;++ const primary = { A: 1, B: 1, C: 2 };+ const secondary = { A: 20, B: 10, C: 5 };++ const exp = new OrderByAndLimitExp([+ { direction: "asc", valueExtractor: { extract: (n) => primary[n.title as keyof typeof primary] } },+ { direction: "asc", valueExtractor: { extract: (n) => secondary[n.title as keyof typeof secondary] } }+ ]);++ // A and B tie on the primary key (1), broken by the secondary key: B(10) before A(20). C has primary 2 last.+ expect(run(exp, [a, b, c]).notes.map((n) => n.title)).toEqual(["B", "A", "C"]);+ });++ it("continues to the next order definition when both values are empty/zero", () => {+ const a = note("A").note;+ const b = note("B").note;++ // Both have 0 on the primary key (falsy -> continue), broken by the secondary key.+ const exp = new OrderByAndLimitExp([+ { direction: "asc", valueExtractor: { extract: () => 0 } },+ { direction: "asc", valueExtractor: { extract: (n) => (n.title === "A" ? 2 : 1) } }+ ]);++ expect(run(exp, [a, b]).notes.map((n) => n.title)).toEqual(["B", "A"]);+ });++ it("applies the limit by slicing the sorted result", () => {+ const a = note("A").note;+ const b = note("B").note;+ const c = note("C").note;+ const values = { A: 3, B: 1, C: 2 };++ const exp = new OrderByAndLimitExp([{ direction: "asc", valueExtractor: { extract: (n) => values[n.title as keyof typeof values] } }], 2);++ // Sorted ascending => B, C, A; limit 2 keeps the first two.+ expect(run(exp, [a, b, c]).notes.map((n) => n.title)).toEqual(["B", "C"]);+ });++ it("does not slice when the limit is zero", () => {+ const a = note("A").note;+ const b = note("B").note;+ const c = note("C").note;+ const exp = new OrderByAndLimitExp([{ direction: "asc", valueExtractor: { extract: () => 0 } }]);++ expect(run(exp, [a, b, c]).notes).toHaveLength(3);+ });++ describe("isDate", () => {+ it("recognises parseable dates and rejects garbage", () => {+ const exp = new OrderByAndLimitExp([]);+ expect(exp.isDate("2024-01-01")).toBe(true);+ expect(exp.isDate("not-a-date")).toBe(false);+ });+ });++ describe("isNumber", () => {+ it("recognises numbers and numeric strings, rejecting blanks and words", () => {+ const exp = new OrderByAndLimitExp([]);+ expect(exp.isNumber(42)).toBe(true);+ expect(exp.isNumber("42")).toBe(true);+ expect(exp.isNumber("3.14")).toBe(true);+ expect(exp.isNumber("")).toBe(false);+ expect(exp.isNumber(" ")).toBe(false);+ expect(exp.isNumber("abc")).toBe(false);+ });+ });+});diff --git a/packages/trilium-core/src/services/search/expressions/parent_of.spec.ts b/packages/trilium-core/src/services/search/expressions/parent_of.spec.tsnew file mode 100644index 0000000000..7df8215cd8--- /dev/null+++ b/packages/trilium-core/src/services/search/expressions/parent_of.spec.ts@@ -0,0 +1,166 @@+import { beforeEach, describe, expect, it } from "vitest";++import becca from "../../../becca/becca.js";+import BBranch from "../../../becca/entities/bbranch.js";+import BNote from "../../../becca/entities/bnote.js";+import { note, NoteBuilder } from "../../../test/becca_mocking.js";+import Expression from "./expression.js";+import NoteSet from "../note_set.js";+import ParentOfExp from "./parent_of.js";++// SearchContext-like argument is unused by execute(), so we pass an empty object.+const dummySearchContext = {} as any;++/** A stub sub-expression: records the note set it receives and returns a fixed result. */+class StubExp extends Expression {+ calls: NoteSet[] = [];++ constructor(private result: NoteSet) {+ super();+ }++ execute(inputNoteSet: NoteSet) {+ this.calls.push(inputNoteSet);+ return this.result;+ }+}++function noteIds(noteSet: NoteSet) {+ return noteSet.notes.map((n) => n.noteId).sort();+}++let rootNote: NoteBuilder;++describe("ParentOfExp", () => {+ beforeEach(() => {+ becca.reset();++ rootNote = new NoteBuilder(new BNote({ noteId: "root", title: "root", type: "text" }));+ new BBranch({+ branchId: "none_root",+ noteId: "root",+ parentNoteId: "none",+ notePosition: 10+ });+ });++ it("returns the parents of the notes matched by the sub-expression", () => {+ const parent = note("Parent");+ const child = note("Child");+ parent.child(child);+ rootNote.child(parent);++ // The sub-expression matches the child; the result should be its parent.+ const sub = new StubExp(new NoteSet([child.note]));+ const exp = new ParentOfExp(sub);++ const input = new NoteSet([rootNote.note, parent.note, child.note]);+ expect(noteIds(exp.execute(input, {}, dummySearchContext))).toEqual([+ parent.note.noteId+ ]);+ });++ it("feeds the sub-expression a note set of all children of the input notes", () => {+ const parent = note("Parent");+ const childA = note("ChildA");+ const childB = note("ChildB");+ parent.child(childA).child(childB);+ rootNote.child(parent);++ const sub = new StubExp(new NoteSet());+ const exp = new ParentOfExp(sub);++ exp.execute(new NoteSet([parent.note]), {}, dummySearchContext);++ // The sub-expression must have been called once with both children.+ expect(sub.calls).toHaveLength(1);+ expect(noteIds(sub.calls[0])).toEqual([childA.note.noteId, childB.note.noteId].sort());+ });++ it("excludes a parent that is not present in the input note set", () => {+ const parent = note("Parent");+ const child = note("Child");+ parent.child(child);+ rootNote.child(parent);++ // The matched child's parent exists, but it is filtered out because the input+ // set does not contain it.+ const sub = new StubExp(new NoteSet([child.note]));+ const exp = new ParentOfExp(sub);++ const input = new NoteSet([rootNote.note, child.note]);+ expect(exp.execute(input, {}, dummySearchContext).notes).toHaveLength(0);+ });++ it("returns only the input-set parents for a cloned (multi-parent) child", () => {+ const parentA = note("ParentA");+ const parentB = note("ParentB");+ const child = note("Child");+ parentA.child(child);+ parentB.child(child);+ rootNote.child(parentA).child(parentB);++ const sub = new StubExp(new NoteSet([child.note]));+ const exp = new ParentOfExp(sub);++ // Both parents match, but only the one present in the input set is returned.+ const input = new NoteSet([parentA.note, child.note]);+ expect(noteIds(exp.execute(input, {}, dummySearchContext))).toEqual([+ parentA.note.noteId+ ]);++ // With both parents in the input, both are returned.+ const inputBoth = new NoteSet([parentA.note, parentB.note, child.note]);+ expect(noteIds(exp.execute(inputBoth, {}, dummySearchContext))).toEqual(+ [parentA.note.noteId, parentB.note.noteId].sort()+ );+ });++ it("de-duplicates a parent that has several matching children", () => {+ const parent = note("Parent");+ const childA = note("ChildA");+ const childB = note("ChildB");+ parent.child(childA).child(childB);+ rootNote.child(parent);++ // Both children match; the shared parent must appear exactly once.+ const sub = new StubExp(new NoteSet([childA.note, childB.note]));+ const exp = new ParentOfExp(sub);++ const result = exp.execute(new NoteSet([parent.note]), {}, dummySearchContext);+ expect(noteIds(result)).toEqual([parent.note.noteId]);+ expect(result.notes).toHaveLength(1);+ });++ it("returns an empty set when the sub-expression matches nothing", () => {+ const parent = note("Parent");+ const child = note("Child");+ parent.child(child);+ rootNote.child(parent);++ const sub = new StubExp(new NoteSet());+ const exp = new ParentOfExp(sub);++ const result = exp.execute(new NoteSet([parent.note, child.note]), {}, dummySearchContext);+ expect(result).toBeInstanceOf(NoteSet);+ expect(result.notes).toHaveLength(0);+ });++ it("propagates an error thrown by the sub-expression", () => {+ const parent = note("Parent");+ const child = note("Child");+ parent.child(child);+ rootNote.child(parent);++ const boom = new (class extends Expression {+ execute(): NoteSet {+ throw new Error("sub-expression failure");+ }+ })();+ const exp = new ParentOfExp(boom);++ expect(() => exp.execute(new NoteSet([parent.note]), {}, dummySearchContext)).toThrow(+ "sub-expression failure"+ );+ });+});diff --git a/packages/trilium-core/src/services/search/expressions/property_comparison.spec.ts b/packages/trilium-core/src/services/search/expressions/property_comparison.spec.tsnew file mode 100644index 0000000000..455dc0dee5--- /dev/null+++ b/packages/trilium-core/src/services/search/expressions/property_comparison.spec.ts@@ -0,0 +1,189 @@+import { beforeEach, describe, expect, it } from "vitest";++import becca from "../../../becca/becca.js";+import BBranch from "../../../becca/entities/bbranch.js";+import BNote from "../../../becca/entities/bnote.js";+import { note, NoteBuilder } from "../../../test/becca_mocking.js";+import NoteSet from "../note_set.js";+import PropertyComparisonExp from "./property_comparison.js";++/** Build a NoteSet that contains every note currently registered in becca. */+function allNotesSet() {+ return new NoteSet(Object.values(becca.notes));+}++function execute(exp: PropertyComparisonExp, searchContext: any = {}, inputNoteSet = allNotesSet()) {+ return exp.execute(inputNoteSet, {}, searchContext);+}++function noteIds(noteSet: NoteSet) {+ return noteSet.notes.map((n) => n.noteId).sort();+}++let rootNote: NoteBuilder;++describe("PropertyComparisonExp", () => {+ beforeEach(() => {+ becca.reset();++ rootNote = new NoteBuilder(new BNote({ noteId: "root", title: "root", type: "text" }));+ new BBranch({+ branchId: "none_root",+ noteId: "root",+ parentNoteId: "none",+ notePosition: 10+ });+ });++ describe("isProperty", () => {+ it("recognises known (lower-cased) property names", () => {+ expect(PropertyComparisonExp.isProperty("title")).toBe(true);+ expect(PropertyComparisonExp.isProperty("noteid")).toBe(true);+ expect(PropertyComparisonExp.isProperty("childrencount")).toBe(true);+ expect(PropertyComparisonExp.isProperty("contentsize")).toBe(true);+ });++ it("rejects unknown or wrongly-cased names", () => {+ expect(PropertyComparisonExp.isProperty("noteId")).toBe(false);+ expect(PropertyComparisonExp.isProperty("bogus")).toBe(false);+ expect(PropertyComparisonExp.isProperty("")).toBe(false);+ });+ });++ describe("constructor", () => {+ it("maps the lower-cased property name to its case-sensitive form", () => {+ const exp = new PropertyComparisonExp({}, "datecreated", "=", "x");+ expect(exp.propertyName).toBe("dateCreated");+ expect(exp.operator).toBe("=");+ expect(exp.comparedValue).toBe("x");+ });++ it("does not flag dbLoadNeeded for non-DB-backed properties", () => {+ const searchContext: any = {};+ new PropertyComparisonExp(searchContext, "title", "=", "hello");+ expect(searchContext.dbLoadNeeded).toBeUndefined();+ });++ it("leaves dbLoadNeeded unset for DB-backed properties (mapped name never matches the lower-cased guard)", () => {+ // The guard compares the already case-mapped propertyName ("contentSize") against+ // a list of lower-cased names ("contentsize"), so it can never match - dbLoadNeeded+ // is therefore never set here. This locks in the current observed behaviour.+ for (const prop of [+ "contentsize",+ "contentandattachmentssize",+ "contentandattachmentsandrevisionssize",+ "revisioncount"+ ]) {+ const searchContext: any = {};+ new PropertyComparisonExp(searchContext, prop, ">", "0");+ expect(searchContext.dbLoadNeeded).toBeUndefined();+ }+ });+ });++ describe("execute", () => {+ it("matches notes by an exact string property (case-insensitive)", () => {+ const code = note("Code", { type: "code" });+ const text = note("Text", { type: "text" });+ rootNote.child(code).child(text);++ const exp = new PropertyComparisonExp({}, "type", "=", "code");+ expect(noteIds(execute(exp))).toEqual([code.note.noteId]);+ });++ it("compares the title case-insensitively via the lower-cased value", () => {+ const austria = note("Austria");+ rootNote.child(austria);++ // The note's title "Austria" is lower-cased before comparison, and the comparator+ // also lower-cases its target, so a mixed-case search term still matches.+ const exp = new PropertyComparisonExp({}, "title", "=", "Austria");+ expect(noteIds(execute(exp))).toEqual([austria.note.noteId]);+ });++ it("supports substring operators on string properties", () => {+ const aaa = note("Apple");+ const bbb = note("Grape");+ rootNote.child(aaa).child(bbb);++ const startsWith = new PropertyComparisonExp({}, "title", "=*", "app");+ expect(noteIds(execute(startsWith))).toEqual([aaa.note.noteId]);++ const contains = new PropertyComparisonExp({}, "title", "*=*", "rap");+ expect(noteIds(execute(contains))).toEqual([bbb.note.noteId]);+ });++ it("stringifies and lower-cases non-string property values before comparing", () => {+ // childrenCount is a number; parent has two children, leaves have zero.+ const childA = note("ChildA");+ const childB = note("ChildB");+ const parent = note("Parent");+ parent.child(childA).child(childB);+ rootNote.child(parent);++ const hasTwoChildren = new PropertyComparisonExp({}, "childrencount", "=", "2");+ expect(noteIds(execute(hasTwoChildren))).toEqual([parent.note.noteId]);+ });++ it("supports numeric comparison operators on numeric properties", () => {+ const childA = note("ChildA");+ const childB = note("ChildB");+ const parent = note("Parent");+ parent.child(childA).child(childB);+ rootNote.child(parent);++ // childrenCount > 0 should match the parent (2) and root (1), excluding the leaves.+ const exp = new PropertyComparisonExp({}, "childrencount", ">", "0");+ expect(noteIds(execute(exp))).toEqual(+ [rootNote.note.noteId, parent.note.noteId].sort()+ );+ });++ it("treats a falsy (zero) numeric value as an empty value for the comparator", () => {+ // A leaf note has childrenCount === 0. Because execute() only lower-cases truthy+ // values, the stringified "0" stays "0" and the numeric comparator parses it.+ const leaf = note("Leaf");+ rootNote.child(leaf);++ const exp = new PropertyComparisonExp({}, "childrencount", "<", "1");+ expect(noteIds(execute(exp))).toContain(leaf.note.noteId);+ expect(execute(exp).notes.map((n) => n.noteId)).not.toContain(rootNote.note.noteId);+ });++ it("returns an empty set when nothing satisfies the comparator", () => {+ const austria = note("Austria");+ rootNote.child(austria);++ const exp = new PropertyComparisonExp({}, "type", "=", "image");+ expect(execute(exp).notes).toHaveLength(0);+ });++ it("only considers notes present in the input note set", () => {+ const codeA = note("CodeA", { type: "code" });+ const codeB = note("CodeB", { type: "code" });+ rootNote.child(codeA).child(codeB);++ const exp = new PropertyComparisonExp({}, "type", "=", "code");+ const restricted = new NoteSet([codeA.note]);+ expect(noteIds(execute(exp, {}, restricted))).toEqual([codeA.note.noteId]);+ });++ it("returns an empty set when the operator is unknown (no comparator built)", () => {+ const austria = note("Austria");+ rootNote.child(austria);++ // buildComparator returns undefined for an unsupported operator, so execute() never+ // adds any note.+ const exp = new PropertyComparisonExp({}, "title", "??", "Austria");+ expect(execute(exp).notes).toHaveLength(0);+ });++ it("matches on noteId, mapping the lower-cased 'noteid' to the real property", () => {+ const target = note("Target");+ rootNote.child(target);++ const exp = new PropertyComparisonExp({}, "noteid", "=", target.note.noteId);+ expect(noteIds(execute(exp))).toEqual([target.note.noteId]);+ });+ });+});diff --git a/packages/trilium-core/src/services/search/expressions/relation_where.spec.ts b/packages/trilium-core/src/services/search/expressions/relation_where.spec.tsnew file mode 100644index 0000000000..ebfaa43a9e--- /dev/null+++ b/packages/trilium-core/src/services/search/expressions/relation_where.spec.ts@@ -0,0 +1,197 @@+import { beforeEach, describe, expect, it } from "vitest";++import becca from "../../../becca/becca.js";+import BAttribute from "../../../becca/entities/battribute.js";+import BBranch from "../../../becca/entities/bbranch.js";+import BNote from "../../../becca/entities/bnote.js";+import { id, note, NoteBuilder } from "../../../test/becca_mocking.js";+import Expression from "./expression.js";+import NoteSet from "../note_set.js";+import RelationWhereExp from "./relation_where.js";++// SearchContext-like argument is unused by execute(), so we pass an empty object.+const dummySearchContext = {} as any;++/** Build a NoteSet that contains every note currently registered in becca. */+function allNotesSet() {+ return new NoteSet(Object.values(becca.notes));+}++function execute(exp: RelationWhereExp, inputNoteSet = allNotesSet()) {+ return exp.execute(inputNoteSet, {}, dummySearchContext);+}++function noteIds(noteSet: NoteSet) {+ return noteSet.notes.map((n) => n.noteId).sort();+}++/**+ * A sub-expression stub that returns its input note set unchanged when `matches`+ * is true, and an empty set otherwise. RelationWhereExp keeps a relation's source+ * note when the sub-result still contains the relation's target note, so returning+ * the input verbatim simulates a "matching" sub-condition.+ */+class StubExp extends Expression {+ constructor(+ private matches: boolean,+ public received: NoteSet[] = []+ ) {+ super();+ }++ execute(inputNoteSet: NoteSet) {+ this.received.push(inputNoteSet);+ return this.matches ? inputNoteSet : new NoteSet();+ }+}++const matchAll = () => new StubExp(true);+const matchNone = () => new StubExp(false);++let rootNote: NoteBuilder;++describe("RelationWhereExp", () => {+ beforeEach(() => {+ becca.reset();++ rootNote = new NoteBuilder(new BNote({ noteId: "root", title: "root", type: "text" }));+ new BBranch({+ branchId: "none_root",+ noteId: "root",+ parentNoteId: "none",+ notePosition: 10+ });+ });++ it("keeps the source note when the sub-expression matches the relation target", () => {+ const target = note("Target");+ const source = note("Source").relation("author", target.note);+ rootNote.child(target).child(source);++ const exp = new RelationWhereExp("author", matchAll());+ expect(noteIds(execute(exp))).toEqual([source.note.noteId]);+ });++ it("drops the source note when the sub-expression rejects the relation target", () => {+ const target = note("Target");+ const source = note("Source").relation("author", target.note);+ rootNote.child(target).child(source);++ const exp = new RelationWhereExp("author", matchNone());+ expect(execute(exp).notes).toHaveLength(0);+ });++ it("runs the sub-expression against a note set containing only the relation target", () => {+ const target = note("Target");+ const source = note("Source").relation("author", target.note);+ rootNote.child(target).child(source);++ const stub = matchAll();+ new RelationWhereExp("author", stub).execute(allNotesSet(), {}, dummySearchContext);++ expect(stub.received).toHaveLength(1);+ expect(noteIds(stub.received[0])).toEqual([target.note.noteId]);+ });++ it("considers only relations with the requested name", () => {+ const target = note("Target");+ const author = note("Author").relation("author", target.note);+ const editor = note("Editor").relation("editor", target.note);+ rootNote.child(target).child(author).child(editor);++ const exp = new RelationWhereExp("author", matchAll());+ expect(noteIds(execute(exp))).toEqual([author.note.noteId]);+ });++ it("ignores labels that share the relation's name", () => {+ const target = note("Target");+ const withRelation = note("WithRelation").relation("ref", target.note);+ const withLabel = note("WithLabel").label("ref", target.note.noteId);+ rootNote.child(target).child(withRelation).child(withLabel);++ const exp = new RelationWhereExp("ref", matchAll());+ expect(noteIds(execute(exp))).toEqual([withRelation.note.noteId]);+ });++ it("only keeps source notes that are present in the input note set", () => {+ const target = note("Target");+ const inSet = note("InSet").relation("author", target.note);+ const outOfSet = note("OutOfSet").relation("author", target.note);+ rootNote.child(target).child(inSet).child(outOfSet);++ const exp = new RelationWhereExp("author", matchAll());++ // Restrict the input to the target plus only one of the two source notes;+ // the source that is absent from the input must be excluded.+ const restricted = new NoteSet([target.note, inSet.note]);+ expect(noteIds(execute(exp, restricted))).toEqual([inSet.note.noteId]);+ });++ it("skips relations whose target note no longer exists", () => {+ const source = note("Source").relation("author", note("Ghost").note);+ // Build the relation against a note that is never attached to the tree and+ // then remove it from becca so attr.targetNote resolves to undefined.+ const ghostId = source.note.getRelationValue("author")!;+ delete becca.notes[ghostId];+ rootNote.child(source);++ const exp = new RelationWhereExp("author", matchAll());+ expect(execute(exp).notes).toHaveLength(0);+ });++ it("returns an empty set when no relation with that name exists", () => {+ const lonely = note("Lonely");+ rootNote.child(lonely);++ const exp = new RelationWhereExp("author", matchAll());+ expect(execute(exp).notes).toHaveLength(0);+ });++ it("expands an inheritable relation to the whole subtree of the source", () => {+ const target = note("Target");+ const parent = note("Parent");+ // The mocking `relation()` helper always creates a non-inheritable attribute,+ // so build the inheritable relation directly (the BAttribute constructor+ // registers in becca without a persisting save() that needs CLS).+ new BAttribute({+ attributeId: id(),+ noteId: parent.note.noteId,+ type: "relation",+ name: "author",+ value: target.note.noteId,+ isInheritable: true+ });+ const child = note("Child");+ const grandchild = note("Grandchild");+ parent.child(child.child(grandchild));+ rootNote.child(target).child(parent);++ const exp = new RelationWhereExp("author", matchAll());+ expect(noteIds(execute(exp))).toEqual(+ [parent.note.noteId, child.note.noteId, grandchild.note.noteId].sort()+ );+ });++ it("expands to inheriting notes when the source is used as a template", () => {+ const target = note("Target");+ // The source carries the matched relation and is also a template target,+ // so isInherited() is true and getInheritingNotes() is used.+ const source = note("Source").relation("author", target.note);+ const consumer = note("Consumer").relation("template", source.note);+ rootNote.child(target).child(source).child(consumer);++ const exp = new RelationWhereExp("author", matchAll());+ expect(noteIds(execute(exp))).toEqual(+ [source.note.noteId, consumer.note.noteId].sort()+ );+ });++ it("adds only the source note when the relation is neither inheritable nor inherited", () => {+ const target = note("Target");+ const source = note("Source").relation("author", target.note);+ rootNote.child(target).child(source);++ const exp = new RelationWhereExp("author", matchAll());+ expect(noteIds(execute(exp))).toEqual([source.note.noteId]);+ });+});diff --git a/packages/trilium-core/src/services/search/expressions/true.spec.ts b/packages/trilium-core/src/services/search/expressions/true.spec.tsnew file mode 100644index 0000000000..a7feec7dd2--- /dev/null+++ b/packages/trilium-core/src/services/search/expressions/true.spec.ts@@ -0,0 +1,51 @@+import { beforeEach, describe, expect, it } from "vitest";++import becca from "../../../becca/becca.js";+import type BNote from "../../../becca/entities/bnote.js";+import { note } from "../../../test/becca_mocking.js";+import Expression from "./expression.js";+import NoteSet from "../note_set.js";+import TrueExp from "./true.js";++// SearchContext-like argument is unused by execute(), so we pass an empty object.+const dummySearchContext = {} as any;++let a: BNote;+let b: BNote;++describe("TrueExp", () => {+ beforeEach(() => {+ becca.reset();++ a = note("A").note;+ b = note("B").note;+ });++ it("is an Expression with the constructor name as its name", () => {+ const exp = new TrueExp();++ expect(exp).toBeInstanceOf(Expression);+ expect(exp.name).toBe("TrueExp");+ });++ it("returns the exact same note set instance it was given", () => {+ const exp = new TrueExp();+ const input = new NoteSet([a, b]);++ const result = exp.execute(input, {}, dummySearchContext);++ // Identity passthrough: same reference, same contents, nothing mutated.+ expect(result).toBe(input);+ expect(result.notes).toEqual([a, b]);+ });++ it("passes through an empty note set unchanged", () => {+ const exp = new TrueExp();+ const input = new NoteSet();++ const result = exp.execute(input, {}, dummySearchContext);++ expect(result).toBe(input);+ expect(result.notes).toHaveLength(0);+ });+});diff --git a/packages/trilium-core/src/services/search/note_set.spec.ts b/packages/trilium-core/src/services/search/note_set.spec.tsnew file mode 100644index 0000000000..c23c1139d2--- /dev/null+++ b/packages/trilium-core/src/services/search/note_set.spec.ts@@ -0,0 +1,170 @@+import { beforeEach, describe, expect, it } from "vitest";++import becca from "../../becca/becca.js";+import BNote from "../../becca/entities/bnote.js";+import { buildNote } from "../../test/becca_easy_mocking.js";+import NoteSet from "./note_set.js";++describe("NoteSet", () => {+ let a: BNote;+ let b: BNote;+ let c: BNote;++ beforeEach(() => {+ becca.reset();+ a = buildNote({ id: "a", title: "A" });+ b = buildNote({ id: "b", title: "B" });+ c = buildNote({ id: "c", title: "C" });+ });++ describe("constructor", () => {+ it("defaults to an empty, unsorted set", () => {+ const set = new NoteSet();++ expect(set.notes).toEqual([]);+ expect(set.sorted).toBe(false);+ expect(set.hasNoteId("a")).toBe(false);+ });++ it("seeds notes and indexes their ids", () => {+ const set = new NoteSet([a, b]);++ expect(set.notes).toEqual([a, b]);+ expect(set.hasNote(a)).toBe(true);+ expect(set.hasNote(b)).toBe(true);+ expect(set.hasNote(c)).toBe(false);+ expect(set.hasNoteId("a")).toBe(true);+ expect(set.hasNoteId("missing")).toBe(false);+ });+ });++ describe("add", () => {+ it("adds a new note and indexes its id", () => {+ const set = new NoteSet();++ set.add(a);++ expect(set.notes).toEqual([a]);+ expect(set.hasNote(a)).toBe(true);+ expect(set.hasNoteId("a")).toBe(true);+ });++ it("ignores a note whose id is already present (deduplicates)", () => {+ const set = new NoteSet([a]);+ // distinct BNote instance sharing the same noteId+ const aDuplicate = buildNote({ id: "a", title: "A again" });++ set.add(a);+ set.add(aDuplicate);++ expect(set.notes).toEqual([a]);+ expect(set.notes).toHaveLength(1);+ });+ });++ describe("addAll", () => {+ it("adds every note while deduplicating against existing ids", () => {+ const set = new NoteSet([a]);++ set.addAll([a, b, c]);++ expect(set.notes).toEqual([a, b, c]);+ });++ it("is a no-op for an empty array", () => {+ const set = new NoteSet([a]);++ set.addAll([]);++ expect(set.notes).toEqual([a]);+ });+ });++ describe("hasNote / hasNoteId", () => {+ it("reports membership by note and by id consistently", () => {+ const set = new NoteSet([a]);++ expect(set.hasNote(a)).toBe(true);+ expect(set.hasNoteId("a")).toBe(true);+ expect(set.hasNote(b)).toBe(false);+ expect(set.hasNoteId("b")).toBe(false);+ });+ });++ describe("mergeIn", () => {+ it("absorbs all notes from another set, deduplicating overlaps", () => {+ const set = new NoteSet([a, b]);+ const other = new NoteSet([b, c]);++ set.mergeIn(other);++ expect(set.notes).toEqual([a, b, c]);+ // the source set is left untouched+ expect(other.notes).toEqual([b, c]);+ });++ it("merging an empty set changes nothing", () => {+ const set = new NoteSet([a]);++ set.mergeIn(new NoteSet());++ expect(set.notes).toEqual([a]);+ });+ });++ describe("minus", () => {+ it("returns a new set of notes not present in the other set", () => {+ const set = new NoteSet([a, b, c]);+ const other = new NoteSet([b]);++ const result = set.minus(other);++ expect(result).toBeInstanceOf(NoteSet);+ expect(result.notes).toEqual([a, c]);+ // operands are not mutated+ expect(set.notes).toEqual([a, b, c]);+ expect(other.notes).toEqual([b]);+ });++ it("returns all notes when subtracting an empty set", () => {+ const set = new NoteSet([a, b]);++ expect(set.minus(new NoteSet()).notes).toEqual([a, b]);+ });++ it("returns an empty set when every note is removed", () => {+ const set = new NoteSet([a, b]);+ const other = new NoteSet([a, b, c]);++ expect(set.minus(other).notes).toEqual([]);+ });+ });++ describe("intersection", () => {+ it("returns a new set of notes present in both sets", () => {+ const set = new NoteSet([a, b, c]);+ const other = new NoteSet([b, c]);++ const result = set.intersection(other);++ expect(result).toBeInstanceOf(NoteSet);+ expect(result.notes).toEqual([b, c]);+ // operands are not mutated+ expect(set.notes).toEqual([a, b, c]);+ expect(other.notes).toEqual([b, c]);+ });++ it("returns an empty set when there is no overlap", () => {+ const set = new NoteSet([a]);+ const other = new NoteSet([b]);++ expect(set.intersection(other).notes).toEqual([]);+ });++ it("intersecting with an empty set yields an empty set", () => {+ const set = new NoteSet([a, b]);++ expect(set.intersection(new NoteSet()).notes).toEqual([]);+ });+ });+});diff --git a/packages/trilium-core/src/services/search/search_context.spec.ts b/packages/trilium-core/src/services/search/search_context.spec.tsnew file mode 100644index 0000000000..71921a5f35--- /dev/null+++ b/packages/trilium-core/src/services/search/search_context.spec.ts@@ -0,0 +1,132 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import hoistedNoteService from "../hoisted_note.js";+import optionService from "../options.js";+import SearchContext from "./search_context.js";++let getHoistedNoteId: ReturnType<typeof vi.spyOn>;+let getOptionBool: ReturnType<typeof vi.spyOn>;++describe("SearchContext", () => {+ beforeEach(() => {+ getHoistedNoteId = vi.spyOn(hoistedNoteService, "getHoistedNoteId").mockReturnValue("root");+ getOptionBool = vi.spyOn(optionService, "getOptionBool").mockReturnValue(true);+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ it("defaults every flag to false / empty when constructed without params", () => {+ const ctx = new SearchContext();++ expect(ctx.fastSearch).toBe(false);+ expect(ctx.includeArchivedNotes).toBe(false);+ expect(ctx.includeHiddenNotes).toBe(false);+ expect(ctx.ignoreHoistedNote).toBe(false);+ expect(ctx.ignoreInternalAttributes).toBe(false);+ expect(ctx.fuzzyAttributeSearch).toBe(false);+ expect(ctx.autocomplete).toBe(false);+ expect(ctx.highlightedTokens).toEqual([]);+ expect(ctx.originalQuery).toBe("");+ expect(ctx.fulltextQuery).toBe("");+ expect(ctx.dbLoadNeeded).toBe(false);+ expect(ctx.debugInfo).toBeNull();+ expect(ctx.error).toBeNull();+ });++ it("coerces truthy/falsy param values into strict booleans", () => {+ const ctx = new SearchContext({+ fastSearch: true,+ includeArchivedNotes: true,+ includeHiddenNotes: true,+ ignoreInternalAttributes: true,+ fuzzyAttributeSearch: true,+ autocomplete: true+ });++ expect(ctx.fastSearch).toBe(true);+ expect(ctx.includeArchivedNotes).toBe(true);+ expect(ctx.includeHiddenNotes).toBe(true);+ expect(ctx.ignoreInternalAttributes).toBe(true);+ expect(ctx.fuzzyAttributeSearch).toBe(true);+ expect(ctx.autocomplete).toBe(true);+ });++ it("passes through the plain ordering / paging / depth params verbatim", () => {+ const ctx = new SearchContext({+ ancestorDepth: "eq3",+ orderBy: "title",+ orderDirection: "desc",+ limit: 25,+ debug: true+ });++ expect(ctx.ancestorDepth).toBe("eq3");+ expect(ctx.orderBy).toBe("title");+ expect(ctx.orderDirection).toBe("desc");+ expect(ctx.limit).toBe(25);+ expect(ctx.debug).toBe(true);+ });++ it("falls back to the hoisted note id when no ancestor is supplied", () => {+ getHoistedNoteId.mockReturnValue("hoisted123");++ const ctx = new SearchContext();++ expect(getHoistedNoteId).toHaveBeenCalledTimes(1);+ expect(ctx.ancestorNoteId).toBe("hoisted123");+ });++ it("keeps an explicitly supplied ancestorNoteId and never consults the hoisted note", () => {+ const ctx = new SearchContext({ ancestorNoteId: "myAncestor" });++ expect(ctx.ancestorNoteId).toBe("myAncestor");+ expect(getHoistedNoteId).not.toHaveBeenCalled();+ });++ it("does not apply the hoisted note when ignoreHoistedNote is set", () => {+ getHoistedNoteId.mockReturnValue("hoisted123");++ const ctx = new SearchContext({ ignoreHoistedNote: true });++ expect(ctx.ignoreHoistedNote).toBe(true);+ expect(ctx.ancestorNoteId).toBeUndefined();+ expect(getHoistedNoteId).not.toHaveBeenCalled();+ });++ it("reads the searchEnableFuzzyMatching option for enableFuzzyMatching", () => {+ getOptionBool.mockReturnValue(false);++ const ctx = new SearchContext();++ expect(getOptionBool).toHaveBeenCalledWith("searchEnableFuzzyMatching");+ expect(ctx.enableFuzzyMatching).toBe(false);+ });++ it("defaults enableFuzzyMatching to true when the option is not yet initialized (throws)", () => {+ getOptionBool.mockImplementation(() => {+ throw new Error("option store not initialized");+ });++ const ctx = new SearchContext();++ expect(ctx.enableFuzzyMatching).toBe(true);+ });++ describe("addError / hasError / getError", () => {+ it("records the first error and ignores subsequent ones", () => {+ const ctx = new SearchContext();++ expect(ctx.hasError()).toBe(false);+ expect(ctx.getError()).toBeNull();++ ctx.addError("first problem");+ ctx.addError("second problem");++ expect(ctx.hasError()).toBe(true);+ expect(ctx.getError()).toBe("first problem");+ expect(ctx.error).toBe("first problem");+ });+ });+});diff --git a/packages/trilium-core/src/services/search/search_result.spec.ts b/packages/trilium-core/src/services/search/search_result.spec.tsnew file mode 100644index 0000000000..83091e3d33--- /dev/null+++ b/packages/trilium-core/src/services/search/search_result.spec.ts@@ -0,0 +1,218 @@+import { beforeEach, describe, expect, it } from "vitest";++import becca from "../../becca/becca.js";+import BBranch from "../../becca/entities/bbranch.js";+import BNote from "../../becca/entities/bnote.js";+import { note, NoteBuilder } from "../../test/becca_mocking.js";+import SearchResult from "./search_result.js";++let rootNote: NoteBuilder;++/** Build a SearchResult for a note reachable directly under root. */+function resultFor(noteBuilder: NoteBuilder) {+ return new SearchResult(["root", noteBuilder.note.noteId]);+}++describe("SearchResult", () => {+ beforeEach(() => {+ becca.reset();++ rootNote = new NoteBuilder(new BNote({ noteId: "root", title: "root", type: "text" }));+ new BBranch({+ branchId: "none_root",+ noteId: "root",+ parentNoteId: "none",+ notePosition: 10+ });+ });++ describe("constructor and getters", () => {+ it("derives notePath, noteId, and notePathTitle from the path array", () => {+ const austria = note("Austria");+ rootNote.child(austria);++ const result = new SearchResult(["root", austria.note.noteId]);++ expect(result.notePath).toBe(`root/${austria.note.noteId}`);+ expect(result.noteId).toBe(austria.note.noteId);+ // The path title joins ancestor titles below the hoisted (root) note.+ expect(result.notePathTitle).toBe("Austria");+ expect(result.score).toBe(0);+ });++ it("returns the last path segment as noteId for a deeper path", () => {+ const parent = note("Parent");+ const child = note("Child");+ parent.child(child);+ rootNote.child(parent);++ const result = new SearchResult(["root", parent.note.noteId, child.note.noteId]);++ expect(result.noteId).toBe(child.note.noteId);+ expect(result.notePath).toBe(`root/${parent.note.noteId}/${child.note.noteId}`);+ expect(result.notePathTitle).toBe("Parent › Child");+ });+ });++ describe("computeScore - title matching", () => {+ it("awards the exact-title bonus when the query equals the title", () => {+ const target = note("Austria");+ rootNote.child(target);++ const result = resultFor(target);+ result.computeScore("austria", ["austria"]);++ // Exact title match (2000) + exact token match on the title chunk.+ expect(result.score).toBeGreaterThanOrEqual(2000);+ });++ it("ranks an exact title match above a prefix match above a word match", () => {+ const exact = note("Vienna");+ const prefix = note("Vienna City");+ const word = note("The Vienna Region");+ rootNote.child(exact).child(prefix).child(word);++ const exactResult = resultFor(exact);+ exactResult.computeScore("vienna", ["vienna"], false);++ const prefixResult = resultFor(prefix);+ prefixResult.computeScore("vienna", ["vienna"], false);++ const wordResult = resultFor(word);+ wordResult.computeScore("vienna", ["vienna"], false);++ expect(exactResult.score).toBeGreaterThan(prefixResult.score);+ expect(prefixResult.score).toBeGreaterThan(wordResult.score);+ });++ it("matches the query as a complete word at the start, middle, and end of the title", () => {+ const start = note("vienna is great");+ const middle = note("the vienna region");+ const end = note("welcome to vienna");+ rootNote.child(start).child(middle).child(end);++ for (const builder of [start, middle, end]) {+ const result = resultFor(builder);+ // Disable fuzzy matching so any score reflects the word-match branch / tokens.+ result.computeScore("vienna", ["vienna"], false);+ // Word match (300) is awarded for all three positions.+ expect(result.score).toBeGreaterThanOrEqual(300);+ }+ });+ });++ describe("computeScore - note id matching", () => {+ it("adds the note-id bonus when the query equals the note id", () => {+ const target = note("Some title", { noteId: "abc123" });+ rootNote.child(target);++ const result = new SearchResult(["root", "abc123"]);+ // Query equals the lowercased note id but not the title.+ result.computeScore("abc123", ["abc123"], false);++ // Note-id exact match contributes 1000.+ expect(result.score).toBeGreaterThanOrEqual(1000);+ });+ });++ describe("computeScore - token matching via addScoreForStrings", () => {+ it("scores exact token matches higher than prefix matches higher than contains matches", () => {+ const target = note("alpha");+ rootNote.child(target);+ const result = resultFor(target);++ const exact = new SearchResult(["root", target.note.noteId]);+ exact.addScoreForStrings(["alpha"], "alpha", 1, false);++ const prefix = new SearchResult(["root", target.note.noteId]);+ prefix.addScoreForStrings(["alph"], "alpha", 1, false);++ const contains = new SearchResult(["root", target.note.noteId]);+ contains.addScoreForStrings(["lph"], "alpha", 1, false);++ expect(exact.score).toBeGreaterThan(prefix.score);+ expect(prefix.score).toBeGreaterThan(contains.score);+ expect(contains.score).toBeGreaterThan(0);+ // result is only constructed to anchor the note in becca for getNoteTitleForPath.+ expect(result.score).toBe(0);+ });++ it("scales the token score by the factor and the token length", () => {+ const target = note("alpha");+ rootNote.child(target);++ const single = new SearchResult(["root", target.note.noteId]);+ single.addScoreForStrings(["alpha"], "alpha", 1, false);++ const doubled = new SearchResult(["root", target.note.noteId]);+ doubled.addScoreForStrings(["alpha"], "alpha", 2, false);++ // factor 2 yields exactly double the exact-match contribution.+ expect(doubled.score).toBeCloseTo(single.score * 2);+ });++ it("does not award token score when no chunk matches", () => {+ const target = note("alpha");+ rootNote.child(target);++ const result = new SearchResult(["root", target.note.noteId]);+ result.addScoreForStrings(["zzz"], "alpha", 1, false);++ expect(result.score).toBe(0);+ });+ });++ describe("computeScore - hidden subtree penalty", () => {+ it("divides the total score by the hidden-note penalty for hidden notes", () => {+ const hidden = new NoteBuilder(new BNote({ noteId: "_hidden", title: "Vienna", type: "text" }));+ new BBranch({+ branchId: "root__hidden",+ noteId: "_hidden",+ parentNoteId: "root",+ notePosition: 10+ });++ const result = new SearchResult(["root", "_hidden"]);+ result.computeScore("vienna", ["vienna"], false);++ const visible = note("Vienna");+ rootNote.child(visible);+ const visibleResult = resultFor(visible);+ visibleResult.computeScore("vienna", ["vienna"], false);++ expect(hidden.note.isInHiddenSubtree()).toBe(true);+ // Hidden note score is exactly one third (penalty = 3) of the visible equivalent.+ expect(result.score).toBeCloseTo(visibleResult.score / 3);+ });+ });++ describe("computeScore - fuzzy matching", () => {+ it("awards a fuzzy title score for a near-miss query only when fuzzy matching is enabled", () => {+ const target = note("Vienna");+ rootNote.child(target);++ const fuzzy = resultFor(target);+ // "vienne" is one substitution away from "vienna".+ fuzzy.computeScore("vienne", ["vienne"], true);++ const strict = resultFor(target);+ strict.computeScore("vienne", ["vienne"], false);++ expect(fuzzy.score).toBeGreaterThan(strict.score);+ });++ it("ranks a fuzzy match strictly below an exact title match", () => {+ const exact = note("Vienna");+ const typo = note("Vienna");+ rootNote.child(exact).child(typo);++ const exactResult = resultFor(exact);+ exactResult.computeScore("vienna", ["vienna"], true);++ const fuzzyResult = resultFor(typo);+ fuzzyResult.computeScore("vienne", ["vienne"], true);++ expect(exactResult.score).toBeGreaterThan(fuzzyResult.score);+ });+ });+});diff --git a/packages/trilium-core/src/services/search/services/build_comparator.spec.ts b/packages/trilium-core/src/services/search/services/build_comparator.spec.tsnew file mode 100644index 0000000000..ed56b9c4dc--- /dev/null+++ b/packages/trilium-core/src/services/search/services/build_comparator.spec.ts@@ -0,0 +1,159 @@+import { describe, expect, it } from "vitest";++import buildComparator from "./build_comparator.js";++describe("buildComparator", () => {+ it("returns undefined for an unknown operator", () => {+ expect(buildComparator("???", "value")).toBeUndefined();+ });++ describe("numeric comparators", () => {+ it("uses numeric comparison when the compared value is a number", () => {+ const gt = buildComparator(">", "5")!;+ expect(gt("10")).toBe(true);+ expect(gt("3")).toBe(false);+ expect(gt("5")).toBe(false);++ const gte = buildComparator(">=", "5")!;+ expect(gte("5")).toBe(true);+ expect(gte("4")).toBe(false);++ const lt = buildComparator("<", "5")!;+ expect(lt("3")).toBe(true);+ expect(lt("5")).toBe(false);++ const lte = buildComparator("<=", "5")!;+ expect(lte("5")).toBe(true);+ expect(lte("6")).toBe(false);+ });++ it("parses the candidate value as a float (numeric, not lexical)", () => {+ // Lexically "9" > "10", but numerically 9 < 10. Numeric path must win.+ const gt = buildComparator(">", "10")!;+ expect(gt("9")).toBe(false);+ expect(gt("100")).toBe(true);++ // Decimal compared values are supported.+ const lt = buildComparator("<", "2.5")!;+ expect(lt("2.4")).toBe(true);+ expect(lt("2.6")).toBe(false);+ });++ it("falls back to lexical string comparison when the compared value is not numeric", () => {+ const gt = buildComparator(">", "abc")!;+ // String comparison: "abd" > "abc"+ expect(gt("abd")).toBe(true);+ expect(gt("abb")).toBe(false);+ });+ });++ describe("equality operators (= and !=)", () => {+ it("matches a single word case-insensitively against any word in the value", () => {+ const eq = buildComparator("=", "Hello")!;+ expect(eq("hello world")).toBe(true);+ expect(eq("say HELLO there")).toBe(true);+ expect(eq("hellothere")).toBe(false); // not an exact word+ expect(eq("")).toBe(false);+ });++ it("matches a multi-word phrase as a consecutive substring", () => {+ const eq = buildComparator("=", "hello world")!;+ expect(eq("well hello world friend")).toBe(true);+ expect(eq("world hello")).toBe(false);+ });++ it("normalizes diacritics on both sides", () => {+ const eq = buildComparator("=", "café")!;+ expect(eq("the cafe is open")).toBe(true);+ });++ it("negates the equality match and treats empty value as a match", () => {+ const neq = buildComparator("!=", "hello")!;+ expect(neq("hello world")).toBe(false);+ expect(neq("goodbye world")).toBe(true);+ expect(neq("")).toBe(true);++ const neqPhrase = buildComparator("!=", "hello world")!;+ expect(neqPhrase("well hello world")).toBe(false);+ expect(neqPhrase("world hello")).toBe(true);+ });+ });++ describe("substring operators", () => {+ it("handles *= (ends with), =* (starts with) and *=* (includes)", () => {+ // comparedValue is lowercased internally.+ const endsWith = buildComparator("*=", "World")!;+ expect(endsWith("hello world")).toBe(true);+ expect(endsWith("world hello")).toBe(false);+ expect(endsWith("")).toBe(false);++ const startsWith = buildComparator("=*", "Hello")!;+ expect(startsWith("hello world")).toBe(true);+ expect(startsWith("say hello")).toBe(false);+ expect(startsWith("")).toBe(false);++ const includes = buildComparator("*=*", "lo wo")!;+ expect(includes("hello world")).toBe(true);+ expect(includes("helloworld")).toBe(false);+ expect(includes("")).toBe(false);+ });+ });++ describe("regex operator (%=)", () => {+ it("tests the value against the compared value as a regular expression", () => {+ const re = buildComparator("%=", "^h.llo$")!;+ expect(re("hello")).toBe(true);+ expect(re("hallo")).toBe(true);+ expect(re("hello world")).toBe(false);+ expect(re("")).toBe(false);+ });++ it("caches compiled regexes (repeated calls behave consistently)", () => {+ const re = buildComparator("%=", "ab+c")!;+ expect(re("abbbc")).toBe(true);+ expect(re("ac")).toBe(false);+ // Re-using the same pattern hits the cache; behavior is unchanged.+ const re2 = buildComparator("%=", "ab+c")!;+ expect(re2("abc")).toBe(true);+ });+ });++ describe("fuzzy operators (~= and ~*)", () => {+ it("~= matches exact substring and close typos for tokens of sufficient length", () => {+ const fuzzy = buildComparator("~=", "hello")!;+ // Exact substring match.+ expect(fuzzy("well hello there")).toBe(true);+ // Fuzzy word match (single edit distance).+ expect(fuzzy("the hallo world")).toBe(true);+ // Completely unrelated.+ expect(fuzzy("goodbye")).toBe(false);+ });++ it("~= falls back to plain substring matching for tokens below the minimum length", () => {+ // "ab" is shorter than MIN_FUZZY_TOKEN_LENGTH (3), so no fuzzy logic applies.+ const fuzzy = buildComparator("~=", "ab")!;+ expect(fuzzy("crab")).toBe(true);+ expect(fuzzy("xyz")).toBe(false);+ });++ it("returns false when either side is empty for fuzzy operators", () => {+ const fuzzyEq = buildComparator("~=", "hello")!;+ expect(fuzzyEq("")).toBe(false);++ const fuzzyStar = buildComparator("~*", "hello")!;+ expect(fuzzyStar("")).toBe(false);+ });++ it("~* performs fuzzy matching across the whole content", () => {+ const fuzzy = buildComparator("~*", "hello")!;+ expect(fuzzy("hello world")).toBe(true);+ expect(fuzzy("xyz")).toBe(false);+ });++ it("~* falls back to substring matching for short tokens", () => {+ const fuzzy = buildComparator("~*", "ab")!;+ expect(fuzzy("crab")).toBe(true);+ expect(fuzzy("xyz")).toBe(false);+ });+ });+});diff --git a/packages/trilium-core/src/services/spaced_update.spec.ts b/packages/trilium-core/src/services/spaced_update.spec.tsnew file mode 100644index 0000000000..bf38bec3af--- /dev/null+++ b/packages/trilium-core/src/services/spaced_update.spec.ts@@ -0,0 +1,169 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import SpacedUpdate from "./spaced_update.js";++describe("SpacedUpdate", () => {+ beforeEach(() => {+ vi.useFakeTimers();+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ describe("scheduleUpdate / triggerUpdate", () => {+ it("fires the updater once the interval has elapsed", async () => {+ const updater = vi.fn();+ const spacedUpdate = new SpacedUpdate(updater, 50);++ // Move the clock forward so the very next change is already past the interval+ // relative to the construction time.+ await vi.advanceTimersByTimeAsync(60);++ spacedUpdate.scheduleUpdate();+ await vi.runAllTimersAsync();++ expect(updater).toHaveBeenCalledTimes(1);+ });++ it("reschedules instead of firing while still within the interval, then fires once", async () => {+ const updater = vi.fn();+ const spacedUpdate = new SpacedUpdate(updater, 100);++ // Rapid scheduling well within the interval keeps deferring the update.+ for (let i = 0; i < 5; i++) {+ spacedUpdate.scheduleUpdate();+ await vi.advanceTimersByTimeAsync(10);+ }+ expect(updater).not.toHaveBeenCalled();++ // Once the interval fully elapses the pending change flushes exactly once.+ await vi.advanceTimersByTimeAsync(200);+ expect(updater).toHaveBeenCalledTimes(1);+ });++ it("triggerUpdate is a no-op when nothing changed", () => {+ const updater = vi.fn();+ const spacedUpdate = new SpacedUpdate(updater, 50);++ spacedUpdate.triggerUpdate();++ expect(updater).not.toHaveBeenCalled();+ });++ it("clears the changed flag after a successful flush so a second elapsed trigger does nothing", async () => {+ const updater = vi.fn();+ const spacedUpdate = new SpacedUpdate(updater, 50);++ await vi.advanceTimersByTimeAsync(60);+ spacedUpdate.scheduleUpdate();+ await vi.runAllTimersAsync();+ expect(updater).toHaveBeenCalledTimes(1);++ // No new change scheduled -> even past the interval triggerUpdate stays inert.+ await vi.advanceTimersByTimeAsync(100);+ spacedUpdate.triggerUpdate();+ expect(updater).toHaveBeenCalledTimes(1);+ });+ });++ describe("updateNowIfNecessary", () => {+ it("calls the updater when there are pending changes", async () => {+ const updater = vi.fn(async () => {});+ const spacedUpdate = new SpacedUpdate(updater, 50);++ spacedUpdate.scheduleUpdate();+ await spacedUpdate.updateNowIfNecessary();++ expect(updater).toHaveBeenCalledTimes(1);+ });++ it("does nothing when there are no pending changes", async () => {+ const updater = vi.fn(async () => {});+ const spacedUpdate = new SpacedUpdate(updater, 50);++ await spacedUpdate.updateNowIfNecessary();++ expect(updater).not.toHaveBeenCalled();+ });++ it("restores the changed flag and rethrows when the updater fails, allowing a retry", async () => {+ let shouldFail = true;+ const updater = vi.fn(async () => {+ if (shouldFail) {+ throw new Error("boom");+ }+ });+ const spacedUpdate = new SpacedUpdate(updater, 50);++ spacedUpdate.scheduleUpdate();++ await expect(spacedUpdate.updateNowIfNecessary()).rejects.toThrow("boom");++ // changed flag restored -> a subsequent successful flush runs the updater again.+ shouldFail = false;+ await spacedUpdate.updateNowIfNecessary();+ expect(updater).toHaveBeenCalledTimes(2);+ });+ });++ describe("isAllSavedAndTriggerUpdate", () => {+ it("returns false and flushes pending changes when there are changes", async () => {+ const updater = vi.fn(async () => {});+ const spacedUpdate = new SpacedUpdate(updater, 50);++ spacedUpdate.scheduleUpdate();++ expect(spacedUpdate.isAllSavedAndTriggerUpdate()).toBe(false);++ await vi.runAllTimersAsync();+ expect(updater).toHaveBeenCalledTimes(1);+ });++ it("returns true and does not call the updater when nothing is pending", () => {+ const updater = vi.fn(async () => {});+ const spacedUpdate = new SpacedUpdate(updater, 50);++ expect(spacedUpdate.isAllSavedAndTriggerUpdate()).toBe(true);+ expect(updater).not.toHaveBeenCalled();+ });+ });++ describe("allowUpdateWithoutChange", () => {+ it("suppresses scheduleUpdate while the callback runs and re-enables it afterwards", async () => {+ const updater = vi.fn(async () => {});+ const spacedUpdate = new SpacedUpdate(updater, 50);++ await spacedUpdate.allowUpdateWithoutChange(async () => {+ // scheduleUpdate is a no-op while change is forbidden.+ spacedUpdate.scheduleUpdate();+ });++ await vi.runAllTimersAsync();+ expect(updater).not.toHaveBeenCalled();++ // After the callback, scheduling works again.+ await vi.advanceTimersByTimeAsync(60);+ spacedUpdate.scheduleUpdate();+ await vi.runAllTimersAsync();+ expect(updater).toHaveBeenCalledTimes(1);+ });++ it("re-enables scheduling even when the callback throws", async () => {+ const updater = vi.fn(async () => {});+ const spacedUpdate = new SpacedUpdate(updater, 50);++ await expect(+ spacedUpdate.allowUpdateWithoutChange(async () => {+ throw new Error("callback failed");+ })+ ).rejects.toThrow("callback failed");++ // changeForbidden was reset in finally -> scheduling works again.+ await vi.advanceTimersByTimeAsync(60);+ spacedUpdate.scheduleUpdate();+ await vi.runAllTimersAsync();+ expect(updater).toHaveBeenCalledTimes(1);+ });+ });+});diff --git a/packages/trilium-core/src/services/special_notes.spec.ts b/packages/trilium-core/src/services/special_notes.spec.tsnew file mode 100644index 0000000000..81e20eab87--- /dev/null+++ b/packages/trilium-core/src/services/special_notes.spec.ts@@ -0,0 +1,389 @@+import { afterEach, describe, expect, it, vi } from "vitest";++import becca from "../becca/becca.js";+import type BNote from "../becca/entities/bnote.js";+import attributeService from "./attributes.js";+import { getContext } from "./context.js";+import hoistedNoteService from "./hoisted_note.js";+import specialNotes from "./special_notes.js";++/**+ * Wraps a callback in a CLS context. Entity mutations (createNewNote,+ * note.save(), branch.markAsDeleted(), etc.) require CLS to be initialised.+ */+function withContext<T>(fn: () => T): T {+ return getContext().init(fn);+}++/**+ * The created note must end up (transitively) under the hidden subtree of the+ * given root, as the monthly parent for these special notes lives there.+ */+function expectUnderHidden(note: BNote, rootNoteId: string) {+ expect(note.hasAncestor(rootNoteId)).toBe(true);+ expect(note.hasAncestor("_hidden")).toBe(true);+}++describe("special_notes (core, real DB)", () => {+ afterEach(() => vi.restoreAllMocks());++ describe("createSqlConsole", () => {+ it("creates a code SQL console note under a monthly book parent in the hidden subtree", () => {+ const note = withContext(() => specialNotes.createSqlConsole());++ expect(note.type).toBe("code");+ expect(note.mime).toBe("text/x-sqlite;schema=trilium");+ expect(note.getContent().toString()).toContain("SELECT");+ expect(note.getLabelValue("iconClass")).toBe("bx bx-data");+ expect(note.hasLabel("keepCurrentHoisting")).toBe(true);+ expect(note.title).toContain("SQL Console");++ expectUnderHidden(note, "_sqlConsole");++ // The monthly parent must be a book note labelled sqlConsoleMonthNote.+ const parent = note.getParentNotes()[0];+ expect(parent.type).toBe("book");+ expect(parent.hasLabel("sqlConsoleMonthNote")).toBe(true);+ });++ it("reuses the same monthly parent for consoles created in the same month", () => {+ const a = withContext(() => specialNotes.createSqlConsole());+ const b = withContext(() => specialNotes.createSqlConsole());++ expect(a.getParentNotes()[0].noteId).toBe(b.getParentNotes()[0].noteId);+ });+ });++ describe("saveSqlConsole", () => {+ it("rejects when the SQL console note does not exist", async () => {+ await expect(withContext(() => specialNotes.saveSqlConsole("doesNotExist123")))+ .rejects.toThrow(/SQL console note/);+ });++ it("clones to the day note home and removes the hidden-subtree parent branch", async () => {+ const note = withContext(() => specialNotes.createSqlConsole());+ expect(note.hasAncestor("_hidden")).toBe(true);++ const result = await withContext(() => specialNotes.saveSqlConsole(note.noteId));++ expect(result.success).toBe(true);+ expect(result.branchId).toBeTruthy();+ expect(becca.getBranch(result.branchId!)).toBeTruthy();++ // After saving, the console must no longer hang off the hidden subtree.+ const liveParents = note.getParentBranches().filter((b) => !b.isDeleted);+ expect(liveParents.length).toBeGreaterThan(0);+ expect(liveParents.some((b) => b.parentNote?.hasAncestor("_hidden"))).toBe(false);+ });++ it("uses an explicit #sqlConsoleHome target note when present", async () => {+ // A real, root-anchored note used as the clone target.+ const home = becca.getNoteOrThrow("root").getChildNotes()[0];+ vi.spyOn(attributeService, "getNoteWithLabel").mockReturnValue(home);++ const note = withContext(() => specialNotes.createSqlConsole());+ const result = await withContext(() => specialNotes.saveSqlConsole(note.noteId));++ expect(result.success).toBe(true);+ // It was cloned under the supplied home (a descendant of root, not hidden).+ const liveParents = note.getParentBranches().filter((b) => !b.isDeleted);+ expect(liveParents.some((b) => b.parentNoteId === home.noteId)).toBe(true);+ });+ });++ describe("createSearchNote", () => {+ it("creates a search note carrying the search string and keepCurrentHoisting label", () => {+ const note = withContext(() => specialNotes.createSearchNote("hello world", ""));++ expect(note.type).toBe("search");+ expect(note.mime).toBe("application/json");+ expect(note.getLabelValue("searchString")).toBe("hello world");+ expect(note.hasLabel("keepCurrentHoisting")).toBe(true);+ expect(note.title).toContain("hello world");++ expectUnderHidden(note, "_search");++ const parent = note.getParentNotes()[0];+ expect(parent.type).toBe("book");+ expect(parent.hasLabel("searchMonthNote")).toBe(true);+ });++ it("sets the ancestor relation only when an ancestorNoteId is supplied", () => {+ const withAncestor = withContext(() => specialNotes.createSearchNote("q1", "root"));+ expect(withAncestor.getRelationValue("ancestor")).toBe("root");++ const withoutAncestor = withContext(() => specialNotes.createSearchNote("q2", ""));+ expect(withoutAncestor.hasRelation("ancestor")).toBe(false);+ });+ });++ describe("saveSearchNote", () => {+ it("throws when the search note does not exist", () => {+ expect(() => withContext(() => specialNotes.saveSearchNote("doesNotExist123")))+ .toThrow(/search note/);+ });++ it("throws when there is no workspace note", () => {+ vi.spyOn(hoistedNoteService, "getWorkspaceNote").mockReturnValue(null as any);+ const note = withContext(() => specialNotes.createSearchNote("q", ""));++ expect(() => withContext(() => specialNotes.saveSearchNote(note.noteId)))+ .toThrow(/workspace note/);+ });++ it("clones to the search home and removes the hidden-subtree parent branch", () => {+ const note = withContext(() => specialNotes.createSearchNote("q", ""));+ expect(note.hasAncestor("_hidden")).toBe(true);++ const result = withContext(() => specialNotes.saveSearchNote(note.noteId));++ expect(result.success).toBe(true);+ expect(result.branchId).toBeTruthy();+ expect(becca.getBranch(result.branchId!)).toBeTruthy();++ const liveParents = note.getParentBranches().filter((b) => !b.isDeleted);+ expect(liveParents.length).toBeGreaterThan(0);+ expect(liveParents.some((b) => b.parentNote?.hasAncestor("_hidden"))).toBe(false);+ });+ });++ describe("getInboxNote", () => {+ it("throws when there is no workspace note", () => {+ vi.spyOn(hoistedNoteService, "getWorkspaceNote").mockReturnValue(null as any);+ expect(() => specialNotes.getInboxNote("2026-05-29")).toThrow(/workspace note/);+ });++ it("returns the #inbox-labelled note when at the root workspace", () => {+ const inbox = becca.getNoteOrThrow("root").getChildNotes()[0];+ vi.spyOn(attributeService, "getNoteWithLabel").mockReturnValue(inbox);++ const result = specialNotes.getInboxNote("2026-05-29");+ expect(result.noteId).toBe(inbox.noteId);+ });++ it("falls back to the day note when no #inbox label exists at the root", () => {+ vi.spyOn(attributeService, "getNoteWithLabel").mockReturnValue(null);++ // getDayNote may create the day note, so it needs a CLS context.+ const result = withContext(() => specialNotes.getInboxNote("2026-05-29"));+ // Day note for the date is created under the calendar; it is a real note.+ expect(result).toBeTruthy();+ expect(result.noteId).not.toBe("root");+ });++ it("prefers #workspaceInbox over #inbox within a non-root workspace", () => {+ const workspaceInbox = becca.getNoteOrThrow("root").getChildNotes()[0];+ const plainInbox = becca.getNoteOrThrow("root").getChildNotes()[1];+ const workspace = makeWorkspaceStub({+ "#workspaceInbox": workspaceInbox,+ "#inbox": plainInbox+ });+ vi.spyOn(hoistedNoteService, "getWorkspaceNote").mockReturnValue(workspace as any);++ expect(specialNotes.getInboxNote("2026-05-29").noteId).toBe(workspaceInbox.noteId);+ });++ it("falls back to the workspace note itself when no inbox label is found in the subtree", () => {+ const workspace = makeWorkspaceStub({});+ vi.spyOn(hoistedNoteService, "getWorkspaceNote").mockReturnValue(workspace as any);++ // The stub workspace reports its own noteId via the underlying real note.+ const result = specialNotes.getInboxNote("2026-05-29");+ expect(result).toBe(workspace);+ });+ });++ describe("createLauncher", () => {+ it("creates a note launcher with the note-launcher template", () => {+ const { success, note } = withContext(() =>+ specialNotes.createLauncher({ parentNoteId: "_lbVisibleLaunchers", launcherType: "note" })+ );++ expect(success).toBe(true);+ expect(note.type).toBe("launcher");+ expect(note.getRelationValue("template")).toBe("_lbTplLauncherNote");+ });++ it("creates a script launcher with the script template", () => {+ const { note } = withContext(() =>+ specialNotes.createLauncher({ parentNoteId: "_lbVisibleLaunchers", launcherType: "script" })+ );++ expect(note.type).toBe("launcher");+ expect(note.getRelationValue("template")).toBe("_lbTplLauncherScript");+ });++ it("creates a custom widget launcher with the custom widget template", () => {+ const { note } = withContext(() =>+ specialNotes.createLauncher({ parentNoteId: "_lbVisibleLaunchers", launcherType: "customWidget" })+ );++ expect(note.getRelationValue("template")).toBe("_lbTplCustomWidget");+ });++ it("creates a spacer launcher with the spacer template", () => {+ const { note } = withContext(() =>+ specialNotes.createLauncher({ parentNoteId: "_lbVisibleLaunchers", launcherType: "spacer" })+ );++ expect(note.getRelationValue("template")).toBe("_lbTplSpacer");+ });++ it("throws on an unrecognized launcher type", () => {+ expect(() =>+ withContext(() =>+ specialNotes.createLauncher({+ parentNoteId: "_lbVisibleLaunchers",+ launcherType: "bogus" as any+ })+ )+ ).toThrow(/Unrecognized launcher type/);+ });+ });++ describe("resetLauncher", () => {+ it("deletes a normal launcher note", () => {+ const { note } = withContext(() =>+ specialNotes.createLauncher({ parentNoteId: "_lbVisibleLaunchers", launcherType: "note" })+ );+ expect(note.isDeleted).toBe(false);++ withContext(() => specialNotes.resetLauncher(note.noteId));++ expect(becca.getNote(note.noteId)?.isDeleted ?? true).toBe(true);+ });++ it("only resets the children (not the root note itself) for the launchbar roots", () => {+ // Deleting the real _lbRoot children would corrupt the shared fixture+ // DB for the other tests, so drive the root-reset branch through a mock.+ const childA = { deleteNote: vi.fn() };+ const childB = { deleteNote: vi.fn() };+ const rootNote = {+ isLaunchBarConfig: () => true,+ deleteNote: vi.fn(),+ getChildNotes: () => [childA, childB]+ };+ vi.spyOn(becca, "getNote").mockReturnValue(rootNote as any);++ withContext(() => specialNotes.resetLauncher("_lbRoot"));++ // The root itself must NOT be deleted; only its children are reset.+ expect(rootNote.deleteNote).not.toHaveBeenCalled();+ expect(childA.deleteNote).toHaveBeenCalledTimes(1);+ expect(childB.deleteNote).toHaveBeenCalledTimes(1);+ });++ it("is a no-op for a note that is not a launchbar config note", () => {+ const plain = withContext(() => specialNotes.createSearchNote("not-a-launcher", ""));++ withContext(() => specialNotes.resetLauncher(plain.noteId));++ // Search notes are not launchbar config, so they are left intact.+ expect(becca.getNote(plain.noteId)?.isDeleted).toBe(false);+ });+ });++ describe("createOrUpdateScriptLauncherFromApi", () => {+ it("rejects non-alphanumeric ids and a missing title", () => {+ expect(() =>+ withContext(() =>+ specialNotes.createOrUpdateScriptLauncherFromApi({+ id: "bad id!",+ title: "X",+ action: "() => {}"+ })+ )+ ).toThrow(/alphanumeric/);++ expect(() =>+ withContext(() =>+ specialNotes.createOrUpdateScriptLauncherFromApi({+ id: "okid",+ title: "",+ action: "() => {}"+ })+ )+ ).toThrow(/Title is mandatory/);+ });++ it("creates a new script launcher with content, mime, shortcut and icon labels", () => {+ const launcher = withContext(() =>+ specialNotes.createOrUpdateScriptLauncherFromApi({+ id: "myLauncher1",+ title: "My Launcher",+ action: "() => console.log(1)",+ shortcut: "ctrl+m",+ icon: "rocket"+ })+ );++ expect(launcher.noteId).toBe("myLauncher1");+ expect(launcher.title).toBe("My Launcher");+ expect(launcher.mime).toBe("application/javascript;env=frontend");+ expect(launcher.getContent().toString()).toBe("(() => console.log(1))()");+ expect(launcher.hasLabel("scriptInLauncherContent")).toBe(true);+ expect(launcher.getLabelValue("keyboardShortcut")).toBe("ctrl+m");+ expect(launcher.getLabelValue("iconClass")).toBe("bx bx-rocket");+ expect(launcher.getRelationValue("template")).toBe("_lbTplLauncherScript");+ });++ it("updates the existing launcher and removes shortcut/icon labels when omitted", () => {+ withContext(() =>+ specialNotes.createOrUpdateScriptLauncherFromApi({+ id: "myLauncher2",+ title: "First",+ action: "() => 1",+ shortcut: "ctrl+a",+ icon: "cog"+ })+ );++ const updated = withContext(() =>+ specialNotes.createOrUpdateScriptLauncherFromApi({+ id: "myLauncher2",+ title: "Second",+ action: "() => 2"+ })+ );++ expect(updated.noteId).toBe("myLauncher2");+ expect(updated.title).toBe("Second");+ expect(updated.getContent().toString()).toBe("(() => 2)()");+ expect(updated.hasLabel("keyboardShortcut")).toBe(false);+ expect(updated.hasLabel("iconClass")).toBe(false);+ });++ it("derives an alphanumeric id from the title when no id is provided", () => {+ const launcher = withContext(() =>+ specialNotes.createOrUpdateScriptLauncherFromApi({+ id: "",+ title: "Hello World!",+ action: "() => {}"+ })+ );++ expect(launcher.noteId).toMatch(/^tb_/);+ });+ });+});++/**+ * Returns a workspace stub backed by a real, non-root note but with a+ * controllable searchNoteInSubtree and isRoot() === false, so the inbox/search+ * short-circuit operands can each be reached deterministically (the real+ * searchNoteInSubtree is global, so genuine labels would collide between tests).+ */+function makeWorkspaceStub(found: Record<string, unknown>) {+ const real = becca.getNoteOrThrow("root").getChildNotes()[0];+ return new Proxy(real, {+ get(target, prop) {+ if (prop === "isRoot") {+ return () => false;+ }+ if (prop === "searchNoteInSubtree") {+ return (query: string) => found[query] ?? null;+ }+ return (target as any)[prop];+ }+ });+}diff --git a/packages/trilium-core/src/services/sql/sql.spec.ts b/packages/trilium-core/src/services/sql/sql.spec.tsnew file mode 100644index 0000000000..38bfbe3031--- /dev/null+++ b/packages/trilium-core/src/services/sql/sql.spec.ts@@ -0,0 +1,361 @@+import { beforeAll, describe, expect, it } from "vitest";++import { getContext } from "../context.js";+import { getSql } from "./index.js";++/**+ * Wraps a callback in a CLS context. Methods that touch `getContext()`+ * (e.g. `disableSlowQueryLogging`, `transactional`) require an initialised+ * context.+ */+function withContext<T>(fn: () => T): T {+ return getContext().init(fn);+}++let tableCounter = 0;++/**+ * Creates a fresh isolated temp table for write tests. Each test gets its own+ * table name so that the shared in-memory fixture DB (one copy per spec file)+ * doesn't leak rows between `it()`s.+ */+function createTempTable(columns = "id INTEGER PRIMARY KEY, name TEXT, val INTEGER"): string {+ tableCounter++;+ const name = `sql_spec_tbl_${tableCounter}`;+ getSql().executeScript(`CREATE TEMP TABLE "${name}" (${columns})`);+ return name;+}++describe("SqlService (real DB)", () => {+ beforeAll(() => {+ // Touching getSql() throws if core wasn't initialised; assert the+ // suite-level fixture really booted the service.+ expect(getSql()).toBeDefined();+ });++ describe("insert / replace / upsert", () => {+ it("inserts a row and returns the last insert rowid, joining columns and values", () => {+ const table = createTempTable();+ const rowid = getSql().insert(table, { name: "alpha", val: 10 });++ expect(typeof rowid).toBe("number");++ const row = getSql().getRow<{ name: string; val: number }>(+ `SELECT name, val FROM "${table}" WHERE rowid = ?`,+ [rowid]+ );+ expect(row).toEqual({ name: "alpha", val: 10 });+ });++ it("returns undefined and does not insert when the record is empty", () => {+ const table = createTempTable();+ const result = getSql().insert(table, {});++ expect(result).toBeUndefined();+ expect(getSql().getValue<number>(`SELECT COUNT(*) FROM "${table}"`)).toBe(0);+ });++ it("replace overwrites a conflicting primary key via INSERT OR REPLACE", () => {+ const table = createTempTable();+ getSql().insert(table, { id: 1, name: "first", val: 1 });+ const rowid = getSql().replace(table, { id: 1, name: "second", val: 2 });++ expect(typeof rowid).toBe("number");+ const rows = getSql().getRows<{ name: string }>(`SELECT name FROM "${table}"`);+ expect(rows).toEqual([{ name: "second" }]);+ });++ it("upsert inserts then updates on conflict and coerces booleans to 0/1", () => {+ const table = createTempTable("id INTEGER PRIMARY KEY, name TEXT, flag INTEGER");++ getSql().upsert(table, "id", { id: 5, name: "orig", flag: true });+ expect(getSql().getValue<number>(`SELECT flag FROM "${table}" WHERE id = 5`)).toBe(1);++ getSql().upsert(table, "id", { id: 5, name: "updated", flag: false });+ const row = getSql().getRow<{ name: string; flag: number }>(+ `SELECT name, flag FROM "${table}" WHERE id = 5`+ );+ // Conflict path updated the existing row in place; boolean false -> 0.+ expect(row).toEqual({ name: "updated", flag: 0 });+ expect(getSql().getValue<number>(`SELECT COUNT(*) FROM "${table}"`)).toBe(1);+ });++ it("upsert is a no-op for an empty record", () => {+ const table = createTempTable();+ getSql().upsert(table, "id", {});+ expect(getSql().getValue<number>(`SELECT COUNT(*) FROM "${table}"`)).toBe(0);+ });+ });++ describe("row readers", () => {+ it("getRow / getRowOrNull / getValue / getColumn / getRows read a seeded table", () => {+ const table = createTempTable();+ getSql().insert(table, { name: "a", val: 1 });+ getSql().insert(table, { name: "b", val: 2 });++ expect(getSql().getValue<number>(`SELECT COUNT(*) FROM "${table}"`)).toBe(2);+ // Distinct query strings: getColumn pluck-mode and getRows row-mode+ // share the statement cache by query text, so reusing the exact same+ // string would leave the cached statement stuck in pluck mode.+ expect(+ getSql().getColumn<string>(`SELECT name FROM "${table}" /*col*/ ORDER BY val`)+ ).toEqual(["a", "b"]);++ const all = getSql().getRows<{ name: string }>(+ `SELECT name FROM "${table}" /*rows*/ ORDER BY val`+ );+ expect(all.map((r) => r.name)).toEqual(["a", "b"]);++ const first = getSql().getRowOrNull<{ name: string }>(+ `SELECT name FROM "${table}" ORDER BY val LIMIT 1`+ );+ expect(first).toEqual({ name: "a" });++ const single = getSql().getRow<{ name: string }>(+ `SELECT name FROM "${table}" WHERE val = ?`,+ [2]+ );+ expect(single).toEqual({ name: "b" });+ });++ it("getRowOrNull returns null when no rows match", () => {+ const table = createTempTable();+ expect(getSql().getRowOrNull(`SELECT name FROM "${table}" WHERE val = ?`, [999])).toBeNull();+ });++ it("getMap maps the first column to the second column", () => {+ const table = createTempTable();+ getSql().insert(table, { name: "k1", val: 100 });+ getSql().insert(table, { name: "k2", val: 200 });++ const map = getSql().getMap<string, number>(`SELECT name, val FROM "${table}"`);+ expect(map).toEqual({ k1: 100, k2: 200 });+ });++ it("getRawRows returns positional arrays (raw mode) rather than keyed objects", () => {+ const table = createTempTable();+ getSql().insert(table, { name: "x", val: 7 });++ const raw = getSql().getRawRows<[string, number]>(`SELECT name, val FROM "${table}"`);+ expect(raw).toEqual([["x", 7]]);+ });++ it("iterateRows yields rows lazily", () => {+ const table = createTempTable();+ getSql().insert(table, { name: "i1", val: 1 });+ getSql().insert(table, { name: "i2", val: 2 });++ const names: string[] = [];+ for (const row of getSql().iterateRows<{ name: string }>(+ `SELECT name FROM "${table}" ORDER BY val`+ )) {+ names.push(row.name);+ }+ expect(names).toEqual(["i1", "i2"]);+ });+ });++ describe("statement cache (stmt)", () => {+ it("returns the same cached statement for an identical query string", () => {+ const sql = getSql();+ const a = sql.stmt("SELECT 1");+ const b = sql.stmt("SELECT 1");+ expect(a).toBe(b);+ });++ it("keeps raw and non-raw statements as distinct cache entries", () => {+ const sql = getSql();+ const plain = sql.stmt("SELECT 2");+ const raw = sql.stmt("SELECT 2", true);+ expect(plain).not.toBe(raw);+ });+ });++ describe("getManyRows / executeMany (??? placeholder expansion)", () => {+ it("getManyRows expands ??? into named params and chunks beyond the 100-param limit", () => {+ const table = createTempTable();+ const total = 250;+ for (let i = 0; i < total; i++) {+ getSql().insert(table, { name: `n${i}`, val: i });+ }++ const ids = Array.from({ length: total }, (_, i) => i);+ const rows = getSql().getManyRows<{ val: number }>(+ `SELECT val FROM "${table}" WHERE val IN (???)`,+ ids+ );++ // All chunks (100 + 100 + 50) are concatenated into one result set.+ expect(rows.length).toBe(total);+ expect(new Set(rows.map((r) => r.val)).size).toBe(total);+ });++ it("getManyRows returns an empty array for an empty param list", () => {+ const table = createTempTable();+ expect(getSql().getManyRows(`SELECT val FROM "${table}" WHERE val IN (???)`, [])).toEqual([]);+ });++ it("executeMany runs the query for each chunk of params", () => {+ const table = createTempTable("id INTEGER PRIMARY KEY, val INTEGER");+ for (let i = 0; i < 150; i++) {+ getSql().insert(table, { id: i, val: i });+ }++ const ids = Array.from({ length: 150 }, (_, i) => i);+ getSql().executeMany(`DELETE FROM "${table}" WHERE val IN (???)`, ids);++ expect(getSql().getValue<number>(`SELECT COUNT(*) FROM "${table}"`)).toBe(0);+ });+ });++ describe("fillParamList", () => {+ it("truncates and fills the param_list temp table with a de-duplicated set", () => {+ getSql().fillParamList(["p1", "p2", "p2", "p3"]);++ const ids = getSql()+ .getColumn<string>("SELECT paramId FROM param_list ORDER BY paramId");+ expect(ids).toEqual(["p1", "p2", "p3"]);+ });++ it("does nothing for an empty array (leaving any prior contents intact)", () => {+ getSql().fillParamList(["only"]);+ getSql().fillParamList([]);+ // The early-return for an empty list skips the DELETE, so the+ // previous single entry is still present.+ expect(getSql().getColumn<string>("SELECT paramId FROM param_list")).toEqual(["only"]);+ });++ it("accepts a Set as input", () => {+ getSql().fillParamList(new Set(["s1", "s2"]));+ expect(+ getSql().getColumn<string>("SELECT paramId FROM param_list ORDER BY paramId")+ ).toEqual(["s1", "s2"]);+ });+ });++ describe("execute", () => {+ it("runs a write and reports the number of changed rows", () => {+ const table = createTempTable();+ getSql().insert(table, { name: "a", val: 1 });+ getSql().insert(table, { name: "b", val: 1 });++ const res = getSql().execute(`UPDATE "${table}" SET val = 99 WHERE val = ?`, [1]);+ expect(res.changes).toBe(2);+ expect(getSql().getValue<number>(`SELECT COUNT(*) FROM "${table}" WHERE val = 99`)).toBe(2);+ });+ });++ describe("wrap (error handling)", () => {+ it("rethrows real SQL errors", () => {+ expect(() => getSql().getRow("SELECT * FROM table_that_does_not_exist_xyz")).toThrow();+ });++ it("returns null instead of throwing when the connection is reported closed", () => {+ const sql = getSql();+ const result = sql.wrap("SELECT 1", () => {+ throw new Error("The database connection is not open");+ });+ expect(result).toBeNull();+ });+ });++ describe("transactional", () => {+ it("commits the changes made inside the callback and returns its value", () => {+ const table = createTempTable();+ const ret = withContext(() =>+ getSql().transactional(() => {+ getSql().insert(table, { name: "committed", val: 1 });+ return "done";+ })+ );++ expect(ret).toBe("done");+ expect(getSql().getValue<number>(`SELECT COUNT(*) FROM "${table}"`)).toBe(1);+ });++ it("rolls back all changes and rethrows when the callback throws", () => {+ const table = createTempTable();+ getSql().insert(table, { name: "before", val: 1 });++ expect(() =>+ withContext(() =>+ getSql().transactional(() => {+ getSql().insert(table, { name: "doomed", val: 2 });+ throw new Error("boom");+ })+ )+ ).toThrow("boom");++ // The pre-existing row survives, the in-transaction insert is rolled back.+ const rows = getSql().getColumn<string>(`SELECT name FROM "${table}" ORDER BY name`);+ expect(rows).toEqual(["before"]);+ });+ });++ describe("transactionalAsync", () => {+ it("commits an async callback and returns its resolved value", async () => {+ const table = createTempTable();+ const ret = await withContext(() =>+ getSql().transactionalAsync(async () => {+ getSql().insert(table, { name: "async", val: 1 });+ return 42;+ })+ );++ expect(ret).toBe(42);+ expect(getSql().getValue<number>(`SELECT COUNT(*) FROM "${table}"`)).toBe(1);+ });++ it("rolls back and rethrows when the async callback rejects", async () => {+ const table = createTempTable();+ getSql().insert(table, { name: "keep", val: 1 });++ await expect(+ withContext(() =>+ getSql().transactionalAsync(async () => {+ getSql().insert(table, { name: "discard", val: 2 });+ throw new Error("async-boom");+ })+ )+ ).rejects.toThrow("async-boom");++ const rows = getSql().getColumn<string>(`SELECT name FROM "${table}" ORDER BY name`);+ expect(rows).toEqual(["keep"]);+ });+ });++ describe("disableSlowQueryLogging", () => {+ it("sets the flag for the duration of the callback and restores the prior value", () => {+ withContext(() => {+ const ctx = getContext();+ expect(ctx.get("disableSlowQueryLogging")).toBeFalsy();++ const inner = getSql().disableSlowQueryLogging(() => {+ return getContext().get("disableSlowQueryLogging");+ });+ expect(inner).toBe(true);++ // Restored back to the original (undefined/false) value afterwards.+ expect(ctx.get("disableSlowQueryLogging")).toBeFalsy();+ });+ });++ it("restores the flag even if the callback throws", () => {+ withContext(() => {+ expect(() =>+ getSql().disableSlowQueryLogging(() => {+ throw new Error("inner-fail");+ })+ ).toThrow("inner-fail");+ expect(getContext().get("disableSlowQueryLogging")).toBeFalsy();+ });+ });+ });++ describe("serialize", () => {+ it("throws when the underlying provider does not support serialization", () => {+ // The server's better-sqlite3 provider has no serialize() method.+ expect(() => getSql().serialize()).toThrow("does not support serialization");+ });+ });+});diff --git a/packages/trilium-core/src/services/sql_init.spec.ts b/packages/trilium-core/src/services/sql_init.spec.tsnew file mode 100644index 0000000000..0ece699f79--- /dev/null+++ b/packages/trilium-core/src/services/sql_init.spec.ts@@ -0,0 +1,104 @@+import { beforeAll, describe, expect, it } from "vitest";++import { getContext } from "./context.js";+import eventService from "./events.js";+import { getSql } from "./sql/index.js";+import sqlInit from "./sql_init.js";++/**+ * Wraps a callback in a CLS context. Some sql_init code paths+ * (initDbConnection, optionService.setOption) require an initialised context.+ */+function withContext<T>(fn: () => T): T {+ return getContext().init(fn);+}++describe("sql_init (real DB)", () => {+ beforeAll(() => {+ // The shared in-memory fixture DB is already initialised by the suite+ // setup, so getSql() must be available.+ expect(getSql()).toBeDefined();+ });++ describe("schemaExists", () => {+ it("reports the options table present in the initialised fixture DB", () => {+ expect(sqlInit.schemaExists()).toBe(true);+ });+ });++ describe("isDbInitialized", () => {+ it("is true because the fixture DB has the 'initialized' option set", () => {+ // Sanity: the underlying option really is "true" in the fixture.+ expect(getSql().getValue("SELECT value FROM options WHERE name = 'initialized'")).toBe("true");+ expect(sqlInit.isDbInitialized()).toBe(true);+ });+ });++ describe("getDbSize", () => {+ it("returns a positive page-based size for the populated fixture DB", () => {+ const size = sqlInit.getDbSize();+ expect(typeof size).toBe("number");+ expect(size).toBeGreaterThan(0);+ });+ });++ describe("createInitialDatabase", () => {+ it("throws on an already-initialised DB without mutating the schema", async () => {+ const branchCountBefore = getSql().getValue<number>("SELECT COUNT(*) FROM branches");++ await expect(sqlInit.createInitialDatabase()).rejects.toThrow("DB is already initialized");++ // The early guard runs before any schema/transaction work, so nothing changed.+ expect(getSql().getValue<number>("SELECT COUNT(*) FROM branches")).toBe(branchCountBefore);+ expect(sqlInit.isDbInitialized()).toBe(true);+ });+ });++ describe("createDatabaseForSync", () => {+ it("throws on an already-initialised DB without applying the schema or options", async () => {+ const optionCountBefore = getSql().getValue<number>("SELECT COUNT(*) FROM options");++ await expect(sqlInit.createDatabaseForSync([])).rejects.toThrow("DB is already initialized");++ // Guard short-circuits before initNotSyncedOptions / option inserts.+ expect(getSql().getValue<number>("SELECT COUNT(*) FROM options")).toBe(optionCountBefore);+ });+ });++ describe("setDbAsInitialized", () => {+ it("is a no-op when the DB is already initialized and does not re-emit DB_INITIALIZED", () => {+ let dbInitializedEmitted = false;+ eventService.subscribe(eventService.DB_INITIALIZED, () => {+ dbInitializedEmitted = true;+ });++ sqlInit.setDbAsInitialized();++ // The `!isDbInitialized()` guard skips both the option write and the event emit.+ expect(dbInitializedEmitted).toBe(false);+ expect(sqlInit.isDbInitialized()).toBe(true);+ });+ });++ describe("initDbConnection", () => {+ it("creates the param_list and user_data tables and resolves dbReady", async () => {+ await withContext(() => sqlInit.initDbConnection());++ // The connection setup creates these auxiliary tables idempotently.+ expect(+ getSql().getValue(+ "SELECT name FROM sqlite_master WHERE type IN ('table') AND name = 'user_data'"+ )+ ).toBe("user_data");+ expect(+ getSql().getValue(+ "SELECT name FROM sqlite_temp_master WHERE type = 'table' AND name = 'param_list'"+ )+ ).toBe("param_list");++ // dbReady is the exported deferred promise, resolved once the+ // connection is ready; awaiting it must not hang.+ await expect(Promise.resolve(sqlInit.dbReady)).resolves.toBeUndefined();+ });+ });+});diff --git a/packages/trilium-core/src/services/task_context.spec.ts b/packages/trilium-core/src/services/task_context.spec.tsnew file mode 100644index 0000000000..e8ea5bf7ab--- /dev/null+++ b/packages/trilium-core/src/services/task_context.spec.ts@@ -0,0 +1,157 @@+import type { TaskData, TaskResult } from "@triliumnext/commons";+import { afterEach, beforeEach, describe, expect, it, type MockInstance, vi } from "vitest";++import TaskContext from "./task_context.js";+import ws from "./ws.js";++// task_context's only runtime side effect is ws.sendMessageToAllClients, which we+// spy on so we can assert the WebSocket messages it emits without a real server.+let sendMessageToAllClients: MockInstance;++const importData: TaskData<"importNotes"> = { safeImport: true };+const importResult: TaskResult<"importNotes"> = { importedNoteId: "abc123" };++describe("TaskContext", () => {+ beforeEach(() => {+ sendMessageToAllClients = vi+ .spyOn(ws, "sendMessageToAllClients")+ .mockImplementation(() => {});+ });++ afterEach(() => {+ vi.useRealTimers();+ vi.restoreAllMocks();+ });++ describe("construction", () => {+ it("emits an initial progress message on creation with the task metadata", () => {+ new TaskContext("ctor-1", "importNotes", importData);++ expect(sendMessageToAllClients).toHaveBeenCalledTimes(1);+ expect(sendMessageToAllClients).toHaveBeenCalledWith({+ type: "taskProgressCount",+ taskId: "ctor-1",+ taskType: "importNotes",+ data: importData,+ // progressCount starts at -1 and is incremented immediately on construction.+ progressCount: 0+ });+ });++ it("exposes the provided data and a default noteDeletionHandlerTriggered flag", () => {+ const ctx = new TaskContext("ctor-2", "importNotes", importData);++ expect(ctx.data).toBe(importData);+ expect(ctx.noteDeletionHandlerTriggered).toBe(false);+ });++ it("does not emit any message for the reserved no-progress-reporting task id", () => {+ new TaskContext("no-progress-reporting", "importNotes", importData);++ expect(sendMessageToAllClients).not.toHaveBeenCalled();+ });+ });++ describe("increaseProgressCount", () => {+ it("throttles progress messages to at most once per 300ms window", () => {+ vi.useFakeTimers();+ // lastSentCountTs starts at 0, so the constructor's first send only fires+ // when the clock is already >= 300ms past the epoch (always true with the+ // real wall clock); anchor the fake clock past that boundary to match.+ vi.setSystemTime(1_000);++ // Construction sends the first message (progressCount 0).+ const ctx = new TaskContext("throttle-1", "importNotes", importData);+ expect(sendMessageToAllClients).toHaveBeenCalledTimes(1);++ // Still inside the 300ms window since the last send: increments are coalesced.+ vi.setSystemTime(1_100);+ ctx.increaseProgressCount();+ vi.setSystemTime(1_299);+ ctx.increaseProgressCount();+ expect(sendMessageToAllClients).toHaveBeenCalledTimes(1);++ // Crossing the window boundary flushes a message carrying the accumulated count.+ vi.setSystemTime(1_300);+ ctx.increaseProgressCount();+ expect(sendMessageToAllClients).toHaveBeenCalledTimes(2);+ expect(sendMessageToAllClients).toHaveBeenLastCalledWith(+ expect.objectContaining({+ type: "taskProgressCount",+ taskId: "throttle-1",+ // 0 (ctor) + 3 increments = 3.+ progressCount: 3+ })+ );+ });++ it("never sends progress messages for the reserved no-progress-reporting id", () => {+ vi.useFakeTimers();+ vi.setSystemTime(0);++ const ctx = new TaskContext("no-progress-reporting", "importNotes", importData);+ vi.setSystemTime(10_000);+ ctx.increaseProgressCount();+ ctx.increaseProgressCount();++ expect(sendMessageToAllClients).not.toHaveBeenCalled();+ });+ });++ describe("reportError", () => {+ it("broadcasts a taskError message with the failure text and task metadata", () => {+ const ctx = new TaskContext("err-1", "importNotes", importData);+ sendMessageToAllClients.mockClear();++ ctx.reportError("something broke");++ expect(sendMessageToAllClients).toHaveBeenCalledTimes(1);+ expect(sendMessageToAllClients).toHaveBeenCalledWith({+ type: "taskError",+ taskId: "err-1",+ taskType: "importNotes",+ data: importData,+ message: "something broke"+ });+ });+ });++ describe("taskSucceeded", () => {+ it("broadcasts a taskSucceeded message carrying the result payload", () => {+ const ctx = new TaskContext("ok-1", "importNotes", importData);+ sendMessageToAllClients.mockClear();++ ctx.taskSucceeded(importResult);++ expect(sendMessageToAllClients).toHaveBeenCalledTimes(1);+ expect(sendMessageToAllClients).toHaveBeenCalledWith({+ type: "taskSucceeded",+ taskId: "ok-1",+ taskType: "importNotes",+ data: importData,+ result: importResult+ });+ });+ });++ describe("getInstance", () => {+ it("creates a single cached context per task id and reuses it on later lookups", () => {+ const first = TaskContext.getInstance("singleton-1", "importNotes", { safeImport: true });+ // Creating the instance emits its initial progress message.+ expect(sendMessageToAllClients).toHaveBeenCalledTimes(1);++ // A second lookup with the same id returns the cached instance without+ // constructing a new one (no additional initial-progress message), and+ // the originally cached data is preserved (the new data arg is ignored).+ const second = TaskContext.getInstance("singleton-1", "importNotes", { safeImport: false });+ expect(second).toBe(first);+ expect(second.data).toEqual({ safeImport: true });+ expect(sendMessageToAllClients).toHaveBeenCalledTimes(1);++ // A different id yields a distinct instance with its own initial message.+ const other = TaskContext.getInstance("singleton-2", "importNotes", { safeImport: true });+ expect(other).not.toBe(first);+ expect(sendMessageToAllClients).toHaveBeenCalledTimes(2);+ });+ });+});diff --git a/packages/trilium-core/src/services/task_states.spec.ts b/packages/trilium-core/src/services/task_states.spec.tsnew file mode 100644index 0000000000..4c4a28dada--- /dev/null+++ b/packages/trilium-core/src/services/task_states.spec.ts@@ -0,0 +1,243 @@+import {+ DEFAULT_TASK_STATES,+ DONE_STATE_ID,+ NONE_STATE_ID,+ TASK_STATES_CONTAINER_ID,+ type TaskStateDef+} from "@triliumnext/commons";+import { beforeAll, describe, expect, it } from "vitest";++import becca from "../becca/becca.js";+import BAttribute from "../becca/entities/battribute.js";+import type BNote from "../becca/entities/bnote.js";+import { getContext } from "./context.js";+import hiddenSubtreeService from "./hidden_subtree.js";+import { createTaskStateNote, generateTaskStateCss, getTaskStates } from "./task_states.js";++/**+ * Entity mutations (createNewNote, BAttribute.save, branch.save, markAsDeleted)+ * require an initialised CLS context.+ */+function withContext<T>(fn: () => T): T {+ return getContext().init(fn);+}++let counter = 0;++/** A self-contained, valid custom state with a unique name/symbol per call. */+function customState(overrides: Partial<TaskStateDef> = {}): TaskStateDef {+ counter++;+ return {+ name: `state${counter}`,+ title: `State ${counter}`,+ markdownSymbol: "",+ isCompleted: false,+ color: "#123456",+ icon: "bx bx-loader",+ ...overrides+ };+}++describe("task_states (real DB)", () => {+ beforeAll(() => {+ // Materialise the _taskStates container with its none/done anchors and the+ // seeded custom defaults into the shared in-memory fixture DB. Idempotent.+ withContext(() => hiddenSubtreeService.checkHiddenSubtree());+ });++ describe("getTaskStates", () => {+ it("returns the seeded default states with anchors mapped to their fixed definitions", () => {+ const states = getTaskStates();++ // The seeded container yields the full default ordered sequence.+ expect(states.map((s) => s.name)).toEqual(DEFAULT_TASK_STATES.map((s) => s.name));++ // The none/done anchors are returned as their fixed built-in definitions,+ // not reconstructed from the note's labels.+ const none = states.find((s) => s.id === NONE_STATE_ID);+ const done = states.find((s) => s.id === DONE_STATE_ID);+ expect(none).toMatchObject({ name: "none", markdownSymbol: " ", isCompleted: false });+ expect(done).toMatchObject({ name: "done", markdownSymbol: "x", isCompleted: true });++ // Custom states are read from their promoted labels.+ const doing = states.find((s) => s.name === "doing");+ expect(doing).toBeDefined();+ expect(doing!.markdownSymbol).toBe("/");+ expect(doing!.isCompleted).toBe(false);+ });++ it("ignores archived definition notes entirely", () => {+ const note = withContext(() =>+ createTaskStateNote(customState({ name: "archivedState", markdownSymbol: "@" }))+ );+ withContext(() => note.addLabel("archived"));+ expect(note.isArchived).toBe(true);++ const names = getTaskStates().map((s) => s.name);+ expect(names).not.toContain("archivedState");+ });++ it("drops invalid custom states while keeping the valid ones", () => {+ // A custom state with a name containing a space fails validation and is dropped.+ const invalid = withContext(() =>+ createTaskStateNote(customState({ name: "not valid", markdownSymbol: "!" }))+ );++ const states = getTaskStates();+ expect(states.some((s) => s.id === invalid.noteId)).toBe(false);+ // The seeded anchors and valid defaults survive the validation pass.+ expect(states.some((s) => s.id === NONE_STATE_ID)).toBe(true);+ expect(states.some((s) => s.id === DONE_STATE_ID)).toBe(true);+ });++ it("falls back to DEFAULT_TASK_STATES when the container note is missing", () => {+ const realContainer = becca.notes[TASK_STATES_CONTAINER_ID];+ try {+ // Temporarily hide the container so the early-return branch is hit.+ delete becca.notes[TASK_STATES_CONTAINER_ID];+ expect(getTaskStates()).toBe(DEFAULT_TASK_STATES);+ } finally {+ becca.notes[TASK_STATES_CONTAINER_ID] = realContainer;+ }+ });+ });++ describe("createTaskStateNote", () => {+ it("creates a doc note under the container with the promoted state labels", () => {+ const state = customState({+ name: "review",+ title: "Review",+ markdownSymbol: "r",+ isCompleted: true,+ color: "#ff8800",+ icon: "bx bx-search"+ });++ const note = withContext(() => createTaskStateNote(state));++ expect(note.type).toBe("doc");+ expect(note.title).toBe("Review");+ // Parented under the task states container.+ expect(+ note.getParentBranches().some((b) => b.parentNoteId === TASK_STATES_CONTAINER_ID)+ ).toBe(true);++ // The promoted attributes mirror the state definition (booleans stringified).+ expect(note.getLabelValue("stateId")).toBe("review");+ expect(note.getLabelValue("markdownSymbol")).toBe("r");+ expect(note.getLabelValue("isCompleted")).toBe("true");+ expect(note.getLabelValue("color")).toBe("#ff8800");+ expect(note.getLabelValue("iconClass")).toBe("bx bx-search");+ expect(note.getLabelValue("docName")).toBe("task_state");++ // Label attribute ids follow the deterministic `${noteId}_l${name}` scheme.+ const stateIdAttr = note.getOwnedAttributes("label", "stateId")[0];+ expect(stateIdAttr).toBeInstanceOf(BAttribute);+ expect(stateIdAttr.attributeId).toBe(`${note.noteId}_lstateId`);+ });++ it("honours the explicit noteId and title overrides", () => {+ counter++;+ const noteId = `customTaskStateSpec${counter}`;+ const note = withContext(() =>+ createTaskStateNote(customState({ name: `over${counter}`, markdownSymbol: "" }), {+ noteId,+ title: "Overridden title"+ })+ );++ expect(note.noteId).toBe(noteId);+ expect(note.title).toBe("Overridden title");+ expect(becca.notes[noteId]).toBe(note);+ });++ it("round-trips a created custom state through getTaskStates", () => {+ const state = customState({+ name: "roundtrip",+ title: "Round Trip",+ markdownSymbol: "~",+ isCompleted: false,+ color: "#00aa55",+ icon: "bx bx-time"+ });++ const note: BNote = withContext(() => createTaskStateNote(state));+ const read = getTaskStates().find((s) => s.id === note.noteId);++ expect(read).toBeDefined();+ expect(read).toMatchObject({+ name: "roundtrip",+ title: "Round Trip",+ markdownSymbol: "~",+ isCompleted: false,+ color: "#00aa55",+ icon: "bx bx-time",+ isHidden: false+ });+ });+ });++ describe("generateTaskStateCss", () => {+ it("emits a checkbox rule per non-anchor custom state with a resolvable icon", () => {+ const css = generateTaskStateCss();++ // Anchors (none/done) carry no custom checkbox glyph rule.+ expect(css).not.toContain(`[data-trilium-task-state="none"]`);+ expect(css).not.toContain(`[data-trilium-task-state="done"]`);++ // The seeded "doing" state uses `bx bx-loader`, which resolves against the+ // built-in boxicons manifest, so it produces a rule with the glyph/family vars.+ expect(css).toContain(`[data-trilium-task-state="doing"]`);+ expect(css).toContain("--task-state-glyph:");+ expect(css).toContain("--task-state-glyph-font-family:");+ });++ it("computes a hue var for chromatic colors and leaves grayscale colors as unset", () => {+ // "maybe" is seeded without a color → no hue, color falls back to inherit.+ const maybeNote = withContext(() =>+ createTaskStateNote(+ customState({ name: "graystate", markdownSymbol: "g", color: "#808080" })+ )+ );+ const colorNote = withContext(() =>+ createTaskStateNote(+ customState({ name: "colorstate", markdownSymbol: "c", color: "#ff0000" })+ )+ );++ const css = generateTaskStateCss();++ // Each state's selector appears twice in its rule, so take the tail after+ // the last occurrence — that segment holds the declaration block.+ const declBlock = (name: string) => {+ const parts = css.split(`[data-trilium-task-state="${name}"]`);+ return parts[parts.length - 1] ?? "";+ };++ // The grayscale state (zero saturation) yields `--task-state-hue: unset`.+ expect(declBlock("graystate")).toContain("--task-state-hue: unset");++ // The pure-red state has a defined hue (0) rather than unset.+ const colorBlock = declBlock("colorstate");+ expect(colorBlock).toContain("--task-state-hue: 0");+ expect(colorBlock).toContain("--task-state-color: #ff0000");++ expect(maybeNote.noteId).toBeTruthy();+ expect(colorNote.noteId).toBeTruthy();+ });++ it("skips states whose icon cannot be resolved to a glyph", () => {+ const note = withContext(() =>+ createTaskStateNote(+ customState({ name: "noicon", markdownSymbol: "n", icon: "bx bx-this-icon-does-not-exist" })+ )+ );+ expect(note.noteId).toBeTruthy();++ const css = generateTaskStateCss();+ // The state exists and is valid, but its icon does not map to a manifest+ // glyph, so generateTaskStateCss produces no rule for it.+ expect(css).not.toContain(`[data-trilium-task-state="noicon"]`);+ });+ });+});diff --git a/packages/trilium-core/src/services/utils/binary.spec.ts b/packages/trilium-core/src/services/utils/binary.spec.tsnew file mode 100644index 0000000000..7ef6b82c72Binary files /dev/null and b/packages/trilium-core/src/services/utils/binary.spec.ts differdiff --git a/packages/trilium-core/src/services/utils/date.spec.ts b/packages/trilium-core/src/services/utils/date.spec.tsnew file mode 100644index 0000000000..ce61bd2b9f--- /dev/null+++ b/packages/trilium-core/src/services/utils/date.spec.ts@@ -0,0 +1,182 @@+import { describe, expect, it } from "vitest";++import * as cls from "../context.js";+import date from "./date.js";++describe("date utils", () => {+ describe("constants", () => {+ it("exposes the local and UTC date-time formats", () => {+ expect(date.LOCAL_DATETIME_FORMAT).toBe("YYYY-MM-DD HH:mm:ss.SSSZZ");+ expect(date.UTC_DATETIME_FORMAT).toBe("YYYY-MM-DD HH:mm:ssZ");+ });+ });++ describe("utcDateStr", () => {+ it("returns only the date portion of an ISO string", () => {+ const d = new Date("2023-08-21T23:38:51.110Z");+ expect(date.utcDateStr(d)).toBe("2023-08-21");+ });+ });++ describe("utcDateTimeStr", () => {+ it("replaces the ISO 'T' separator with a space", () => {+ const d = new Date("2023-08-21T23:38:51.110Z");+ expect(date.utcDateTimeStr(d)).toBe("2023-08-21 23:38:51.110Z");+ });+ });++ describe("utcNowDateTime", () => {+ it("produces a space-separated UTC string ending in Z", () => {+ const result = date.utcNowDateTime();+ expect(result).toMatch(/^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]{3}Z$/);+ // it should describe roughly the current moment+ expect(Math.abs(Date.parse(result.replace(" ", "T")) - Date.now())).toBeLessThan(5000);+ });+ });++ describe("parseDateTime", () => {+ it("round-trips a value produced by utcDateTimeStr", () => {+ const original = new Date("2023-08-21T23:38:51.110Z");+ const parsed = date.parseDateTime(date.utcDateTimeStr(original));+ expect(parsed.getTime()).toBe(original.getTime());+ });++ it("parses a plain ISO string treating it as GMT", () => {+ const parsed = date.parseDateTime("2020-01-02T03:04:05.000Z");+ expect(parsed.toISOString()).toBe("2020-01-02T03:04:05.000Z");+ });++ it("returns an Invalid Date for an unparseable string rather than throwing", () => {+ // Date.parse() returns NaN (it does not throw), so the catch path is+ // never hit and the result is an Invalid Date instance.+ const parsed = date.parseDateTime("not-a-date");+ expect(parsed).toBeInstanceOf(Date);+ expect(Number.isNaN(parsed.getTime())).toBe(true);+ });+ });++ describe("parseLocalDate", () => {+ it("uses only the first 10 chars and anchors at local noon", () => {+ const parsed = date.parseLocalDate("2023-08-21 23:38:51.110+0200");+ expect(parsed.getFullYear()).toBe(2023);+ expect(parsed.getMonth()).toBe(7); // August (0-indexed)+ expect(parsed.getDate()).toBe(21);+ // parsed without a timezone => local time, anchored at 12:00:00+ expect(parsed.getHours()).toBe(12);+ expect(parsed.getMinutes()).toBe(0);+ expect(parsed.getSeconds()).toBe(0);+ });++ it("ignores the time component of the input entirely", () => {+ const a = date.parseLocalDate("2023-08-21 00:00:00.000+0000");+ const b = date.parseLocalDate("2023-08-21 23:59:59.999+0000");+ expect(a.getTime()).toBe(b.getTime());+ });+ });++ describe("getDateTimeForFile", () => {+ it("returns a colon-free 15-char timestamp suitable for filenames", () => {+ const result = date.getDateTimeForFile();+ expect(result).not.toContain(":");+ // YYYY-MM-DDTHHMMSS+ expect(result).toMatch(/^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{6}$/);+ });+ });++ describe("validateLocalDateTime", () => {+ it("returns undefined for empty / nullish input", () => {+ expect(date.validateLocalDateTime("")).toBeUndefined();+ expect(date.validateLocalDateTime(null)).toBeUndefined();+ expect(date.validateLocalDateTime(undefined)).toBeUndefined();+ });++ it("returns undefined for a well-formed local date time", () => {+ expect(date.validateLocalDateTime("2023-08-21 23:38:51.110+0200")).toBeUndefined();+ expect(date.validateLocalDateTime("2023-08-21 23:38:51.110-0500")).toBeUndefined();+ });++ it("returns a format error message for malformed input", () => {+ // UTC "Z" form is not valid local form+ const utcForm = date.validateLocalDateTime("2023-08-21 23:38:51.110Z");+ expect(utcForm).toContain("Invalid local date time format");++ // missing milliseconds+ expect(date.validateLocalDateTime("2023-08-21 23:38:51+0200")).toContain(+ "Invalid local date time format"+ );++ // missing the offset sign/digits+ expect(date.validateLocalDateTime("2023-08-21 23:38:51.110")).toContain(+ "Invalid local date time format"+ );++ // entirely wrong shape+ expect(date.validateLocalDateTime("not a date")).toContain(+ "Invalid local date time format"+ );+ });+ });++ describe("validateUtcDateTime", () => {+ it("returns undefined for empty / undefined input", () => {+ expect(date.validateUtcDateTime("")).toBeUndefined();+ expect(date.validateUtcDateTime(undefined)).toBeUndefined();+ });++ it("returns undefined for a well-formed UTC date time", () => {+ expect(date.validateUtcDateTime("2023-08-21 23:38:51.110Z")).toBeUndefined();+ });++ it("returns a format error message for malformed input", () => {+ // local offset form is not valid UTC form+ expect(date.validateUtcDateTime("2023-08-21 23:38:51.110+0200")).toContain(+ "Invalid UTC date time format"+ );++ // missing milliseconds+ expect(date.validateUtcDateTime("2023-08-21 23:38:51Z")).toContain(+ "Invalid UTC date time format"+ );++ // entirely wrong shape+ expect(date.validateUtcDateTime("garbage")).toContain("Invalid UTC date time format");+ });+ });++ describe("localNowDateTime", () => {+ it("falls back to the current local time when no CLS value is set", () => {+ const result = date.localNowDateTime();+ expect(result).toMatch(+ /^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]{3}[+-][0-9]{4}$/+ );+ });++ it("returns the CLS-provided value verbatim when present", () => {+ const stored = "2023-08-21 23:38:51.110+0200";+ const result = cls.init(() => {+ cls.set("localNowDateTime", stored);+ return date.localNowDateTime();+ });+ expect(result).toBe(stored);+ });+ });++ describe("localNowDate", () => {+ it("derives today's date in YYYY-MM-DD form when no CLS value is set", () => {+ const result = date.localNowDate();+ expect(result).toMatch(/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/);++ const now = new Date();+ const expected = `${now.getFullYear()}-${`${now.getMonth() + 1}`.padStart(2, "0")}-${`${now.getDate()}`.padStart(2, "0")}`;+ expect(result).toBe(expected);+ });++ it("extracts the date portion from the CLS value when present", () => {+ const result = cls.init(() => {+ cls.set("localNowDateTime", "2023-08-21 23:38:51.110+0200");+ return date.localNowDate();+ });+ expect(result).toBe("2023-08-21");+ });+ });+});