Skip to content

Build your personal knowledge base with Trilium Notes

Merge remote-tracking branch 'origin/main' into standalone

Elian Doran28c6826b35d5
diff --cc apps/build-docs/package.json
index cbfebddae5,cae84da510..dfaf54bd4c
--- a/apps/build-docs/package.json
+++ b/apps/build-docs/package.json
@@@ -15,12 -15,8 +15,12 @@@
"author": "Elian Doran <[email protected]>",
"license": "AGPL-3.0-only",
"packageManager": "[email protected]",
+ "dependencies": {
+ "@triliumnext/core": "workspace:*",
+ "@triliumnext/server": "workspace:*"
+ },
"devDependencies": {
- "@redocly/cli": "2.26.0",
+ "@redocly/cli": "2.28.0",
"archiver": "7.0.1",
"fs-extra": "11.3.4",
"js-yaml": "4.1.1",
diff --cc apps/client/src/widgets/dialogs/revisions.tsx
index 6f0850651f,787264b1ac..2e2094267c
--- a/apps/client/src/widgets/dialogs/revisions.tsx
+++ b/apps/client/src/widgets/dialogs/revisions.tsx
@@@ -296,29 -582,21 +582,21 @@@ function RevisionContentText({ content
function RevisionContentDiff({ noteContent, itemContent, itemType }: {
noteContent?: string,
- itemContent: string | Buffer<ArrayBufferLike> | undefined,
+ itemContent: string | Uint8Array | undefined,
itemType: string
}) {
- const contentRef = useRef<HTMLDivElement>(null);
-
- useEffect(() => {
- if (!noteContent || typeof itemContent !== "string") {
- if (contentRef.current) {
- contentRef.current.textContent = t("revisions.diff_not_available");
- }
- return;
- }
-
- let processedNoteContent = noteContent;
- let processedItemContent = itemContent;
-
- if (itemType === "text") {
- processedNoteContent = utils.formatHtml(noteContent);
- processedItemContent = utils.formatHtml(itemContent);
- }
+ if (!noteContent || typeof itemContent !== "string") {
+ return <div className="revision-diff-content">{t("revisions.diff_not_available")}</div>;
+ }
- const diff = diffWords(processedNoteContent, processedItemContent);
- const diffHtml = diff.map(part => {
+ let diffHtml: string;
+ if (itemType === "text") {
+ // Use proper HTML-aware diff for rich text content
+ diffHtml = HtmlDiff.execute(noteContent, itemContent);
+ } else {
+ // Use word diff for code/mermaid (plain text)
+ const diff = diffWords(noteContent, itemContent);
+ diffHtml = diff.map(part => {
if (part.added) {
return `<span class="revision-diff-added">${utils.escapeHtml(part.value)}</span>`;
} else if (part.removed) {
diff --cc apps/desktop/src/main.ts
index 9045aa1dcb,508e7be7e7..c08e314544
--- a/apps/desktop/src/main.ts
+++ b/apps/desktop/src/main.ts
@@@ -1,30 -1,17 +1,30 @@@
-import { initializeTranslations } from "@triliumnext/server/src/services/i18n.js";
-import { t } from "i18next";
-
-import { app, globalShortcut, BrowserWindow } from "electron";
-import sqlInit from "@triliumnext/server/src/services/sql_init.js";
-import windowService from "@triliumnext/server/src/services/window.js";
+import { getLog, initializeCore, sql_init } from "@triliumnext/core";
+import ClsHookedExecutionContext from "@triliumnext/server/src/cls_provider.js";
+import NodejsCryptoProvider from "@triliumnext/server/src/crypto_provider.js";
+import { loadCoreSchema } from "@triliumnext/server/src/core_assets.js";
+import NodejsInAppHelpProvider from "@triliumnext/server/src/in_app_help_provider.js";
+import dataDirs from "@triliumnext/server/src/services/data_dir.js";
+import { options } from "@triliumnext/core";
+import port from "@triliumnext/server/src/services/port.js";
+import NodeRequestProvider from "@triliumnext/server/src/services/request.js";
+import { RESOURCE_DIR } from "@triliumnext/server/src/services/resource_dir.js";
import tray from "@triliumnext/server/src/services/tray.js";
-import options from "@triliumnext/server/src/services/options.js";
+import windowService from "@triliumnext/server/src/services/window.js";
+import WebSocketMessagingProvider from "@triliumnext/server/src/services/ws_messaging_provider.js";
+import ServerBackupService from "@triliumnext/server/src/backup_provider.js";
+import ServerLogService from "@triliumnext/server/src/log_provider.js";
+import BetterSqlite3Provider from "@triliumnext/server/src/sql_provider.js";
+import NodejsZipProvider from "@triliumnext/server/src/zip_provider.js";
+import { app, BrowserWindow,globalShortcut } from "electron";
import electronDebug from "electron-debug";
import electronDl from "electron-dl";
-import { PRODUCT_NAME } from "./app-info";
-import port from "@triliumnext/server/src/services/port.js";
-import { join, resolve } from "path";
+import fs from "fs";
+import { t } from "i18next";
- import path, { join } from "path";
++import path, { join, resolve } from "path";
+
import { deferred, LOCALES } from "../../../packages/commons/src";
+import { PRODUCT_NAME } from "./app-info";
+import DesktopPlatformProvider from "./platform_provider";
async function main() {
const userDataPath = getUserData();
diff --cc apps/server/package.json
index 2e6563a863,0e5e75acf8..bab158adcb
--- a/apps/server/package.json
+++ b/apps/server/package.json
@@@ -31,17 -30,17 +31,17 @@@
"proxy-nginx-subdir": "docker run --name trilium-nginx-subdir --rm --network=host -v ./docker/nginx.conf:/etc/nginx/conf.d/default.conf:ro nginx:latest"
},
"dependencies": {
- "@ai-sdk/anthropic": "3.0.68",
- "@ai-sdk/google": "3.0.60",
- "@ai-sdk/openai": "3.0.52",
+ "@ai-sdk/anthropic": "3.0.69",
+ "@ai-sdk/google": "3.0.63",
+ "@ai-sdk/openai": "3.0.53",
"@modelcontextprotocol/sdk": "^1.12.1",
- "ai": "6.0.154",
- "better-sqlite3": "12.8.0",
+ "ai": "6.0.161",
+ "better-sqlite3": "12.9.0",
"html-to-text": "9.0.5",
+ "i18next-fs-backend": "2.6.3",
+ "i18next": "26.0.4",
"js-yaml": "4.1.1",
- "unpdf": "1.4.0"
- "node-html-parser": "7.1.0",
- "sucrase": "3.35.1",
+ "unpdf": "1.6.0"
},
"devDependencies": {
"@braintree/sanitize-url": "7.1.2",
@@@ -82,9 -87,10 +82,9 @@@
"csrf-csrf": "4.0.3",
"debounce": "3.0.0",
"debug": "4.4.3",
- "ejs": "5.0.1",
+ "ejs": "5.0.2",
"electron": "41.2.0",
"electron-window-state": "5.0.3",
- "escape-html": "1.0.3",
"express": "5.2.1",
"express-http-proxy": "2.1.2",
"express-openid-connect": "2.20.1",
@@@ -103,11 -111,14 +103,11 @@@
"is-svg": "6.1.0",
"jimp": "1.6.1",
"marked": "18.0.0",
- "mime-types": "3.0.2",
"multer": "2.1.1",
"normalize-strings": "1.1.1",
- "officeparser": "6.0.7",
+ "officeparser": "6.1.0",
"rand-token": "1.0.1",
"safe-compare": "1.1.4",
- "sanitize-filename": "1.6.4",
- "sanitize-html": "2.17.3",
"sax": "1.6.0",
"serve-favicon": "2.5.1",
"stream-throttle": "0.1.3",
@@@ -117,7 -129,9 +117,7 @@@
"time2fa": "1.4.2",
"tmp": "0.2.5",
"turnish": "1.8.0",
- "vite": "8.0.7",
- "unescape": "1.0.1",
+ "vite": "8.0.8",
- "ws": "8.20.0",
"xml2js": "0.6.2",
"yauzl": "3.3.0"
}
diff --cc apps/server/src/routes/api/fonts.ts
index 7ef814526a,d9882a4101..8973662c7d
--- a/apps/server/src/routes/api/fonts.ts
+++ b/apps/server/src/routes/api/fonts.ts
@@@ -1,26 -1,7 +1,9 @@@
- import type { OptionMap } from "@triliumnext/commons";
++import { SYSTEM_MONOSPACE_FONT_STACK, SYSTEM_SANS_SERIF_FONT_STACK, type OptionMap } from "@triliumnext/commons";
+import { sql_init } from "@triliumnext/core";
import type { Request, Response } from "express";
+
import optionService from "../../services/options.js";
-import { SYSTEM_MONOSPACE_FONT_STACK, SYSTEM_SANS_SERIF_FONT_STACK, type OptionMap } from "@triliumnext/commons";
- const SYSTEM_SANS_SERIF = [
- "system-ui",
- "-apple-system",
- "BlinkMacSystemFont",
- "Segoe UI",
- "Cantarell",
- "Ubuntu",
- "Noto Sans",
- "Helvetica",
- "Arial",
- "sans-serif",
- "Apple Color Emoji",
- "Segoe UI Emoji"
- ].join(",");
-
- const SYSTEM_MONOSPACE = ["ui-monospace", "SFMono-Regular", "SF Mono", "Consolas", "Source Code Pro", "Ubuntu Mono", "Menlo", "Liberation Mono", "monospace"].join(",");
-
function getFontCss(req: Request, res: Response) {
res.setHeader("Content-Type", "text/css");
diff --cc packages/commons/src/lib/server_api.ts
index 115699f448,63e5c63680..2ea0bea19b
--- a/packages/commons/src/lib/server_api.ts
+++ b/packages/commons/src/lib/server_api.ts
@@@ -1,5 -1,4 +1,5 @@@
-import { AttachmentRow, AttributeRow, BranchRow, NoteRow, NoteType, RevisionSource } from "./rows.js";
+import type { Locale } from "./i18n.js";
- import { AttachmentRow, AttributeRow, BranchRow, NoteRow, NoteType, OptionRow } from "./rows.js";
++import { AttachmentRow, AttributeRow, BranchRow, NoteRow, NoteType, OptionRow, RevisionSource } from "./rows.js";
type Response = {
success: true,
diff --cc packages/trilium-core/src/becca/becca-interface.ts
index ef817ca60f,f1e7c7fde3..e29c7d63c9
--- a/packages/trilium-core/src/becca/becca-interface.ts
+++ b/packages/trilium-core/src/becca/becca-interface.ts
@@@ -1,4 -1,8 +1,6 @@@
-import sql from "../services/sql.js";
-import log from "../services/log.js";
-import { formatSize } from "../services/utils.js";
-import NoteSet from "../services/search/note_set.js";
-import NotFoundError from "../errors/not_found_error.js";
+import { NotFoundError } from "../errors.js";
++import { getLog } from "../services/log.js";
++import { formatSize } from "../services/utils/index.js";
import type BOption from "./entities/boption.js";
import type BNote from "./entities/bnote.js";
import type BEtapiToken from "./entities/betapi_token.js";
@@@ -242,6 -257,67 +257,67 @@@ export default class Becca
/** Should be called when the set of all non-skeleton notes changes (added/removed) */
dirtyNoteSetCache() {
this.allNoteSetCache = null;
+ // Full rebuild needed since the note set itself changed
+ this.flatTextIndex = null;
+ this.dirtyFlatTextNoteIds.clear();
+ }
+
+ /** Mark a single note's flat text as needing recomputation in the index. */
+ dirtyNoteFlatText(noteId: string) {
+ if (this.flatTextIndex) {
+ // Index exists — schedule an incremental update
+ this.dirtyFlatTextNoteIds.add(noteId);
+ }
+ // If flatTextIndex is null, full rebuild will happen on next access anyway
+ }
+
+ /**
+ * Returns pre-built parallel arrays of notes and their flat texts for fast scanning.
+ * The flat texts are already normalized (lowercase, diacritics removed).
+ * Supports incremental updates: when individual notes are dirtied, only their
+ * entries are recomputed rather than rebuilding the entire index.
+ */
+ getFlatTextIndex(): { notes: BNote[], flatTexts: string[], noteIdToIdx: Map<string, number> } {
+ if (!this.flatTextIndex) {
+ // Measure heap before building
+ const heapBefore = process.memoryUsage().heapUsed;
+
+ const allNoteSet = this.getAllNoteSet();
+ const notes: BNote[] = [];
+ const flatTexts: string[] = [];
+ const noteIdToIdx = new Map<string, number>();
+
+ for (const note of allNoteSet.notes) {
+ noteIdToIdx.set(note.noteId, notes.length);
+ notes.push(note);
+ flatTexts.push(note.getFlatText());
+ }
+
+ this.flatTextIndex = { notes, flatTexts, noteIdToIdx };
+ this.dirtyFlatTextNoteIds.clear();
+
+ // Measure heap after building and log
+ const heapAfter = process.memoryUsage().heapUsed;
+ const heapDelta = heapAfter - heapBefore;
- log.info(`Flat text search index built: ${notes.length} notes, ${formatSize(heapDelta)}`);
++ getLog().info(`Flat text search index built: ${notes.length} notes, ${formatSize(heapDelta)}`);
+ } else if (this.dirtyFlatTextNoteIds.size > 0) {
+ // Incremental update: only recompute flat texts for dirtied notes
+ const { flatTexts, noteIdToIdx } = this.flatTextIndex;
+
+ for (const noteId of this.dirtyFlatTextNoteIds) {
+ const idx = noteIdToIdx.get(noteId);
+ if (idx !== undefined) {
+ const note = this.notes[noteId];
+ if (note) {
+ flatTexts[idx] = note.getFlatText();
+ }
+ }
+ }
+
+ this.dirtyFlatTextNoteIds.clear();
+ }
+
+ return this.flatTextIndex;
}
getAllNoteSet() {
diff --cc packages/trilium-core/src/becca/entities/bnote.ts
index 3e9fe6fa35,0000000000..9ba1c96e64
mode 100644,000000..100644
--- a/packages/trilium-core/src/becca/entities/bnote.ts
+++ b/packages/trilium-core/src/becca/entities/bnote.ts
@@@ -1,1786 -1,0 +1,1788 @@@
- import type { AttachmentRow, AttributeType, CloneResponse, NoteRow, NoteType, RevisionRow } from "@triliumnext/commons";
++import type { AttachmentRow, AttributeType, CloneResponse, NoteRow, NoteType, RevisionRow, RevisionSource } from "@triliumnext/commons";
+import { dayjs, getNoteIcon } from "@triliumnext/commons";
+
+import cloningService from "../../services/cloning.js";
+import dateUtils from "../../services/utils/date.js";
+import eraseService from "../../services/erase.js";
+import eventService from "../../services/events.js";
+import handlers from "../../services/handlers.js";
+import noteService from "../../services/notes.js";
+import optionService from "../../services/options.js";
+import protectedSessionService from "../../services/protected_session.js";
+import searchService from "../../services/search/services/search.js";
+import TaskContext from "../../services/task_context.js";
+import type { NotePojo } from "../becca-interface.js";
+import AbstractBeccaEntity from "./abstract_becca_entity.js";
+import BAttachment from "./battachment.js";
+import BAttribute from "./battribute.js";
+import type BBranch from "./bbranch.js";
+import BRevision from "./brevision.js";
+import { getLog } from "../../services/log.js";
+import { getSql } from "../../services/sql/index.js";
+import { formatDownloadTitle, isStringNote, normalize, randomString, replaceAll } from "../../services/utils/index.js";
+import scriptService from "../../services/script.js";
+
+const LABEL = "label";
+const RELATION = "relation";
+
+interface NotePathRecord {
+ isArchived: boolean;
+ isInHoistedSubTree: boolean;
+ notePath: string[];
+ isHidden: boolean;
+}
+
+interface ContentOpts {
+ /** will also save this BNote entity */
+ forceSave?: boolean;
+ /** override frontend heuristics on when to reload, instruct to reload */
+ forceFrontendReload?: boolean;
+}
+
+interface Relationship {
+ parentNoteId: string;
+ childNoteId: string;
+}
+
+interface ConvertOpts {
+ /** if true, the action is not triggered by user, but e.g. by migration, and only perfect candidates will be migrated */
+ autoConversion?: boolean;
+}
+
+/**
+ * Trilium's main entity, which can represent text note, image, code note, file attachment etc.
+ */
+class BNote extends AbstractBeccaEntity<BNote> {
+ static get entityName() {
+ return "notes";
+ }
+ static get primaryKeyName() {
+ return "noteId";
+ }
+ static get hashedProperties() {
+ return ["noteId", "title", "isProtected", "type", "mime", "blobId"];
+ }
+
+ noteId!: string;
+ title!: string;
+ type!: NoteType;
+ mime!: string;
+ /** set during the deletion operation, before it is completed (removed from becca completely). */
+ isBeingDeleted!: boolean;
+ isDecrypted!: boolean;
+
+ ownedAttributes!: BAttribute[];
+ parentBranches!: BBranch[];
+ parents!: BNote[];
+ children!: BNote[];
+ targetRelations!: BAttribute[];
+
+ __flatTextCache!: string | null;
+
+ private __attributeCache!: BAttribute[] | null;
+ private __inheritableAttributeCache!: BAttribute[] | null;
+ private __ancestorCache!: BNote[] | null;
+
+ // following attributes are filled during searching in the database
+ /** size of the content in bytes */
+ contentSize!: number | null;
+ /** size of the note content, attachment contents in bytes */
+ contentAndAttachmentsSize!: number | null;
+ /** size of the note content, attachment contents and revision contents in bytes */
+ contentAndAttachmentsAndRevisionsSize!: number | null;
+ /** number of note revisions for this note */
+ revisionCount!: number | null;
+
+ constructor(row?: Partial<NoteRow>) {
+ super();
+
+ if (!row) {
+ return;
+ }
+
+ this.updateFromRow(row);
+ this.init();
+ }
+
+ updateFromRow(row: Partial<NoteRow>) {
+ this.update([row.noteId, row.title, row.type, row.mime, row.isProtected, row.blobId, row.dateCreated, row.dateModified, row.utcDateCreated, row.utcDateModified]);
+ }
+
+ update([noteId, title, type, mime, isProtected, blobId, dateCreated, dateModified, utcDateCreated, utcDateModified]: any) {
+ // ------ Database persisted attributes ------
+
+ this.noteId = noteId;
+ this.title = title;
+ this.type = type;
+ this.mime = mime;
+ this.isProtected = !!isProtected;
+ this.blobId = blobId;
+ this.dateCreated = dateCreated || dateUtils.localNowDateTime();
+ this.dateModified = dateModified;
+ this.utcDateCreated = utcDateCreated || dateUtils.utcNowDateTime();
+ this.utcDateModified = utcDateModified;
+ this.isBeingDeleted = false;
+
+ // ------ Derived attributes ------
+
+ this.isDecrypted = !this.noteId || !this.isProtected;
+
+ this.decrypt();
+
+ this.__flatTextCache = null;
+
+ return this;
+ }
+
+ override init() {
+ this.parentBranches = [];
+ this.parents = [];
+ this.children = [];
+ this.ownedAttributes = [];
+ this.__attributeCache = null;
+ this.__inheritableAttributeCache = null;
+ this.targetRelations = [];
+
+ this.becca.addNote(this.noteId, this);
+ this.__ancestorCache = null;
+
+ this.contentSize = null;
+ this.contentAndAttachmentsSize = null;
+ this.contentAndAttachmentsAndRevisionsSize = null;
+ this.revisionCount = null;
+ }
+
+ isContentAvailable() {
+ return (
+ !this.noteId || // new note which was not encrypted yet
+ !this.isProtected ||
+ protectedSessionService.isProtectedSessionAvailable()
+ );
+ }
+
+ getTitleOrProtected() {
+ return this.isContentAvailable() ? this.title : "[protected]";
+ }
+
+ getParentBranches() {
+ return this.parentBranches;
+ }
+
+ /**
+ * Returns <i>strong</i> (as opposed to <i>weak</i>) parent branches. See isWeak for details.
+ */
+ getStrongParentBranches() {
+ return this.getParentBranches().filter((branch) => !branch.isWeak);
+ }
+
+ /**
+ * @deprecated use getParentBranches() instead
+ */
+ getBranches() {
+ return this.parentBranches;
+ }
+
+ getParentNotes() {
+ return this.parents;
+ }
+
+ getChildNotes() {
+ return this.children;
+ }
+
+ hasChildren() {
+ return this.children && this.children.length > 0;
+ }
+
+ getChildBranches(): BBranch[] {
+ return this.children.map((childNote) => this.becca.getBranchFromChildAndParent(childNote.noteId, this.noteId)) as BBranch[];
+ }
+
+ /**
+ * Note content has quite special handling - it's not a separate entity, but a lazily loaded
+ * part of Note entity with its own sync. Reasons behind this hybrid design has been:
+ *
+ * - content can be quite large, and it's not necessary to load it / fill memory for any note access even if we don't need a content, especially for bulk operations like search
+ * - changes in the note metadata or title should not trigger note content sync (so we keep separate utcDateModified and entity changes records)
+ * - but to the user note content and title changes are one and the same - single dateModified (so all changes must go through Note and content is not a separate entity)
+ */
+ getContent() {
+ return this._getContent();
+ }
+
+ /**
+ * @throws Error in case of invalid JSON
+ */
+ getJsonContent(): any | null {
+ const content = this.getContent();
+
+ if (typeof content !== "string" || !content || !content.trim()) {
+ return null;
+ }
+
+ return JSON.parse(content);
+ }
+
+ /** @returns valid object or null if the content cannot be parsed as JSON */
+ getJsonContentSafely() {
+ try {
+ return this.getJsonContent();
+ } catch (e) {
+ return null;
+ }
+ }
+
+ setContent(content: Uint8Array | string, opts: ContentOpts = {}) {
+ this._setContent(content, opts);
+
+ eventService.emit(eventService.NOTE_CONTENT_CHANGE, { entity: this });
+ }
+
+ setJsonContent(content: {}) {
+ this.setContent(JSON.stringify(content, null, "\t"));
+ }
+
+ get dateCreatedObj() {
+ return this.dateCreated === null ? null : dayjs(this.dateCreated);
+ }
+
+ get utcDateCreatedObj() {
+ return this.utcDateCreated === null ? null : dayjs.utc(this.utcDateCreated);
+ }
+
+ get dateModifiedObj() {
+ return this.dateModified === null ? null : dayjs(this.dateModified);
+ }
+
+ get utcDateModifiedObj() {
+ return this.utcDateModified === null ? null : dayjs.utc(this.utcDateModified);
+ }
+
+ /** @returns true if this note is the root of the note tree. Root note has "root" noteId */
+ isRoot() {
+ return this.noteId === "root";
+ }
+
+ /** @returns true if this note is of application/json content type */
+ isJson() {
+ return this.mime === "application/json";
+ }
+
+ /** @returns true if this note is JavaScript (code or attachment) */
+ isJavaScript() {
+ return (
+ (this.type === "code" || this.type === "file" || this.type === "launcher") &&
+ (this.mime.startsWith("application/javascript") || this.mime === "application/x-javascript" || this.mime === "text/javascript")
+ );
+ }
+
+ isJsx() {
+ return (this.type === "code" && this.mime === "text/jsx");
+ }
+
+ /** @returns true if this note is HTML */
+ isHtml() {
+ return ["code", "file", "render"].includes(this.type) && this.mime === "text/html";
+ }
+
+ /** @returns true if this note is an image */
+ isImage() {
+ return this.type === "image" || (this.type === "file" && this.mime?.startsWith("image/"));
+ }
+
+ /** @deprecated use hasStringContent() instead */
+ isStringNote() {
+ return this.hasStringContent();
+ }
+
+ /** @returns true if the note has string content (not binary) */
+ override hasStringContent() {
+ return isStringNote(this.type, this.mime);
+ }
+
+ /** @returns JS script environment - either "frontend" or "backend" */
+ getScriptEnv() {
+ if (this.isHtml() || (this.isJavaScript() && this.mime.endsWith("env=frontend")) || this.isJsx()) {
+ return "frontend";
+ }
+
+ if (this.type === "render") {
+ return "frontend";
+ }
+
+ if (this.isJavaScript() && this.mime.endsWith("env=backend")) {
+ return "backend";
+ }
+
+ return null;
+ }
+
+ /**
+ * Executes this note as a script. The note must be of type "Code: JS backend".
+ *
+ * @returns the return value of the executed script
+ */
+ executeScript() {
+ return scriptService.executeNote(this, { originEntity: this });
+ }
+
+ /**
+ * Beware that the method must not create a copy of the array, but actually returns its internal array
+ * (for performance reasons)
+ *
+ * @param type - (optional) attribute type to filter
+ * @param name - (optional) attribute name to filter
+ * @returns all note's attributes, including inherited ones
+ */
+ getAttributes(type?: string, name?: string): BAttribute[] {
+ this.__validateTypeName(type, name);
+ this.__ensureAttributeCacheIsAvailable();
+
+ if (!this.__attributeCache) {
+ throw new Error("Attribute cache not available.");
+ }
+
+ if (type && name) {
+ return this.__attributeCache.filter((attr) => attr.name === name && attr.type === type);
+ } else if (type) {
+ return this.__attributeCache.filter((attr) => attr.type === type);
+ } else if (name) {
+ return this.__attributeCache.filter((attr) => attr.name === name);
+ }
+ return this.__attributeCache;
+ }
+
+ private __ensureAttributeCacheIsAvailable() {
+ if (!this.__attributeCache) {
+ this.__getAttributes([]);
+ }
+ }
+
+ private __getAttributes(path: string[]) {
+ if (path.includes(this.noteId)) {
+ return [];
+ }
+
+ if (!this.__attributeCache) {
+ const parentAttributes = this.ownedAttributes.slice();
+ const newPath = [...path, this.noteId];
+
+ // inheritable attrs on root are typically not intended to be applied to hidden subtree #3537
+ if (this.noteId !== "root" && this.noteId !== "_hidden") {
+ for (const parentNote of this.parents) {
+ parentAttributes.push(...parentNote.__getInheritableAttributes(newPath));
+ }
+ }
+
+ const templateAttributes: BAttribute[] = [];
+
+ for (const ownedAttr of parentAttributes) {
+ // parentAttributes so we process also inherited templates
+ if (ownedAttr.type === "relation" && ["template", "inherit"].includes(ownedAttr.name)) {
+ const templateNote = this.becca.notes[ownedAttr.value];
+
+ if (templateNote) {
+ templateAttributes.push(
+ ...templateNote
+ .__getAttributes(newPath)
+ // template attr is used as a marker for templates, but it's not meant to be inherited
+ .filter((attr) => !(attr.type === "label" && (attr.name === "template" || attr.name === "workspacetemplate")))
+ );
+ }
+ }
+ }
+
+ this.__attributeCache = [];
+
+ const addedAttributeIds = new Set();
+
+ for (const attr of parentAttributes.concat(templateAttributes)) {
+ if (!addedAttributeIds.has(attr.attributeId)) {
+ addedAttributeIds.add(attr.attributeId);
+
+ this.__attributeCache.push(attr);
+ }
+ }
+
+ this.__inheritableAttributeCache = [];
+
+ for (const attr of this.__attributeCache) {
+ if (attr.isInheritable) {
+ this.__inheritableAttributeCache.push(attr);
+ }
+ }
+ }
+
+ return this.__attributeCache;
+ }
+
+ private __getInheritableAttributes(path: string[]): BAttribute[] {
+ if (path.includes(this.noteId)) {
+ return [];
+ }
+
+ if (!this.__inheritableAttributeCache) {
+ this.__getAttributes(path); // will refresh also this.__inheritableAttributeCache
+ }
+
+ return this.__inheritableAttributeCache || [];
+ }
+
+ __validateTypeName(type?: string | null, name?: string | null) {
+ if (type && type !== "label" && type !== "relation") {
+ throw new Error(`Unrecognized attribute type '${type}'. Only 'label' and 'relation' are possible values.`);
+ }
+
+ if (name) {
+ const firstLetter = name.charAt(0);
+ if (firstLetter === "#" || firstLetter === "~") {
+ throw new Error(`Detect '#' or '~' in the attribute's name. In the API, attribute names should be set without these characters.`);
+ }
+ }
+ }
+
+ hasAttribute(type: string, name: string, value: string | null = null): boolean {
+ return !!this.getAttributes().find((attr) => attr.name === name && (value === undefined || value === null || attr.value === value) && attr.type === type);
+ }
+
+ getAttributeCaseInsensitive(type: string, name: string, value?: string | null) {
+ name = name.toLowerCase();
+ value = value ? value.toLowerCase() : null;
+
+ return this.getAttributes().find((attr) => attr.name.toLowerCase() === name && (!value || attr.value.toLowerCase() === value) && attr.type === type);
+ }
+
+ getRelationTarget(name: string) {
+ const relation = this.getAttributes().find((attr) => attr.name === name && attr.type === "relation");
+
+ return relation ? relation.targetNote : null;
+ }
+
+ /**
+ * @param name - label name
+ * @param value - label value
+ * @returns true if label exists (including inherited)
+ */
+ hasLabel(name: string, value?: string): boolean {
+ return this.hasAttribute(LABEL, name, value);
+ }
+
+ /**
+ * @param name - label name
+ * @returns true if label exists (including inherited) and does not have "false" value.
+ */
+ isLabelTruthy(name: string): boolean {
+ const label = this.getLabel(name);
+
+ if (!label) {
+ return false;
+ }
+
+ return label && label.value !== "false";
+ }
+
+ /**
+ * @param name - label name
+ * @param value - label value
+ * @returns true if label exists (excluding inherited)
+ */
+ hasOwnedLabel(name: string, value?: string): boolean {
+ return this.hasOwnedAttribute(LABEL, name, value);
+ }
+
+ /**
+ * @param name - relation name
+ * @param value - relation value
+ * @returns true if relation exists (including inherited)
+ */
+ hasRelation(name: string, value?: string): boolean {
+ return this.hasAttribute(RELATION, name, value);
+ }
+
+ /**
+ * @param name - relation name
+ * @param value - relation value
+ * @returns true if relation exists (excluding inherited)
+ */
+ hasOwnedRelation(name: string, value?: string): boolean {
+ return this.hasOwnedAttribute(RELATION, name, value);
+ }
+
+ /**
+ * @param name - label name
+ * @returns label if it exists, null otherwise
+ */
+ getLabel(name: string): BAttribute | null {
+ return this.getAttribute(LABEL, name);
+ }
+
+ /**
+ * @param name - label name
+ * @returns label if it exists, null otherwise
+ */
+ getOwnedLabel(name: string): BAttribute | null {
+ return this.getOwnedAttribute(LABEL, name);
+ }
+
+ /**
+ * @param name - relation name
+ * @returns relation if it exists, null otherwise
+ */
+ getRelation(name: string): BAttribute | null {
+ return this.getAttribute(RELATION, name);
+ }
+
+ /**
+ * @param name - relation name
+ * @returns relation if it exists, null otherwise
+ */
+ getOwnedRelation(name: string): BAttribute | null {
+ return this.getOwnedAttribute(RELATION, name);
+ }
+
+ /**
+ * @param name - label name
+ * @returns label value if label exists, null otherwise
+ */
+ getLabelValue(name: string): string | null {
+ return this.getAttributeValue(LABEL, name);
+ }
+
+ /**
+ * @param name - label name
+ * @returns label value if label exists, null otherwise
+ */
+ getOwnedLabelValue(name: string): string | null {
+ return this.getOwnedAttributeValue(LABEL, name);
+ }
+
+ /**
+ * @param name - relation name
+ * @returns relation value if relation exists, null otherwise
+ */
+ getRelationValue(name: string): string | null {
+ return this.getAttributeValue(RELATION, name);
+ }
+
+ /**
+ * @param name - relation name
+ * @returns relation value if relation exists, null otherwise
+ */
+ getOwnedRelationValue(name: string): string | null {
+ return this.getOwnedAttributeValue(RELATION, name);
+ }
+
+ /**
+ * @param attribute type (label, relation, etc.)
+ * @param name - attribute name
+ * @param value - attribute value
+ * @returns true if note has an attribute with given type and name (excluding inherited)
+ */
+ hasOwnedAttribute(type: string, name: string, value?: string): boolean {
+ return !!this.getOwnedAttribute(type, name, value);
+ }
+
+ /**
+ * @param type - attribute type (label, relation, etc.)
+ * @param name - attribute name
+ * @returns attribute of the given type and name. If there are more such attributes, first is returned.
+ * Returns null if there's no such attribute belonging to this note.
+ */
+ getAttribute(type: string, name: string): BAttribute | null {
+ const attributes = this.getAttributes();
+
+ return attributes.find((attr) => attr.name === name && attr.type === type) || null;
+ }
+
+ /**
+ * @param type - attribute type (label, relation, etc.)
+ * @param name - attribute name
+ * @returns attribute value of given type and name or null if no such attribute exists.
+ */
+ getAttributeValue(type: string, name: string): string | null {
+ const attr = this.getAttribute(type, name);
+
+ return attr ? attr.value : null;
+ }
+
+ /**
+ * @param type - attribute type (label, relation, etc.)
+ * @param name - attribute name
+ * @returns attribute value of given type and name or null if no such attribute exists.
+ */
+ getOwnedAttributeValue(type: string, name: string): string | null {
+ const attr = this.getOwnedAttribute(type, name);
+
+ return attr ? attr.value : null;
+ }
+
+ /**
+ * @param name - label name to filter
+ * @returns all note's labels (attributes with type label), including inherited ones
+ */
+ getLabels(name?: string): BAttribute[] {
+ return this.getAttributes(LABEL, name);
+ }
+
+ /**
+ * @param name - label name to filter
+ * @returns all note's label values, including inherited ones
+ */
+ getLabelValues(name: string): string[] {
+ return this.getLabels(name).map((l) => l.value);
+ }
+
+ /**
+ * @param name - label name to filter
+ * @returns all note's labels (attributes with type label), excluding inherited ones
+ */
+ getOwnedLabels(name: string): BAttribute[] {
+ return this.getOwnedAttributes(LABEL, name);
+ }
+
+ /**
+ * @param name - label name to filter
+ * @returns all note's label values, excluding inherited ones
+ */
+ getOwnedLabelValues(name: string): string[] {
+ return this.getOwnedAttributes(LABEL, name).map((l) => l.value);
+ }
+
+ /**
+ * @param name - relation name to filter
+ * @returns all note's relations (attributes with type relation), including inherited ones
+ */
+ getRelations(name?: string): BAttribute[] {
+ return this.getAttributes(RELATION, name);
+ }
+
+ /**
+ * @param name - relation name to filter
+ * @returns all note's relations (attributes with type relation), excluding inherited ones
+ */
+ getOwnedRelations(name?: string | null): BAttribute[] {
+ return this.getOwnedAttributes(RELATION, name);
+ }
+
+ /**
+ * Beware that the method must not create a copy of the array, but actually returns its internal array
+ * (for performance reasons)
+ *
+ * @param type - (optional) attribute type to filter
+ * @param name - (optional) attribute name to filter
+ * @param value - (optional) attribute value to filter
+ * @returns note's "owned" attributes - excluding inherited ones
+ */
+ getOwnedAttributes(type: string | null = null, name: string | null = null, value: string | null = null) {
+ this.__validateTypeName(type, name);
+
+ if (type && name && value !== undefined && value !== null) {
+ return this.ownedAttributes.filter((attr) => attr.name === name && attr.value === value && attr.type === type);
+ } else if (type && name) {
+ return this.ownedAttributes.filter((attr) => attr.name === name && attr.type === type);
+ } else if (type) {
+ return this.ownedAttributes.filter((attr) => attr.type === type);
+ } else if (name) {
+ return this.ownedAttributes.filter((attr) => attr.name === name);
+ }
+ return this.ownedAttributes;
+ }
+
+ /**
+ * @returns attribute belonging to this specific note (excludes inherited attributes)
+ *
+ * This method can be significantly faster than the getAttribute()
+ */
+ getOwnedAttribute(type: string, name: string, value: string | null = null) {
+ const attrs = this.getOwnedAttributes(type, name, value);
+
+ return attrs.length > 0 ? attrs[0] : null;
+ }
+
+ get isArchived() {
+ return this.hasAttribute("label", "archived");
+ }
+
+ areAllNotePathsArchived() {
+ // there's a slight difference between note being itself archived and all its note paths being archived
+ // - note is archived when it itself has an archived label or inherits it
+ // - note does not have or inherit archived label, but each note path contains a note with (non-inheritable)
+ // archived label
+
+ const bestNotePathRecord = this.getSortedNotePathRecords()[0];
+
+ if (!bestNotePathRecord) {
+ throw new Error(`No note path available for note '${this.noteId}'`);
+ }
+
+ return bestNotePathRecord.isArchived;
+ }
+
+ hasInheritableArchivedLabel() {
+ for (const attr of this.getAttributes()) {
+ if (attr.name === "archived" && attr.type === LABEL && attr.isInheritable) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ // will sort the parents so that the non-archived are first and archived at the end
+ // this is done so that the non-archived paths are always explored as first when looking for note path
+ sortParents() {
+ this.parentBranches.sort((a, b) => {
+ if (a.parentNote?.isArchived) {
+ return 1;
+ } else if (a.parentNote?.isHiddenCompletely()) {
+ return 1;
+ }
+ return 0;
+ });
+
+ this.parents = this.parentBranches.map((branch) => branch.parentNote).filter((note) => !!note) as BNote[];
+ }
+
+ sortChildren() {
+ if (this.children.length === 0) {
+ return;
+ }
+
+ const becca = this.becca;
+
+ this.children.sort((a, b) => {
+ const aBranch = becca.getBranchFromChildAndParent(a.noteId, this.noteId);
+ const bBranch = becca.getBranchFromChildAndParent(b.noteId, this.noteId);
+
+ return (aBranch?.notePosition || 0) - (bBranch?.notePosition || 0) || 0;
+ });
+ }
+
+ /**
+ * This is used for:
+ * - fast searching
+ * - note similarity evaluation
+ *
+ * @returns - returns flattened textual representation of note, prefixes and attributes
+ */
+ getFlatText() {
+ if (!this.__flatTextCache) {
+ this.__flatTextCache = `${this.noteId} ${this.type} ${this.mime} `;
+
+ for (const branch of this.parentBranches) {
+ if (branch.prefix) {
+ this.__flatTextCache += `${branch.prefix} `;
+ }
+ }
+
+ this.__flatTextCache += `${this.title} `;
+
+ for (const attr of this.getAttributes()) {
+ // it's best to use space as separator since spaces are filtered from the search string by the tokenization into words
+ this.__flatTextCache += `${attr.type === "label" ? "#" : "~"}${attr.name}`;
+
+ if (attr.value) {
+ this.__flatTextCache += `=${attr.value}`;
+ }
+
+ this.__flatTextCache += " ";
+ }
+
+ this.__flatTextCache = normalize(this.__flatTextCache);
+ }
+
+ return this.__flatTextCache as string;
+ }
+
+ invalidateThisCache() {
+ this.__flatTextCache = null;
+
+ this.__attributeCache = null;
+ this.__inheritableAttributeCache = null;
+ this.__ancestorCache = null;
+ }
+
+ invalidateSubTree(path: string[] = []) {
+ if (path.includes(this.noteId)) {
+ return;
+ }
+
+ this.invalidateThisCache();
+
+ if (this.children.length || this.targetRelations.length) {
+ path = [...path, this.noteId];
+ }
+
+ for (const childNote of this.children) {
+ childNote.invalidateSubTree(path);
+ }
+
+ for (const targetRelation of this.targetRelations) {
+ if (targetRelation.name === "template" || targetRelation.name === "inherit") {
+ const note = targetRelation.note;
+
+ if (note) {
+ note.invalidateSubTree(path);
+ }
+ }
+ }
+ }
+
+ getRelationDefinitions() {
+ return this.getLabels().filter((l) => l.name.startsWith("relation:"));
+ }
+
+ getLabelDefinitions() {
+ return this.getLabels().filter((l) => l.name.startsWith("relation:"));
+ }
+
+ isInherited() {
+ return !!this.targetRelations.find((rel) => rel.name === "template" || rel.name === "inherit");
+ }
+
+ getSubtreeNotesIncludingTemplated(): BNote[] {
+ const set = new Set<BNote>();
+
+ function inner(note: BNote) {
+ // _hidden is not counted as subtree for the purpose of inheritance
+ if (set.has(note) || note.noteId === "_hidden") {
+ return;
+ }
+
+ set.add(note);
+
+ for (const childNote of note.children) {
+ inner(childNote);
+ }
+
+ for (const targetRelation of note.targetRelations) {
+ if (targetRelation.name === "template" || targetRelation.name === "inherit") {
+ const targetNote = targetRelation.note;
+
+ if (targetNote) {
+ inner(targetNote);
+ }
+ }
+ }
+ }
+
+ inner(this);
+
+ return Array.from(set);
+ }
+
+ getSearchResultNotes(): BNote[] {
+ if (this.type !== "search") {
+ return [];
+ }
+
+ try {
+ const result = searchService.searchFromNote(this);
+ const becca = this.becca;
+ return result.searchResultNoteIds.map((resultNoteId) => becca.notes[resultNoteId]).filter((note) => !!note);
+ } catch (e: any) {
+ getLog().error(`Could not resolve search note ${this.noteId}: ${e.message}`);
+ return [];
+ }
+ }
+
+ getSubtree({ includeArchived = true, includeHidden = false, resolveSearch = false } = {}): {
+ notes: BNote[];
+ relationships: Relationship[];
+ } {
+ const noteSet = new Set<BNote>();
+ const relationships: Relationship[] = []; // list of tuples parentNoteId -> childNoteId
+
+ function resolveSearchNote(searchNote: BNote) {
+ try {
+ for (const resultNote of searchNote.getSearchResultNotes()) {
+ addSubtreeNotesInner(resultNote, searchNote);
+ }
+ } catch (e: any) {
+ getLog().error(`Could not resolve search note ${searchNote?.noteId}: ${e.message}`);
+ }
+ }
+
+ function addSubtreeNotesInner(note: BNote, parentNote: BNote | null = null) {
+ if (note.noteId === "_hidden" && !includeHidden) {
+ return;
+ }
+
+ if (parentNote) {
+ // this needs to happen first before noteSet check to include all clone relationships
+ relationships.push({
+ parentNoteId: parentNote.noteId,
+ childNoteId: note.noteId
+ });
+ }
+
+ if (noteSet.has(note)) {
+ return;
+ }
+
+ if (!includeArchived && note.isArchived) {
+ return;
+ }
+
+ noteSet.add(note);
+
+ if (note.type === "search") {
+ if (resolveSearch) {
+ resolveSearchNote(note);
+ }
+ } else {
+ for (const childNote of note.children) {
+ addSubtreeNotesInner(childNote, note);
+ }
+ }
+ }
+
+ addSubtreeNotesInner(this);
+
+ return {
+ notes: Array.from(noteSet),
+ relationships
+ };
+ }
+
+ /** @returns includes the subtree root note as well */
+ getSubtreeNoteIds({ includeArchived = true, includeHidden = false, resolveSearch = false } = {}) {
+ return this.getSubtree({ includeArchived, includeHidden, resolveSearch }).notes.map((note) => note.noteId);
+ }
+
+ /** @deprecated use getSubtreeNoteIds() instead */
+ getDescendantNoteIds() {
+ return this.getSubtreeNoteIds();
+ }
+
+ get parentCount() {
+ return this.parents.length;
+ }
+
+ get childrenCount() {
+ return this.children.length;
+ }
+
+ get labelCount() {
+ return this.getAttributes().filter((attr) => attr.type === "label").length;
+ }
+
+ get ownedLabelCount() {
+ return this.ownedAttributes.filter((attr) => attr.type === "label").length;
+ }
+
+ get relationCount() {
+ return this.getAttributes().filter((attr) => attr.type === "relation" && !attr.isAutoLink()).length;
+ }
+
+ get relationCountIncludingLinks() {
+ return this.getAttributes().filter((attr) => attr.type === "relation").length;
+ }
+
+ get ownedRelationCount() {
+ return this.ownedAttributes.filter((attr) => attr.type === "relation" && !attr.isAutoLink()).length;
+ }
+
+ get ownedRelationCountIncludingLinks() {
+ return this.ownedAttributes.filter((attr) => attr.type === "relation").length;
+ }
+
+ get targetRelationCount() {
+ return this.targetRelations.filter((attr) => !attr.isAutoLink()).length;
+ }
+
+ get targetRelationCountIncludingLinks() {
+ return this.targetRelations.length;
+ }
+
+ get attributeCount() {
+ return this.getAttributes().length;
+ }
+
+ get ownedAttributeCount() {
+ return this.getOwnedAttributes().length;
+ }
+
+ getAncestors() {
+ if (!this.__ancestorCache) {
+ const noteIds = new Set();
+ this.__ancestorCache = [];
+
+ for (const parent of this.parents) {
+ if (noteIds.has(parent.noteId)) {
+ continue;
+ }
+
+ this.__ancestorCache.push(parent);
+ noteIds.add(parent.noteId);
+
+ for (const ancestorNote of parent.getAncestors()) {
+ if (!noteIds.has(ancestorNote.noteId)) {
+ this.__ancestorCache.push(ancestorNote);
+ noteIds.add(ancestorNote.noteId);
+ }
+ }
+ }
+ }
+
+ return this.__ancestorCache;
+ }
+
+ getAncestorNoteIds(): string[] {
+ return this.getAncestors().map((note) => note.noteId);
+ }
+
+ hasAncestor(ancestorNoteId: string): boolean {
+ for (const ancestorNote of this.getAncestors()) {
+ if (ancestorNote.noteId === ancestorNoteId) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ isInHiddenSubtree() {
+ return this.noteId === "_hidden" || this.hasAncestor("_hidden");
+ }
+
+ getTargetRelations() {
+ return this.targetRelations;
+ }
+
+ /** @returns returns only notes which are templated, does not include their subtrees
+ * in effect returns notes which are influenced by note's non-inheritable attributes */
+ getInheritingNotes(): BNote[] {
+ const arr: BNote[] = [this];
+
+ for (const targetRelation of this.targetRelations) {
+ if (targetRelation.name === "template" || targetRelation.name === "inherit") {
+ const note = targetRelation.note;
+
+ if (note) {
+ arr.push(note);
+ }
+ }
+ }
+
+ return arr;
+ }
+
+ getDistanceToAncestor(ancestorNoteId: string) {
+ if (this.noteId === ancestorNoteId) {
+ return 0;
+ }
+
+ let minDistance = 999999;
+
+ for (const parent of this.parents) {
+ minDistance = Math.min(minDistance, parent.getDistanceToAncestor(ancestorNoteId) + 1);
+ }
+
+ return minDistance;
+ }
+
+ getRevisions(): BRevision[] {
+ return getSql().getRows<RevisionRow>("SELECT * FROM revisions WHERE noteId = ? ORDER BY revisions.utcDateCreated ASC", [this.noteId]).map((row) => new BRevision(row));
+ }
+
+ getAttachments() {
+ const query = /*sql*/`\
+ SELECT attachments.*, LENGTH(blobs.content) AS contentLength
+ FROM attachments
+ JOIN blobs USING (blobId)
+ WHERE ownerId = ? AND isDeleted = 0
+ ORDER BY position`;
+
+ return getSql().getRows<AttachmentRow>(query, [this.noteId]).map((row) => new BAttachment(row));
+ }
+
+ getAttachmentById(attachmentId: string) {
+ const query = /*sql*/`\
+ SELECT attachments.*, LENGTH(blobs.content) AS contentLength
+ FROM attachments
+ JOIN blobs USING (blobId)
+ WHERE ownerId = ? AND attachmentId = ? AND isDeleted = 0`;
+
+ return getSql().getRows<AttachmentRow>(query, [this.noteId, attachmentId]).map((row) => new BAttachment(row))[0];
+ }
+
+ getAttachmentsByRole(role: string): BAttachment[] {
+ return getSql()
+ .getRows<AttachmentRow>(
+ `
+ SELECT attachments.*
+ FROM attachments
+ WHERE ownerId = ?
+ AND role = ?
+ AND isDeleted = 0
+ ORDER BY position`,
+ [this.noteId, role]
+ )
+ .map((row) => new BAttachment(row));
+ }
+
+ getAttachmentByTitle(title: string): BAttachment | undefined {
+ // cannot use SQL to filter by title since it can be encrypted
+ return this.getAttachments().filter((attachment) => attachment.title === title)[0];
+ }
+
+ /**
+ * Gives all possible note paths leading to this note. Paths containing search note are ignored (could form cycles)
+ *
+ * @returns array of notePaths (each represented by array of noteIds constituting the particular note path)
+ */
+ getAllNotePaths(): string[][] {
+ if (this.noteId === "root") {
+ return [["root"]];
+ }
+
+ const parentNotes = this.getParentNotes();
+
+ const notePaths =
+ parentNotes.length === 1
+ ? parentNotes[0].getAllNotePaths() // optimization for the most common case
+ : parentNotes.flatMap((parentNote) => parentNote.getAllNotePaths());
+
+ for (const notePath of notePaths) {
+ notePath.push(this.noteId);
+ }
+
+ return notePaths;
+ }
+
+ getSortedNotePathRecords(hoistedNoteId: string = "root"): NotePathRecord[] {
+ const isHoistedRoot = hoistedNoteId === "root";
+
+ const notePaths = this.getAllNotePaths().map((path) => ({
+ notePath: path,
+ isInHoistedSubTree: isHoistedRoot || path.includes(hoistedNoteId),
+ isArchived: path.some((noteId) => this.becca.notes[noteId].isArchived),
+ isHidden: path.includes("_hidden")
+ }));
+
+ notePaths.sort((a, b) => {
+ if (a.isInHoistedSubTree !== b.isInHoistedSubTree) {
+ return a.isInHoistedSubTree ? -1 : 1;
+ } else if (a.isArchived !== b.isArchived) {
+ return a.isArchived ? 1 : -1;
+ } else if (a.isHidden !== b.isHidden) {
+ return a.isHidden ? 1 : -1;
+ }
+ return a.notePath.length - b.notePath.length;
+ });
+
+ return notePaths;
+ }
+
+ /**
+ * Returns a note path considered to be the "best"
+ *
+ * @return array of noteIds constituting the particular note path
+ */
+ getBestNotePath(hoistedNoteId: string = "root"): string[] {
+ return this.getSortedNotePathRecords(hoistedNoteId)[0]?.notePath;
+ }
+
+ /**
+ * Returns a note path considered to be the "best"
+ *
+ * @return serialized note path (e.g. 'root/a1h315/js725h')
+ */
+ getBestNotePathString(hoistedNoteId: string = "root"): string {
+ const notePath = this.getBestNotePath(hoistedNoteId);
+
+ return notePath?.join("/");
+ }
+
+ /**
+ * @return boolean - true if there's no non-hidden path, note is not cloned to the visible tree
+ */
+ isHiddenCompletely() {
+ if (this.noteId === "root") {
+ return false;
+ }
+
+ for (const parentNote of this.parents) {
+ if (parentNote.noteId === "root") {
+ return false;
+ } else if (parentNote.noteId === "_hidden") {
+ continue;
+ } else if (!parentNote.isHiddenCompletely()) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ /**
+ * @returns true if ancestorNoteId occurs in at least one of the note's paths
+ */
+ isDescendantOfNote(ancestorNoteId: string): boolean {
+ const notePaths = this.getAllNotePaths();
+
+ return notePaths.some((path) => path.includes(ancestorNoteId));
+ }
+
+ /**
+ * Update's given attribute's value or creates it if it doesn't exist
+ *
+ * @param type - attribute type (label, relation, etc.)
+ * @param name - attribute name
+ * @param value - attribute value (optional)
+ */
+ setAttribute(type: AttributeType, name: string, value?: string) {
+ const attributes = this.getOwnedAttributes();
+ const attr = attributes.find((attr) => attr.type === type && attr.name === name);
+
+ value = value?.toString() || "";
+
+ if (attr) {
+ if (attr.value !== value) {
+ attr.value = value;
+ attr.save();
+ }
+ } else {
+ new BAttribute({
+ noteId: this.noteId,
+ type,
+ name,
+ value
+ }).save();
+ }
+ }
+
+ /**
+ * Removes given attribute name-value pair if it exists.
+ *
+ * @param type - attribute type (label, relation, etc.)
+ * @param name - attribute name
+ * @param value - attribute value (optional)
+ */
+ removeAttribute(type: string, name: string, value?: string) {
+ const attributes = this.getOwnedAttributes();
+
+ for (const attribute of attributes) {
+ if (attribute.type === type && attribute.name === name && (value === undefined || value === attribute.value)) {
+ attribute.markAsDeleted();
+ }
+ }
+ }
+
+ /**
+ * Adds a new attribute to this note. The attribute is saved and returned.
+ * See addLabel, addRelation for more specific methods.
+ *
+ * @param type - attribute type (label / relation)
+ * @param name - name of the attribute, not including the leading ~/#
+ * @param value - value of the attribute - text for labels, target note ID for relations; optional.
+ */
+ addAttribute(type: AttributeType, name: string, value: string = "", isInheritable: boolean = false, position: number | null = null): BAttribute {
+ return new BAttribute({
+ noteId: this.noteId,
+ type,
+ name,
+ value,
+ isInheritable,
+ position
+ }).save();
+ }
+
+ /**
+ * Adds a new label to this note. The label attribute is saved and returned.
+ *
+ * @param name - name of the label, not including the leading #
+ * @param value - text value of the label; optional
+ */
+ addLabel(name: string, value: string = "", isInheritable: boolean = false): BAttribute {
+ return this.addAttribute(LABEL, name, value, isInheritable);
+ }
+
+ /**
+ * Adds a new relation to this note. The relation attribute is saved and
+ * returned.
+ *
+ * @param name - name of the relation, not including the leading ~
+ */
+ addRelation(name: string, targetNoteId: string, isInheritable: boolean = false): BAttribute {
+ return this.addAttribute(RELATION, name, targetNoteId, isInheritable);
+ }
+
+ /**
+ * Based on enabled, the attribute is either set or removed.
+ *
+ * @param type - attribute type ('relation', 'label' etc.)
+ * @param enabled - toggle On or Off
+ * @param name - attribute name
+ * @param value - attribute value (optional)
+ */
+ toggleAttribute(type: AttributeType, enabled: boolean, name: string, value?: string) {
+ if (enabled) {
+ this.setAttribute(type, name, value);
+ } else {
+ this.removeAttribute(type, name, value);
+ }
+ }
+
+ /**
+ * Based on enabled, label is either set or removed.
+ *
+ * @param enabled - toggle On or Off
+ * @param name - label name
+ * @param value - label value (optional)
+ */
+ toggleLabel(enabled: boolean, name: string, value?: string) {
+ return this.toggleAttribute(LABEL, enabled, name, value);
+ }
+
+ /**
+ * Based on enabled, relation is either set or removed.
+ *
+ * @param enabled - toggle On or Off
+ * @param name - relation name
+ * @param value - relation value (noteId)
+ */
+ toggleRelation(enabled: boolean, name: string, value?: string) {
+ return this.toggleAttribute(RELATION, enabled, name, value);
+ }
+
+ /**
+ * Update's given label's value or creates it if it doesn't exist
+ *
+ * @param name - label name
+ * @param value label value
+ */
+ setLabel(name: string, value?: string) {
+ return this.setAttribute(LABEL, name, value);
+ }
+
+ /**
+ * Update's given relation's value or creates it if it doesn't exist
+ *
+ * @param name - relation name
+ * @param value - relation value (noteId)
+ */
+ setRelation(name: string, value?: string) {
+ return this.setAttribute(RELATION, name, value);
+ }
+
+ /**
+ * Remove label name-value pair, if it exists.
+ *
+ * @param name - label name
+ * @param value - label value
+ */
+ removeLabel(name: string, value?: string) {
+ return this.removeAttribute(LABEL, name, value);
+ }
+
+ /**
+ * Remove the relation name-value pair, if it exists.
+ *
+ * @param name - relation name
+ * @param value - relation value (noteId)
+ */
+ removeRelation(name: string, value?: string) {
+ return this.removeAttribute(RELATION, name, value);
+ }
+
+ searchNotesInSubtree(searchString: string) {
+ return searchService.searchNotes(searchString) as BNote[];
+ }
+
+ searchNoteInSubtree(searchString: string) {
+ return this.searchNotesInSubtree(searchString)[0];
+ }
+
+ cloneTo(parentNoteId: string): CloneResponse {
+ const branch = this.becca.getNote(parentNoteId)?.getParentBranches()[0];
+ if (!branch?.branchId) {
+ return {
+ success: false,
+ message: "Unable to find the branch ID to clone."
+ };
+ }
+
+ return cloningService.cloneNoteToBranch(this.noteId, branch.branchId);
+ }
+
+ isEligibleForConversionToAttachment(opts: ConvertOpts = { autoConversion: false }) {
+ if (this.type !== "image" || !this.isContentAvailable() || this.hasChildren() || this.getParentBranches().length !== 1) {
+ return false;
+ }
+
+ const targetRelations = this.getTargetRelations().filter((relation) => relation.name === "imageLink");
+
+ if (opts.autoConversion && targetRelations.length === 0) {
+ return false;
+ } else if (targetRelations.length > 1) {
+ return false;
+ }
+
+ const parentNote = this.getParentNotes()[0]; // at this point note can have only one parent
+ const referencingNote = targetRelations[0]?.getNote();
+
+ if (referencingNote && parentNote !== referencingNote) {
+ return false;
+ } else if (parentNote.type !== "text" || !parentNote.isContentAvailable()) {
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * Some notes are eligible for conversion into an attachment of its parent, note must have these properties:
+ * - it has exactly one target relation
+ * - it has a relation from its parent note
+ * - it has no children
+ * - it has no clones
+ * - the parent is of type text
+ * - both notes are either unprotected or user is in protected session
+ *
+ * Currently, works only for image notes.
+ *
+ * In the future, this functionality might get more generic and some of the requirements relaxed.
+ *
+ * @returns null if note is not eligible for conversion
+ */
+ convertToParentAttachment(opts: ConvertOpts = { autoConversion: false }): BAttachment | null {
+ if (!this.isEligibleForConversionToAttachment(opts)) {
+ return null;
+ }
+
+ const content = this.getContent();
+
+ const parentNote = this.getParentNotes()[0];
+ const attachment = parentNote.saveAttachment({
+ role: "image",
+ mime: this.mime,
+ title: this.title,
+ content
+ });
+
+ const parentContent = parentNote.getContent();
+
+ const oldNoteUrl = `api/images/${this.noteId}/`;
+ const newAttachmentUrl = `api/attachments/${attachment.attachmentId}/image/`;
+
+ if (typeof parentContent !== "string") {
+ throw new Error("Unable to convert image note into attachment because parent note does not have a string content.");
+ }
+
+ const fixedContent = replaceAll(parentContent, oldNoteUrl, newAttachmentUrl);
+
+ parentNote.setContent(fixedContent);
+
+ noteService.asyncPostProcessContent(parentNote, fixedContent); // to mark an unused attachment for deletion
+
+ this.deleteNote();
+
+ return attachment;
+ }
+
+ /**
+ * (Soft) delete a note and all its descendants.
+ *
+ * @param deleteId - optional delete identified
+ */
+ deleteNote(deleteId: string | null = null, taskContext: TaskContext<"deleteNotes"> | null = null) {
+ if (this.isDeleted) {
+ return;
+ }
+
+ if (!deleteId) {
+ deleteId = randomString(10);
+ }
+
+ if (!taskContext) {
+ taskContext = new TaskContext("no-progress-reporting", "deleteNotes", null);
+ }
+
+ // needs to be run before branches and attributes are deleted and thus attached relations disappear
+ handlers.runAttachedRelations(this, "runOnNoteDeletion", this);
+ taskContext.noteDeletionHandlerTriggered = true;
+
+ for (const branch of this.getParentBranches()) {
+ branch.deleteBranch(deleteId ?? undefined, taskContext);
+ }
+ }
+
+ decrypt() {
+ if (this.isProtected && !this.isDecrypted && protectedSessionService.isProtectedSessionAvailable()) {
+ try {
+ this.title = protectedSessionService.decryptString(this.title) || "";
+ this.__flatTextCache = null;
+
+ this.isDecrypted = true;
+ } catch (e: any) {
+ getLog().error(`Could not decrypt note ${this.noteId}: ${e.message} ${e.stack}`);
+ }
+ }
+ }
+
+ isLaunchBarConfig() {
+ return this.type === "launcher"
+ || ["_lbRoot", "_lbAvailableLaunchers", "_lbVisibleLaunchers"].includes(this.noteId)
+ || ["_lbMobileRoot", "_lbMobileAvailableLaunchers", "_lbMobileVisibleLaunchers"].includes(this.noteId);
+ }
+
+ isOptions() {
+ return this.noteId.startsWith("_options");
+ }
+
+ override get isDeleted() {
+ // isBeingDeleted is relevant only in the transition period when the deletion process has begun, but not yet
+ // finished (note is still in becca)
+ return !(this.noteId in this.becca.notes) || this.isBeingDeleted;
+ }
+
- saveRevision(): BRevision {
++ saveRevision(opts: { description?: string; source?: RevisionSource } = {}): BRevision {
+ return getSql().transactional(() => {
+ let noteContent = this.getContent();
+
+ const revision = new BRevision(
+ {
+ noteId: this.noteId,
+ // title and text should be decrypted now
+ title: this.title,
++ description: opts.description || "",
++ source: opts.source || "auto",
+ type: this.type,
+ mime: this.mime,
+ isProtected: this.isProtected,
+ utcDateLastEdited: this.utcDateModified,
+ utcDateCreated: dateUtils.utcNowDateTime(),
+ utcDateModified: dateUtils.utcNowDateTime(),
+ dateLastEdited: this.dateModified,
+ dateCreated: dateUtils.localNowDateTime()
+ },
+ true
+ );
+
+ revision.save(); // to generate revisionId, which is then used to save attachments
+
+ for (const noteAttachment of this.getAttachments()) {
+ const revisionAttachment = noteAttachment.copy();
+
+ if (!revision.revisionId) {
+ throw new Error("Revision ID is missing.");
+ }
+
+ revisionAttachment.ownerId = revision.revisionId;
+ revisionAttachment.setContent(noteAttachment.getContent(), { forceSave: true });
+
+ if (this.type === "text" && typeof noteContent === "string") {
+ // content is rewritten to point to the revision attachments
+ noteContent = noteContent.replaceAll(`attachments/${noteAttachment.attachmentId}`, `attachments/${revisionAttachment.attachmentId}`);
+
+ noteContent = noteContent.replaceAll(
+ new RegExp(`href="[^"]*attachmentId=${noteAttachment.attachmentId}[^"]*"`, "gi"),
+ `href="api/attachments/${revisionAttachment.attachmentId}/download"`
+ );
+ }
+ }
+
+ revision.setContent(noteContent);
+
+ this.eraseExcessRevisionSnapshots();
+ return revision;
+ });
+ }
+
+ // Limit the number of Snapshots to revisionSnapshotNumberLimit
+ // Delete older Snapshots that exceed the limit
+ eraseExcessRevisionSnapshots() {
+ // lable has a higher priority
+ let revisionSnapshotNumberLimit = parseInt(this.getLabelValue("versioningLimit") ?? "");
+ if (!Number.isInteger(revisionSnapshotNumberLimit)) {
+ revisionSnapshotNumberLimit = parseInt(optionService.getOption("revisionSnapshotNumberLimit"));
+ }
+ if (revisionSnapshotNumberLimit >= 0) {
+ const revisions = this.getRevisions();
+ if (revisions.length - revisionSnapshotNumberLimit > 0) {
+ const revisionIds = revisions
+ .slice(0, revisions.length - revisionSnapshotNumberLimit)
+ .map((revision) => revision.revisionId)
+ .filter((id): id is string => id !== undefined);
+ eraseService.eraseRevisions(revisionIds);
+ }
+ }
+ }
+
+ /**
+ * @param matchBy - choose by which property we detect if to update an existing attachment.
+ * Supported values are either 'attachmentId' (default) or 'title'
+ */
+ saveAttachment({ attachmentId, role, mime, title, content, position }: Omit<AttachmentRow, "ownerId">, matchBy: "attachmentId" | "title" | undefined = "attachmentId") {
+ if (!["attachmentId", "title"].includes(matchBy)) {
+ throw new Error(`Unsupported value '${matchBy}' for matchBy param, has to be either 'attachmentId' or 'title'.`);
+ }
+
+ let attachment;
+
+ if (matchBy === "title" && title) {
+ attachment = this.getAttachmentByTitle(title);
+ } else if (matchBy === "attachmentId" && attachmentId) {
+ attachment = this.becca.getAttachmentOrThrow(attachmentId);
+ }
+
+ attachment =
+ attachment ||
+ new BAttachment({
+ ownerId: this.noteId,
+ title,
+ role,
+ mime,
+ isProtected: this.isProtected,
+ position
+ });
+
+ content = content || "";
+ attachment.setContent(content, { forceSave: true });
+
+ return attachment;
+ }
+
+ getFileName() {
+ return formatDownloadTitle(this.title, this.type, this.mime);
+ }
+
+ override beforeSaving() {
+ super.beforeSaving();
+
+ this.becca.addNote(this.noteId, this);
+
+ this.dateModified = dateUtils.localNowDateTime();
+ this.utcDateModified = dateUtils.utcNowDateTime();
+ }
+
+ getPojo(): NotePojo {
+ return {
+ noteId: this.noteId,
+ title: this.title,
+ isProtected: this.isProtected,
+ type: this.type,
+ mime: this.mime,
+ blobId: this.blobId,
+ isDeleted: false,
+ dateCreated: this.dateCreated,
+ dateModified: this.dateModified,
+ utcDateCreated: this.utcDateCreated,
+ utcDateModified: this.utcDateModified
+ };
+ }
+
+ override getPojoToSave() {
+ const pojo = this.getPojo();
+
+ if (pojo.isProtected) {
+ if (this.isDecrypted && pojo.title) {
+ pojo.title = protectedSessionService.encrypt(pojo.title) || undefined;
+ } else {
+ // updating protected note outside of protected session means we will keep original ciphertexts
+ delete pojo.title;
+ }
+ }
+
+ return pojo;
+ }
+
+ getIcon() {
+ const iconClassLabels = this.getLabels("iconClass");
+ const icon = getNoteIcon({
+ noteId: this.noteId,
+ type: this.type,
+ mime: this.mime,
+ iconClass: iconClassLabels.length > 0 ? iconClassLabels[0].value : undefined,
+ workspaceIconClass: undefined,
+ isFolder: this.isFolder.bind(this)
+ });
+
+ return `tn-icon ${icon}`;
+ }
+
+ // TODO: Deduplicate with fnote
+ isFolder() {
+ return this.type === "search" || this.getFilteredChildBranches().length > 0;
+ }
+
+ // TODO: Deduplicate with fnote
+ getFilteredChildBranches() {
+ const childBranches = this.getChildBranches();
+
+ if (!childBranches) {
+ console.error(`No children for '${this.noteId}'. This shouldn't happen.`);
+ return [];
+ }
+
+ // we're not checking hideArchivedNotes since that would mean we need to lazy load the child notes
+ // which would seriously slow down everything.
+ // we check this flag only once user chooses to expand the parent. This has the negative consequence that
+ // note may appear as a folder but not contain any children when all of them are archived
+
+ return childBranches;
+ }
+
+ get encodedTitle() {
+ return encodeURIComponent(this.title);
+ }
+
+ getVisibleChildBranches() {
+ return this.getChildBranches().filter((branch) => {
+ const note = branch.getNote();
+ return !note.isLabelTruthy("shareHiddenFromTree") && !note.noteId.startsWith("_");
+ });
+ }
+
+ getVisibleChildNotes() {
+ return this.getVisibleChildBranches().map((branch) => branch.getNote());
+ }
+
+ hasVisibleChildren() {
+ return this.getVisibleChildNotes().length > 0;
+ }
+
+ get shareId() {
+ return this.noteId;
+ }
+
+ /**
+ * Return an attribute by it's attributeId. Requires the attribute cache to be available.
+ * @param attributeId - the id of the attribute owned by this note
+ * @returns - the BAttribute with the given id or undefined if not found.
+ */
+ getAttributeById(attributeId : string): BAttribute | undefined {
+ this.__ensureAttributeCacheIsAvailable();
+
+ if (!this.__attributeCache) {
+ throw new Error("Attribute cache not available.");
+ }
+
+ return this.__attributeCache.find((attr) => attr.attributeId === attributeId);
+ }
+
+ /**
+ * Sets an attribute's value by it's attributeId.
+ * @param attributeId - the id of the attribute owned by this note
+ * @param value - the new value to replace
+ */
+ setAttributeValueById(attributeId : string, value? : string) {
+ const attributes = this.getOwnedAttributes();
+ const attr = attributes.find((attr) => attr.attributeId === attributeId);
+
+ value = value?.toString() || "";
+
+ if (attr) {
+ if (attr.value !== value) {
+ attr.value = value;
+ attr.save();
+ }
+ } else {
+ throw new Error(`Attribute with id ${attributeId} not found.`);
+ }
+ }
+}
+
+export default BNote;
diff --cc packages/trilium-core/src/becca/entities/brevision.ts
index a3a9b4ce08,0000000000..f7f94bf51d
mode 100644,000000..100644
--- a/packages/trilium-core/src/becca/entities/brevision.ts
+++ b/packages/trilium-core/src/becca/entities/brevision.ts
@@@ -1,225 -1,0 +1,231 @@@
+"use strict";
+
+import protectedSessionService from "../../services/protected_session.js";
+import dateUtils from "../../services/utils/date";
+import becca from "../becca.js";
+import AbstractBeccaEntity from "./abstract_becca_entity.js";
+import BAttachment from "./battachment.js";
- import type { AttachmentRow, NoteType, RevisionPojo, RevisionRow } from "@triliumnext/commons";
++import type { AttachmentRow, NoteType, RevisionPojo, RevisionRow, RevisionSource } from "@triliumnext/commons";
+import eraseService from "../../services/erase.js";
+import { getSql } from "../../services/sql/index.js";
+import { isStringNote } from "../../services/utils/index.js";
+
+interface ContentOpts {
+ /** will also save this BRevision entity */
+ forceSave?: boolean;
+}
+
+interface GetByIdOpts {
+ includeContentLength?: boolean;
+}
+
+/**
+ * Revision represents a snapshot of note's title and content at some point in the past.
+ * It's used for seamless note versioning.
+ */
+class BRevision extends AbstractBeccaEntity<BRevision> {
+ static get entityName() {
+ return "revisions";
+ }
+ static get primaryKeyName() {
+ return "revisionId";
+ }
+ static get hashedProperties() {
- return ["revisionId", "noteId", "title", "isProtected", "dateLastEdited", "dateCreated", "utcDateLastEdited", "utcDateCreated", "utcDateModified", "blobId"];
++ return ["revisionId", "noteId", "title", "description", "source", "isProtected", "dateLastEdited", "dateCreated", "utcDateLastEdited", "utcDateCreated", "utcDateModified", "blobId"];
+ }
+
+ revisionId?: string;
+ noteId!: string;
+ type!: NoteType;
+ mime!: string;
+ title!: string;
++ description!: string;
++ source!: RevisionSource;
+ dateLastEdited?: string;
+ utcDateLastEdited?: string;
+ contentLength?: number;
+ content?: string | Uint8Array;
+
+ constructor(row: RevisionRow, titleDecrypted = false) {
+ super();
+
+ this.updateFromRow(row);
+ if (this.isProtected && !titleDecrypted) {
+ const decryptedTitle = protectedSessionService.isProtectedSessionAvailable() ? protectedSessionService.decryptString(this.title) : null;
+ this.title = decryptedTitle || "[protected]";
+ }
+ }
+
+ updateFromRow(row: RevisionRow) {
+ this.revisionId = row.revisionId;
+ this.noteId = row.noteId;
+ this.type = row.type;
+ this.mime = row.mime;
+ this.isProtected = !!row.isProtected;
+ this.title = row.title;
++ this.description = row.description || "";
++ this.source = row.source || "auto";
+ this.blobId = row.blobId;
+ this.dateLastEdited = row.dateLastEdited;
+ this.dateCreated = row.dateCreated;
+ this.utcDateLastEdited = row.utcDateLastEdited;
+ this.utcDateCreated = row.utcDateCreated;
+ this.utcDateModified = row.utcDateModified;
+ this.contentLength = row.contentLength;
+ }
+
+ getNote() {
+ return becca.notes[this.noteId];
+ }
+
+ /** @returns true if the note has string content (not binary) */
+ override hasStringContent(): boolean {
+ return isStringNote(this.type, this.mime);
+ }
+
+ isContentAvailable() {
+ return (
+ !this.revisionId || // new note which was not encrypted yet
+ !this.isProtected ||
+ protectedSessionService.isProtectedSessionAvailable()
+ );
+ }
+
+ /*
+ * Note revision content has quite special handling - it's not a separate entity, but a lazily loaded
+ * part of Revision entity with its own sync. The reason behind this hybrid design is that
+ * content can be quite large, and it's not necessary to load it / fill memory for any note access even
+ * if we don't need a content, especially for bulk operations like search.
+ *
+ * This is the same approach as is used for Note's content.
+ */
+ getContent(): string | Uint8Array {
+ return this._getContent();
+ }
+
+ /**
+ * @throws Error in case of invalid JSON */
+ getJsonContent(): {} | null {
+ const content = this.getContent();
+
+ if (!content || typeof content !== "string" || !content.trim()) {
+ return null;
+ }
+
+ return JSON.parse(content);
+ }
+
+ /** @returns valid object or null if the content cannot be parsed as JSON */
+ getJsonContentSafely(): {} | null {
+ try {
+ return this.getJsonContent();
+ } catch (e) {
+ return null;
+ }
+ }
+
+ setContent(content: string | Uint8Array, opts: ContentOpts = {}) {
+ this._setContent(content, opts);
+ }
+
+ getAttachments(): BAttachment[] {
+ return getSql()
+ .getRows<AttachmentRow>(
+ `
+ SELECT attachments.*
+ FROM attachments
+ WHERE ownerId = ?
+ AND isDeleted = 0`,
+ [this.revisionId]
+ )
+ .map((row) => new BAttachment(row));
+ }
+
+ getAttachmentById(attachmentId: String, opts: GetByIdOpts = {}): BAttachment | null {
+ opts.includeContentLength = !!opts.includeContentLength;
+
+ const query = opts.includeContentLength
+ ? /*sql*/`SELECT attachments.*, LENGTH(blobs.content) AS contentLength
+ FROM attachments
+ JOIN blobs USING (blobId)
+ WHERE ownerId = ? AND attachmentId = ? AND isDeleted = 0`
+ : /*sql*/`SELECT * FROM attachments WHERE ownerId = ? AND attachmentId = ? AND isDeleted = 0`;
+
+ return getSql().getRows<AttachmentRow>(query, [this.revisionId, attachmentId]).map((row) => new BAttachment(row))[0];
+ }
+
+ getAttachmentsByRole(role: string): BAttachment[] {
+ return getSql()
+ .getRows<AttachmentRow>(
+ `
+ SELECT attachments.*
+ FROM attachments
+ WHERE ownerId = ?
+ AND role = ?
+ AND isDeleted = 0
+ ORDER BY position`,
+ [this.revisionId, role]
+ )
+ .map((row) => new BAttachment(row));
+ }
+
+ getAttachmentByTitle(title: string): BAttachment {
+ // cannot use SQL to filter by title since it can be encrypted
+ return this.getAttachments().filter((attachment) => attachment.title === title)[0];
+ }
+
+ /**
+ * Revisions are not soft-deletable, they are immediately hard-deleted (erased).
+ */
+ eraseRevision() {
+ if (this.revisionId) {
+ eraseService.eraseRevisions([this.revisionId]);
+ }
+ }
+
+ override beforeSaving() {
+ super.beforeSaving();
+
+ this.utcDateModified = dateUtils.utcNowDateTime();
+ }
+
+ getPojo() {
+ return {
+ revisionId: this.revisionId,
+ noteId: this.noteId,
+ type: this.type,
+ mime: this.mime,
+ isProtected: this.isProtected,
+ title: this.title,
++ description: this.description,
++ source: this.source,
+ blobId: this.blobId,
+ dateLastEdited: this.dateLastEdited,
+ dateCreated: this.dateCreated,
+ utcDateLastEdited: this.utcDateLastEdited,
+ utcDateCreated: this.utcDateCreated,
+ utcDateModified: this.utcDateModified,
+ content: this.content, // used when retrieving full note revision to frontend
+ contentLength: this.contentLength
+ } satisfies RevisionPojo;
+ }
+
+ override getPojoToSave() {
+ const pojo = this.getPojo();
+ delete pojo.content; // not getting persisted
+ delete pojo.contentLength; // not getting persisted
+
+ if (pojo.isProtected) {
+ if (protectedSessionService.isProtectedSessionAvailable()) {
+ pojo.title = protectedSessionService.encrypt(this.title) ?? "";
+ } else {
+ // updating protected note outside of protected session means we will keep original ciphertexts
+ pojo.title = "";
+ }
+ }
+
+ return pojo;
+ }
+}
+
+export default BRevision;
diff --cc packages/trilium-core/src/migrations/migrations.spec.ts
index 0000000000,98a6924ce3..98a6924ce3
mode 000000,100644..100644
--- a/packages/trilium-core/src/migrations/migrations.spec.ts
+++ b/packages/trilium-core/src/migrations/migrations.spec.ts
diff --cc packages/trilium-core/src/routes/api/revisions.ts
index 22b62ffcba,12e1c990ac..ad28ac231c
--- a/packages/trilium-core/src/routes/api/revisions.ts
+++ b/packages/trilium-core/src/routes/api/revisions.ts
@@@ -107,8 -111,20 +107,20 @@@ function eraseRevision(req: Request<{ r
eraseService.eraseRevisions([req.params.revisionId]);
}
+ function updateRevisionDescription(req: Request<{ revisionId: string }>) {
+ const revision = becca.getRevisionOrThrow(req.params.revisionId);
+ const { description } = req.body;
+
+ if (typeof description !== "string") {
+ return [400, "Description must be a string."];
+ }
+
+ revision.description = description;
+ revision.save();
+ }
+
function eraseAllExcessRevisions() {
- const allNoteIds = sql.getRows("SELECT noteId FROM notes WHERE SUBSTRING(noteId, 1, 1) != '_'") as { noteId: string }[];
+ const allNoteIds = getSql().getRows("SELECT noteId FROM notes WHERE SUBSTRING(noteId, 1, 1) != '_'") as { noteId: string }[];
allNoteIds.forEach((row) => {
becca.getNote(row.noteId)?.eraseExcessRevisionSnapshots();
});
@@@ -120,8 -136,8 +132,8 @@@ function restoreRevision(req: Request<
if (revision) {
const note = revision.getNote();
- sql.transactional(() => {
+ getSql().transactional(() => {
- note.saveRevision();
+ note.saveRevision({ source: "restore" });
for (const oldNoteAttachment of note.getAttachments()) {
oldNoteAttachment.markAsDeleted();
diff --cc packages/trilium-core/src/routes/index.ts
index 107add4acd,0000000000..02bcc3fb92
mode 100644,000000..100644
--- a/packages/trilium-core/src/routes/index.ts
+++ b/packages/trilium-core/src/routes/index.ts
@@@ -1,279 -1,0 +1,280 @@@
+import optionsApiRoute from "./api/options";
+import treeApiRoute from "./api/tree";
+import keysApiRoute from "./api/keys";
+import notesApiRoute from "./api/notes";
+import attachmentsApiRoute from "./api/attachments";
+import noteMapRoute from "./api/note_map";
+import recentNotesRoute from "./api/recent_notes";
+import otherRoute from "./api/others";
+import branchesApiRoute from "./api/branches";
+import appInfoRoute from "./api/app_info";
+import statsRoute from "./api/stats";
+import AbstractBeccaEntity from "../becca/entities/abstract_becca_entity";
+import cloningApiRoute from "./api/cloning";
+import sqlRoute from "./api/sql";
+import attributesRoute from "./api/attributes";
+import revisionsApiRoute from "./api/revisions";
+import relationMapApiRoute from "./api/relation-map";
+import recentChangesApiRoute from "./api/recent_changes";
+import bulkActionRoute from "./api/bulk_action";
+import searchRoute from "./api/search";
+import specialNotesRoute from "./api/special_notes";
+import syncApiRoute from "./api/sync";
+import autocompleteApiRoute from "./api/autocomplete";
+import similarNotesRoute from "./api/similar_notes";
+import imageRoute from "./api/image";
+import setupApiRoute from "./api/setup";
+import filesRoute from "./api/files";
+import importRoute from "./api/import";
+import exportRoute from "./api/export";
+import scriptRoute from "./api/script";
+import backendLogRoute from "./api/backend_log";
+import backupRoute from "./api/backup";
+import passwordApiRoute from "./api/password";
+import loginApiRoute from "./api/login";
+
+// TODO: Deduplicate with routes.ts
+const GET = "get",
+ PST = "post",
+ PUT = "put",
+ PATCH = "patch",
+ DEL = "delete";
+
+interface SharedApiRoutesContext {
+ route: any;
+ asyncRoute: any;
+ apiRoute: any;
+ asyncApiRoute: any;
+ checkApiAuth: any;
+ apiResultHandler: any;
+ checkApiAuthOrElectron: any;
+ checkAppNotInitialized: any;
+ loginRateLimiter: any;
+ checkCredentials: any;
+ uploadMiddlewareWithErrorHandling: any;
+ csrfMiddleware: any;
+}
+
+export function buildSharedApiRoutes({ route, asyncRoute, apiRoute, asyncApiRoute, checkApiAuth, apiResultHandler, checkApiAuthOrElectron, checkAppNotInitialized, checkCredentials, loginRateLimiter, uploadMiddlewareWithErrorHandling, csrfMiddleware }: SharedApiRoutesContext) {
+ apiRoute(GET, '/api/tree', treeApiRoute.getTree);
+ apiRoute(PST, '/api/tree/load', treeApiRoute.load);
+
+ apiRoute(GET, "/api/options", optionsApiRoute.getOptions);
+ // FIXME: possibly change to sending value in the body to avoid host of HTTP server issues with slashes
+ apiRoute(PUT, "/api/options/:name/:value", optionsApiRoute.updateOption);
+ apiRoute(PUT, "/api/options", optionsApiRoute.updateOptions);
+ apiRoute(GET, "/api/options/user-themes", optionsApiRoute.getUserThemes);
+
+ apiRoute(PST, "/api/notes/:noteId/convert-to-attachment", notesApiRoute.convertNoteToAttachment);
+ apiRoute(GET, "/api/notes/:noteId", notesApiRoute.getNote);
+ apiRoute(GET, "/api/notes/:noteId/blob", notesApiRoute.getNoteBlob);
+ apiRoute(GET, "/api/notes/:noteId/metadata", notesApiRoute.getNoteMetadata);
+ apiRoute(PUT, "/api/notes/:noteId/data", notesApiRoute.updateNoteData);
+ apiRoute(DEL, "/api/notes/:noteId", notesApiRoute.deleteNote);
+ apiRoute(PUT, "/api/notes/:noteId/undelete", notesApiRoute.undeleteNote);
+ apiRoute(PST, "/api/notes/:noteId/revision", notesApiRoute.forceSaveRevision);
+ apiRoute(PST, "/api/notes/:parentNoteId/children", notesApiRoute.createNote);
+ apiRoute(PUT, "/api/notes/:noteId/sort-children", notesApiRoute.sortChildNotes);
+ apiRoute(PUT, "/api/notes/:noteId/protect/:isProtected", notesApiRoute.protectNote);
+ apiRoute(PUT, "/api/notes/:noteId/type", notesApiRoute.setNoteTypeMime);
+ apiRoute(PUT, "/api/notes/:noteId/title", notesApiRoute.changeTitle);
+ apiRoute(PST, "/api/notes/:noteId/duplicate/:parentNoteId", notesApiRoute.duplicateSubtree);
+ apiRoute(PST, "/api/notes/erase-deleted-notes-now", notesApiRoute.eraseDeletedNotesNow);
+ apiRoute(PST, "/api/notes/erase-unused-attachments-now", notesApiRoute.eraseUnusedAttachmentsNow);
+ apiRoute(PST, "/api/delete-notes-preview", notesApiRoute.getDeleteNotesPreview);
+
+ apiRoute(GET, "/api/notes/:noteId/attachments", attachmentsApiRoute.getAttachments);
+ apiRoute(PST, "/api/notes/:noteId/attachments", attachmentsApiRoute.saveAttachment);
+ apiRoute(GET, "/api/attachments/:attachmentId", attachmentsApiRoute.getAttachment);
+ apiRoute(GET, "/api/attachments/:attachmentId/all", attachmentsApiRoute.getAllAttachments);
+ apiRoute(PST, "/api/attachments/:attachmentId/convert-to-note", attachmentsApiRoute.convertAttachmentToNote);
+ apiRoute(DEL, "/api/attachments/:attachmentId", attachmentsApiRoute.deleteAttachment);
+ apiRoute(PUT, "/api/attachments/:attachmentId/rename", attachmentsApiRoute.renameAttachment);
+ apiRoute(GET, "/api/attachments/:attachmentId/blob", attachmentsApiRoute.getAttachmentBlob);
+
+ apiRoute(GET, "/api/notes/:noteId/attributes", attributesRoute.getEffectiveNoteAttributes);
+ apiRoute(PST, "/api/notes/:noteId/attributes", attributesRoute.addNoteAttribute);
+ apiRoute(PUT, "/api/notes/:noteId/attributes", attributesRoute.updateNoteAttributes);
+ apiRoute(PUT, "/api/notes/:noteId/attribute", attributesRoute.updateNoteAttribute);
+ apiRoute(PUT, "/api/notes/:noteId/set-attribute", attributesRoute.setNoteAttribute);
+ apiRoute(PUT, "/api/notes/:noteId/relations/:name/to/:targetNoteId", attributesRoute.createRelation);
+ apiRoute(DEL, "/api/notes/:noteId/relations/:name/to/:targetNoteId", attributesRoute.deleteRelation);
+ apiRoute(DEL, "/api/notes/:noteId/attributes/:attributeId", attributesRoute.deleteNoteAttribute);
+ apiRoute(GET, "/api/attribute-names/", attributesRoute.getAttributeNames);
+ apiRoute(GET, "/api/attribute-values/:attributeName", attributesRoute.getValuesForAttribute);
+
+ apiRoute(GET, "/api/notes/:noteId/revisions", revisionsApiRoute.getRevisions);
+ apiRoute(DEL, "/api/notes/:noteId/revisions", revisionsApiRoute.eraseAllRevisions);
+ apiRoute(PST, "/api/revisions/erase-all-excess-revisions", revisionsApiRoute.eraseAllExcessRevisions);
+ apiRoute(GET, "/api/revisions/:revisionId", revisionsApiRoute.getRevision);
+ apiRoute(GET, "/api/revisions/:revisionId/blob", revisionsApiRoute.getRevisionBlob);
+ apiRoute(DEL, "/api/revisions/:revisionId", revisionsApiRoute.eraseRevision);
++ apiRoute(PATCH, "/api/revisions/:revisionId", revisionsApiRoute.updateRevisionDescription);
+ apiRoute(PST, "/api/revisions/:revisionId/restore", revisionsApiRoute.restoreRevision);
+ apiRoute(GET, "/api/edited-notes/:date", revisionsApiRoute.getEditedNotesOnDate);
+
+ apiRoute(PUT, "/api/branches/:branchId/move-to/:parentBranchId", branchesApiRoute.moveBranchToParent);
+ apiRoute(PUT, "/api/branches/:branchId/move-before/:beforeBranchId", branchesApiRoute.moveBranchBeforeNote);
+ apiRoute(PUT, "/api/branches/:branchId/move-after/:afterBranchId", branchesApiRoute.moveBranchAfterNote);
+ apiRoute(PUT, "/api/branches/:branchId/expanded/:expanded", branchesApiRoute.setExpanded);
+ apiRoute(PUT, "/api/branches/:branchId/expanded-subtree/:expanded", branchesApiRoute.setExpandedForSubtree);
+ apiRoute(DEL, "/api/branches/:branchId", branchesApiRoute.deleteBranch);
+ apiRoute(PUT, "/api/branches/:branchId/set-prefix", branchesApiRoute.setPrefix);
+ apiRoute(PUT, "/api/branches/set-prefix-batch", branchesApiRoute.setPrefixBatch);
+
+ // :filename is not used by trilium, but instead used for "save as" to assign a human-readable filename
+ route(GET, "/api/revisions/:revisionId/image/:filename", [checkApiAuthOrElectron], imageRoute.returnImageFromRevision);
+ route(GET, "/api/attachments/:attachmentId/image/:filename", [checkApiAuthOrElectron], imageRoute.returnAttachedImage);
+ route(GET, "/api/images/:noteId/:filename", [checkApiAuthOrElectron], imageRoute.returnImageFromNote);
+ route(PUT, "/api/images/:noteId", [checkApiAuthOrElectron, uploadMiddlewareWithErrorHandling, csrfMiddleware], imageRoute.updateImage, apiResultHandler);
+ route(PST, "/api/notes/:noteId/attachments/upload", [checkApiAuthOrElectron, uploadMiddlewareWithErrorHandling, csrfMiddleware], attachmentsApiRoute.uploadAttachment, apiResultHandler);
+
+ // group of the services below are meant to be executed from the outside
+ route(GET, "/api/setup/status", [], setupApiRoute.getStatus, apiResultHandler);
+ asyncRoute(PST, "/api/setup/new-document", [checkAppNotInitialized], setupApiRoute.setupNewDocument, apiResultHandler);
+ asyncRoute(PST, "/api/setup/sync-from-server", [checkAppNotInitialized], setupApiRoute.setupSyncFromServer, apiResultHandler);
+ route(GET, "/api/setup/sync-seed", [loginRateLimiter, checkCredentials], setupApiRoute.getSyncSeed, apiResultHandler);
+ asyncRoute(PST, "/api/setup/sync-seed", [checkAppNotInitialized], setupApiRoute.saveSyncSeed, apiResultHandler);
+
+ asyncApiRoute(PST, "/api/sync/test", syncApiRoute.testSync);
+ asyncApiRoute(PST, "/api/sync/now", syncApiRoute.syncNow);
+ apiRoute(PST, "/api/sync/fill-entity-changes", syncApiRoute.fillEntityChanges);
+ apiRoute(PST, "/api/sync/force-full-sync", syncApiRoute.forceFullSync);
+ route(GET, "/api/sync/check", [checkApiAuth], syncApiRoute.checkSync, apiResultHandler);
+ route(GET, "/api/sync/changed", [checkApiAuth], syncApiRoute.getChanged, apiResultHandler);
+ route(PUT, "/api/sync/update", [checkApiAuth], syncApiRoute.update, apiResultHandler);
+ route(PST, "/api/sync/finished", [checkApiAuth], syncApiRoute.syncFinished, apiResultHandler);
+ route(PST, "/api/sync/check-entity-changes", [checkApiAuth], syncApiRoute.checkEntityChanges, apiResultHandler);
+ route(PST, "/api/sync/queue-sector/:entityName/:sector", [checkApiAuth], syncApiRoute.queueSector, apiResultHandler);
+ route(GET, "/api/sync/stats", [], syncApiRoute.getStats, apiResultHandler);
+
+ //#region Import/export
+ asyncRoute(PST, "/api/notes/:parentNoteId/notes-import", [checkApiAuthOrElectron, uploadMiddlewareWithErrorHandling, csrfMiddleware], importRoute.importNotesToBranch, apiResultHandler);
+ route(PST, "/api/notes/:parentNoteId/attachments-import", [checkApiAuthOrElectron, uploadMiddlewareWithErrorHandling, csrfMiddleware], importRoute.importAttachmentsToNote, apiResultHandler);
+ asyncRoute(GET, "/api/branches/:branchId/export/:type/:format/:version/:taskId", [checkApiAuthOrElectron], exportRoute.exportBranch);
+ //#endregion
+
+ apiRoute(GET, "/api/quick-search/:searchString", searchRoute.quickSearch);
+ apiRoute(GET, "/api/search-note/:noteId", searchRoute.searchFromNote);
+ apiRoute(PST, "/api/search-and-execute-note/:noteId", searchRoute.searchAndExecute);
+ apiRoute(PST, "/api/search-related", searchRoute.getRelatedNotes);
+ apiRoute(GET, "/api/search/:searchString", searchRoute.search);
+ apiRoute(GET, "/api/search-templates", searchRoute.searchTemplates);
+
+ apiRoute(GET, "/api/autocomplete", autocompleteApiRoute.getAutocomplete);
+ apiRoute(GET, "/api/autocomplete/notesCount", autocompleteApiRoute.getNotesCount);
+
+ apiRoute(PUT, "/api/notes/:noteId/clone-to-branch/:parentBranchId", cloningApiRoute.cloneNoteToBranch);
+ apiRoute(PUT, "/api/notes/:noteId/toggle-in-parent/:parentNoteId/:present", cloningApiRoute.toggleNoteInParent);
+ apiRoute(PUT, "/api/notes/:noteId/clone-to-note/:parentNoteId", cloningApiRoute.cloneNoteToParentNote);
+ apiRoute(PUT, "/api/notes/:noteId/clone-after/:afterBranchId", cloningApiRoute.cloneNoteAfter);
+
+ asyncApiRoute(GET, "/api/special-notes/inbox/:date", specialNotesRoute.getInboxNote);
+ asyncApiRoute(GET, "/api/special-notes/days/:date", specialNotesRoute.getDayNote);
+ asyncApiRoute(GET, "/api/special-notes/week-first-day/:date", specialNotesRoute.getWeekFirstDayNote);
+ asyncApiRoute(GET, "/api/special-notes/weeks/:week", specialNotesRoute.getWeekNote);
+ asyncApiRoute(GET, "/api/special-notes/months/:month", specialNotesRoute.getMonthNote);
+ asyncApiRoute(GET, "/api/special-notes/quarters/:quarter", specialNotesRoute.getQuarterNote);
+ apiRoute(GET, "/api/special-notes/years/:year", specialNotesRoute.getYearNote);
+ apiRoute(GET, "/api/special-notes/notes-for-month/:month", specialNotesRoute.getDayNotesForMonth);
+ apiRoute(PST, "/api/special-notes/sql-console", specialNotesRoute.createSqlConsole);
+ asyncApiRoute(PST, "/api/special-notes/save-sql-console", specialNotesRoute.saveSqlConsole);
+ apiRoute(PST, "/api/special-notes/search-note", specialNotesRoute.createSearchNote);
+ apiRoute(PST, "/api/special-notes/save-search-note", specialNotesRoute.saveSearchNote);
+ apiRoute(PST, "/api/special-notes/launchers/:noteId/reset", specialNotesRoute.resetLauncher);
+ apiRoute(PST, "/api/special-notes/launchers/:parentNoteId/:launcherType", specialNotesRoute.createLauncher);
+ apiRoute(PUT, "/api/special-notes/api-script-launcher", specialNotesRoute.createOrUpdateScriptLauncherFromApi);
+
+ apiRoute(PST, "/api/note-map/:noteId/tree", noteMapRoute.getTreeMap);
+ apiRoute(PST, "/api/note-map/:noteId/link", noteMapRoute.getLinkMap);
+ apiRoute(GET, "/api/note-map/:noteId/backlinks", noteMapRoute.getBacklinks);
+ apiRoute(GET, "/api/note-map/:noteId/backlink-count", noteMapRoute.getBacklinkCount);
+
+ apiRoute(PST, "/api/recent-notes", recentNotesRoute.addRecentNote);
+
+ apiRoute(GET, "/api/keyboard-actions", keysApiRoute.getKeyboardActions);
+ apiRoute(GET, "/api/keyboard-shortcuts-for-notes", keysApiRoute.getShortcutsForNotes);
+
+ apiRoute(GET, "/api/stats/note-size/:noteId", statsRoute.getNoteSize);
+ apiRoute(GET, "/api/stats/subtree-size/:noteId", statsRoute.getSubtreeSize);
+
+ apiRoute(GET, "/api/sql/schema", sqlRoute.getSchema);
+ apiRoute(PST, "/api/sql/execute/:noteId", sqlRoute.execute);
+
+ apiRoute(PST, "/api/bulk-action/execute", bulkActionRoute.execute);
+ apiRoute(PST, "/api/bulk-action/affected-notes", bulkActionRoute.getAffectedNoteCount);
+
+ apiRoute(GET, "/api/app-info", appInfoRoute.getAppInfo);
+ asyncApiRoute(GET, "/api/backend-log", backendLogRoute.getBackendLog);
+
+ // Backup routes
+ asyncApiRoute(GET, "/api/database/backups", backupRoute.getExistingBackups);
+ asyncApiRoute(PST, "/api/database/backup-database", backupRoute.backupDatabase);
+ asyncRoute(GET, "/api/database/backup/download", [checkApiAuthOrElectron], backupRoute.downloadBackup);
+
+ apiRoute(GET, "/api/other/icon-usage", otherRoute.getIconUsage);
+ apiRoute(PST, "/api/other/render-markdown", otherRoute.renderMarkdown);
+ apiRoute(PST, "/api/other/to-markdown", otherRoute.toMarkdown);
+
+ asyncApiRoute(GET, "/api/similar-notes/:noteId", similarNotesRoute.getSimilarNotes);
+ apiRoute(PST, "/api/relation-map", relationMapApiRoute.getRelationMap);
+ apiRoute(GET, "/api/recent-changes/:ancestorNoteId", recentChangesApiRoute.getRecentChanges);
+
+ //#region Files
+ route(GET, "/api/notes/:noteId/open", [checkApiAuthOrElectron], filesRoute.openFile);
+ route(GET, "/api/notes/:noteId/download", [checkApiAuthOrElectron], filesRoute.downloadFile);
+ // this "hacky" path is used for easier referencing of CSS resources
+ route(GET, "/api/notes/download/:noteId", [checkApiAuthOrElectron], filesRoute.downloadFile);
+ route(GET, "/api/attachments/:attachmentId/open", [checkApiAuthOrElectron], filesRoute.openAttachment);
+ route(GET, "/api/attachments/:attachmentId/download", [checkApiAuthOrElectron], filesRoute.downloadAttachment);
+ // this "hacky" path is used for easier referencing of CSS resources
+ route(GET, "/api/attachments/download/:attachmentId", [checkApiAuthOrElectron], filesRoute.downloadAttachment);
+ //#endregion
+
+ //#region Export
+ asyncRoute(PST, "/api/script/exec", [checkApiAuth, csrfMiddleware], scriptRoute.exec, apiResultHandler);
+
+ apiRoute(PST, "/api/script/run/:noteId", scriptRoute.run);
+ apiRoute(GET, "/api/script/startup", scriptRoute.getStartupBundles);
+ apiRoute(GET, "/api/script/widgets", scriptRoute.getWidgetBundles);
+ apiRoute(PST, "/api/script/bundle/:noteId", scriptRoute.getBundle);
+ apiRoute(GET, "/api/script/relation/:noteId/:relationName", scriptRoute.getRelationBundles);
+ //#endregion
+
+ //#region Password and protected session
+ asyncApiRoute(PST, "/api/password/change", passwordApiRoute.changePassword);
+ apiRoute(PST, "/api/password/reset", passwordApiRoute.resetPassword);
+
+ asyncApiRoute(PST, "/api/login/protected", loginApiRoute.loginToProtectedSession);
+ apiRoute(PST, "/api/login/protected/touch", loginApiRoute.touchProtectedSession);
+ apiRoute(PST, "/api/logout/protected", loginApiRoute.logoutFromProtectedSession);
+ //#endregion
+}
+
+/** Handling common patterns. If entity is not caught, serialization to JSON will fail */
+export function convertEntitiesToPojo(result: unknown) {
+ if (result instanceof AbstractBeccaEntity) {
+ result = result.getPojo();
+ } else if (Array.isArray(result)) {
+ for (const idx in result) {
+ if (result[idx] instanceof AbstractBeccaEntity) {
+ result[idx] = result[idx].getPojo();
+ }
+ }
+ } else if (result && typeof result === "object") {
+ if ("note" in result && result.note instanceof AbstractBeccaEntity) {
+ result.note = result.note.getPojo();
+ }
+
+ if ("branch" in result && result.branch instanceof AbstractBeccaEntity) {
+ result.branch = result.branch.getPojo();
+ }
+ }
+
+ if (result && typeof result === "object" && "executionResult" in result) {
+ // from runOnBackend()
+ result.executionResult = convertEntitiesToPojo(result.executionResult);
+ }
+
+ return result;
+}
diff --cc packages/trilium-core/src/services/app_info.ts
index ba78f55b31,0000000000..a860dbe81f
mode 100644,000000..100644
--- a/packages/trilium-core/src/services/app_info.ts
+++ b/packages/trilium-core/src/services/app_info.ts
@@@ -1,19 -1,0 +1,19 @@@
+import build from "./build.js";
+import packageJson from "../../package.json" with { type: "json" };
+import { AppInfo } from "@triliumnext/commons";
++import { MAX_MIGRATION_VERSION } from "../migrations/migrations.js";
+
- const APP_DB_VERSION = 236;
- const SYNC_VERSION = 38;
++const SYNC_VERSION = 39;
+const CLIPPER_PROTOCOL_VERSION = "1.0";
+
+const appInfo: AppInfo = {
+ appVersion: packageJson.version,
- dbVersion: APP_DB_VERSION,
++ dbVersion: MAX_MIGRATION_VERSION,
+ syncVersion: SYNC_VERSION,
+ buildDate: build.buildDate,
+ buildRevision: build.buildRevision,
+ clipperProtocolVersion: CLIPPER_PROTOCOL_VERSION,
+ utcDateTime: new Date().toISOString()
+}
+
+export default appInfo;
diff --cc packages/trilium-core/src/services/attributes.ts
index 4a197b8a4e,0000000000..4cd2d20ffb
mode 100644,000000..100644
--- a/packages/trilium-core/src/services/attributes.ts
+++ b/packages/trilium-core/src/services/attributes.ts
@@@ -1,113 -1,0 +1,113 @@@
+import { type AttributeRow, BUILTIN_ATTRIBUTES } from "@triliumnext/commons";
+
+import searchService from "./search/services/search.js";
+import becca from "../becca/becca.js";
+import BAttribute from "../becca/entities/battribute.js";
+import type BNote from "../becca/entities/bnote.js";
+import { getSql } from "./sql/index.js";
+import attribute_formatter from "./attribute_formatter.js";
+
+const ATTRIBUTE_TYPES = new Set(["label", "relation"]);
+
+function getNotesWithLabel(name: string, value?: string): BNote[] {
+ const query = attribute_formatter.formatAttrForSearch({ type: "label", name, value }, value !== undefined);
+ return searchService.searchNotes(query, {
+ includeArchivedNotes: true,
+ ignoreHoistedNote: true
+ });
+}
+
+// TODO: should be in search service
+function getNoteWithLabel(name: string, value?: string): BNote | null {
+ // optimized version (~20 times faster) without using normal search, useful for e.g., finding date notes
+ const attrs = becca.findAttributes("label", name);
+
+ if (value === undefined) {
+ return attrs[0]?.getNote();
+ }
+
+ value = value?.toLowerCase();
+
+ for (const attr of attrs) {
+ if (attr.value.toLowerCase() === value) {
+ return attr.getNote();
+ }
+ }
+
+ return null;
+}
+
+function createLabel(noteId: string, name: string, value: string = "") {
+ return createAttribute({
+ noteId,
+ type: "label",
+ name,
+ value
+ });
+}
+
+function createRelation(noteId: string, name: string, targetNoteId: string) {
+ return createAttribute({
+ noteId,
+ type: "relation",
+ name,
+ value: targetNoteId
+ });
+}
+
+function createAttribute(attribute: AttributeRow) {
+ return new BAttribute(attribute).save();
+}
+
+function getAttributeNames(type: string, nameLike: string) {
+ nameLike = nameLike.toLowerCase();
+
+ let names = getSql().getColumn<string>(
+ /*sql*/`SELECT DISTINCT name
+ FROM attributes
+ WHERE isDeleted = 0
+ AND type = ?
+ AND name LIKE ?`,
+ [type, `%${nameLike}%`]
+ );
+
+ for (const attr of BUILTIN_ATTRIBUTES) {
+ if (attr.type === type && attr.name.toLowerCase().includes(nameLike) && !names.includes(attr.name)) {
+ names.push(attr.name);
+ }
+ }
+
- names = names.filter((name) => !["internalLink", "imageLink", "includeNoteLink", "relationMapLink"].includes(name));
++ names = names.filter((name) => !["internalLink", "imageLink", "includeNoteLink", "relationMapLink", "internalBookmark"].includes(name));
+
+ names.sort((a, b) => {
+ const aPrefix = a.toLowerCase().startsWith(nameLike);
+ const bPrefix = b.toLowerCase().startsWith(nameLike);
+
+ if (aPrefix !== bPrefix) {
+ return aPrefix ? -1 : 1;
+ }
+
+ return a < b ? -1 : 1;
+ });
+
+ return names;
+}
+
+function isAttributeType(type: string): boolean {
+ return ATTRIBUTE_TYPES.has(type);
+}
+
+function isAttributeDangerous(type: string, name: string): boolean {
+ return BUILTIN_ATTRIBUTES.some((attr) => attr.type === type && attr.name.toLowerCase() === name.trim().toLowerCase() && attr.isDangerous);
+}
+
+export default {
+ getNotesWithLabel,
+ getNoteWithLabel,
+ createLabel,
+ createRelation,
+ createAttribute,
+ getAttributeNames,
+ isAttributeType,
+ isAttributeDangerous
+};
diff --cc packages/trilium-core/src/services/export/single.ts
index 301112825c,9764f22abc..b8421e2ac1
--- a/packages/trilium-core/src/services/export/single.ts
+++ b/packages/trilium-core/src/services/export/single.ts
@@@ -36,7 -34,22 +36,22 @@@ function exportSingleNote(taskContext:
taskContext.taskSucceeded(null);
}
+ /**
+ * Extension fallback for MIME types the `mime-types` package doesn't recognize —
+ * mostly Trilium's `text/x-` custom MIMEs.
+ */
+ export function mapCodeMimeToExtension(mime: string): string | null {
+ switch (mime) {
+ case "text/x-markdown":
+ case "text/markdown":
+ case "text/x-gfm":
+ return "md";
+ default:
+ return null;
+ }
+ }
+
-export function mapByNoteType(note: BNote, content: string | Buffer<ArrayBufferLike>, format: ExportFormat) {
+export function mapByNoteType(note: BNote, content: string | Uint8Array, format: ExportFormat) {
let payload, extension, mime;
if (typeof content !== "string") {
diff --cc packages/trilium-core/src/services/export/zip/abstract_provider.ts
index 42a388281b,6adcf136ca..ce20d1886a
--- a/packages/trilium-core/src/services/export/zip/abstract_provider.ts
+++ b/packages/trilium-core/src/services/export/zip/abstract_provider.ts
@@@ -3,8 -4,8 +3,9 @@@ import mimeTypes from "mime-types"
import type BBranch from "../../../becca/entities/bbranch.js";
import type BNote from "../../../becca/entities/bnote.js";
-import type { default as NoteMeta, NoteMetaFile } from "../../meta/note_meta.js";
+import { ExportFormat, NoteMeta, NoteMetaFile } from "../../../meta.js";
+import type { ZipArchive } from "../../zip_provider.js";
+ import { mapCodeMimeToExtension } from "../single.js";
type RewriteLinksFn = (content: string, noteMeta: NoteMeta) => string;
diff --cc packages/trilium-core/src/services/import/enex.spec.ts
index 0000000000,a95baafec9..a95baafec9
mode 000000,100644..100644
--- a/packages/trilium-core/src/services/import/enex.spec.ts
+++ b/packages/trilium-core/src/services/import/enex.spec.ts
diff --cc packages/trilium-core/src/services/import/enex.ts
index 1672ff24ff,2918883964..ca4f3215da
--- a/packages/trilium-core/src/services/import/enex.ts
+++ b/packages/trilium-core/src/services/import/enex.ts
@@@ -356,11 -350,11 +346,11 @@@ async function importEnex(taskContext:
content += imageLink;
}
} catch (e: any) {
- log.error(`error when saving image from ENEX file: ${e.message}`);
+ getLog().error(`error when saving image from ENEX file: ${e.message}`);
- createFileNote();
+ createFileAttachment();
}
} else {
- createFileNote();
+ createFileAttachment();
}
}
diff --cc packages/trilium-core/src/services/import/markdown.ts
index 4b20bf271d,85c63c852d..a90fb67c53
--- a/packages/trilium-core/src/services/import/markdown.ts
+++ b/packages/trilium-core/src/services/import/markdown.ts
@@@ -1,231 -1,11 +1,11 @@@
- import { getMimeTypeFromMarkdownName, MIME_TYPE_AUTO, normalizeMimeTypeForCKEditor, transclusionExtension, wikiLinkExtension } from "@triliumnext/commons";
- import { parse, Renderer, type Tokens, use } from "marked";
+ import { renderToHtml as renderToHtmlShared } from "@triliumnext/commons";
- import { ADMONITION_TYPE_MAPPINGS } from "../export/markdown.js";
- import importUtils from "./utils.js";
- import { escapeHtml } from "../utils/index.js";
-import htmlSanitizer from "../html_sanitizer.js";
+import { sanitizeHtml } from "../sanitizer.js";
- const escape = escapeHtml;
-
- /**
- * Keep renderer code up to date with https://github.com/markedjs/marked/blob/master/src/Renderer.ts.
- */
- class CustomMarkdownRenderer extends Renderer {
-
- override heading(data: Tokens.Heading): string {
- // Treat h1 as raw text.
- if (data.depth === 1) {
- return `<h1>${data.text}</h1>`;
- }
-
- return super.heading(data).trimEnd();
- }
-
- override paragraph(data: Tokens.Paragraph): string {
- return super.paragraph(data).trimEnd();
- }
-
- override code({ text, lang }: Tokens.Code): string {
- if (!text) {
- return "";
- }
-
- // Escape the HTML.
- text = escape(text);
-
- // Unescape &quot
- text = text.replace(/&quot;/g, '"');
-
- const ckEditorLanguage = getNormalizedMimeFromMarkdownLanguage(lang);
- return `<pre><code class="language-${ckEditorLanguage}">${text}</code></pre>`;
- }
-
- override list(token: Tokens.List): string {
- let result = super.list(token)
- .replace("\n", "") // we replace the first one only.
- .trimEnd();
-
- // Handle todo-list in the CKEditor format.
- if (token.items.some(item => item.task)) {
- result = result.replace(/^<ul>/, "<ul class=\"todo-list\">");
- }
-
- return result;
- }
-
- override checkbox({ checked }: Tokens.Checkbox): string {
- return `<input type="checkbox"${
- checked ? 'checked="checked" ' : ''
- }disabled="disabled">`;
- }
-
- override listitem(item: Tokens.ListItem): string {
- // Handle todo-list in the CKEditor format.
- if (item.task) {
- let itemBody = '';
- const checkbox = this.checkbox({ checked: !!item.checked, raw: "- [ ]", type: "checkbox" });
- if (item.loose) {
- if (item.tokens[0]?.type === 'paragraph') {
- item.tokens[0].text = checkbox + item.tokens[0].text;
- if (item.tokens[0].tokens && item.tokens[0].tokens.length > 0 && item.tokens[0].tokens[0].type === 'text') {
- item.tokens[0].tokens[0].text = checkbox + escape(item.tokens[0].tokens[0].text);
- item.tokens[0].tokens[0].escaped = true;
- }
- } else {
- item.tokens.unshift({
- type: 'text',
- raw: checkbox,
- text: checkbox,
- escaped: true,
- });
- }
- } else {
- itemBody += checkbox;
- }
-
- itemBody += `<span class="todo-list__label__description">${this.parser.parse(item.tokens.filter(t => t.type !== "checkbox"))}</span>`;
- return `<li><label class="todo-list__label">${itemBody}</label></li>`;
- }
-
- return super.listitem(item).trimEnd();
- }
-
- override image(token: Tokens.Image): string {
- return super.image(token)
- .replace(` alt=""`, "");
- }
-
- override blockquote({ tokens }: Tokens.Blockquote): string {
- const body = renderer.parser.parse(tokens);
-
- const admonitionMatch = /^<p>\[\!([A-Z]+)\]/.exec(body);
- if (Array.isArray(admonitionMatch) && admonitionMatch.length === 2) {
- const type = admonitionMatch[1].toLowerCase();
-
- if (ADMONITION_TYPE_MAPPINGS[type]) {
- const bodyWithoutHeader = body
- .replace(/^<p>\[\!([A-Z]+)\]\s*/, "<p>")
- .replace(/^<p><\/p>/, ""); // Having a heading will generate an empty paragraph that we need to remove.
-
- return `<aside class="admonition ${type}">${bodyWithoutHeader.trim()}</aside>`;
- }
- }
-
- return `<blockquote>${body}</blockquote>`;
- }
-
- codespan({ text }: Tokens.Codespan): string {
- return `<code spellcheck="false">${escape(text)}</code>`;
- }
-
- }
-
- function renderToHtml(content: string, title: string) {
- // Double-escape slashes in math expression because they are otherwise consumed by the parser somewhere.
- content = content.replaceAll("\\$", "\\\\$");
-
- // Extract formulas and replace them with placeholders to prevent interference from Markdown rendering
- const { processedText, placeholderMap: formulaMap } = extractFormulas(content);
-
- use({
- // Order is important, especially for wikilinks.
- extensions: [
- transclusionExtension,
- wikiLinkExtension
- ]
- });
-
- let html = parse(processedText, {
- async: false,
- renderer
- }) as string;
-
- // After rendering, replace placeholders back with the formula HTML
- html = restoreFromMap(html, formulaMap);
-
- // h1 handling needs to come before sanitization
- html = importUtils.handleH1(html, title);
- html = sanitizeHtml(html);
-
- // Add a trailing semicolon to CSS styles.
- html = html.replaceAll(/(<(img|figure|col).*?style=".*?)"/g, "$1;\"");
-
- // Remove slash for self-closing tags to match CKEditor's approach.
- html = html.replace(/<(\w+)([^>]*)\s+\/>/g, "<$1$2>");
-
- // Normalize non-breaking spaces to entity.
- html = html.replaceAll("\u00a0", "&nbsp;");
-
- return html;
- }
-
- function getNormalizedMimeFromMarkdownLanguage(language: string | undefined) {
- if (language) {
- const mimeDefinition = getMimeTypeFromMarkdownName(language);
- if (mimeDefinition) {
- return normalizeMimeTypeForCKEditor(mimeDefinition.mime);
- }
- }
-
- return MIME_TYPE_AUTO;
+ function renderToHtml(content: string, title: string): string {
- return renderToHtmlShared(content, title, { sanitize: htmlSanitizer.sanitize });
++ return renderToHtmlShared(content, title, { sanitize: sanitizeHtml });
}
- function extractCodeBlocks(text: string): { processedText: string, placeholderMap: Map<string, string> } {
- const codeMap = new Map<string, string>();
- let id = 0;
- const timestamp = Date.now();
-
- // Multi-line code block and Inline code
- text = text.replace(/```[\s\S]*?```/g, (m) => {
- const key = `<!--CODE_BLOCK_${timestamp}_${id++}-->`;
- codeMap.set(key, m);
- return key;
- }).replace(/`[^`\n]+`/g, (m) => {
- const key = `<!--INLINE_CODE_${timestamp}_${id++}-->`;
- codeMap.set(key, m);
- return key;
- });
-
- return { processedText: text, placeholderMap: codeMap };
- }
-
- function extractFormulas(text: string): { processedText: string, placeholderMap: Map<string, string> } {
- // Protect the $ signs inside code blocks from being recognized as formulas.
- const { processedText: noCodeText, placeholderMap: codeMap } = extractCodeBlocks(text);
-
- const formulaMap = new Map<string, string>();
- let id = 0;
- const timestamp = Date.now();
-
- // Display math and Inline math
- let processedText = noCodeText.replace(/(?<!\\)\$\$((?:(?!\n{2,})[\s\S])+?)\$\$/g, (_, formula) => {
- const key = `<!--FORMULA_BLOCK_${timestamp}_${id++}-->`;
- const rendered = `<span class="math-tex">\\[${formula}\\]</span>`;
- formulaMap.set(key, rendered);
- return key;
- }).replace(/(?<!\\)\$(.+?)\$/g, (_, formula) => {
- const key = `<!--FORMULA_INLINE_${timestamp}_${id++}-->`;
- const rendered = `<span class="math-tex">\\(${formula}\\)</span>`;
- formulaMap.set(key, rendered);
- return key;
- });
-
- processedText = restoreFromMap(processedText, codeMap);
-
- return { processedText, placeholderMap: formulaMap };
- }
-
- function restoreFromMap(text: string, map: Map<string, string>): string {
- if (map.size === 0) return text;
- const pattern = [...map.keys()]
- .map(k => k.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
- .join('|');
- return text.replace(new RegExp(pattern, 'g'), match => map.get(match) ?? match);
- }
-
- const renderer = new CustomMarkdownRenderer({ async: false });
-
export default {
renderToHtml
};
diff --cc packages/trilium-core/src/services/import/samples/File with attachments.enex
index 0000000000,d65423f7d7..c65c91936f
mode 000000,100644..100644
--- a/packages/trilium-core/src/services/import/samples/File with attachments.enex
+++ b/packages/trilium-core/src/services/import/samples/File with attachments.enex
@@@ -1,0 -1,19 +1,19 @@@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE en-export SYSTEM "http://xml.evernote.com/pub/evernote-export2.dtd">
-<en-export export-date="20260417T081355Z" application="Evernote/Windows" version="6.x">
-<note><title>TEST1</title><content><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">
-
-<en-note><div>TXT</div><div><en-media hash="698d51a19d8a121ce581499d7b701668" type="text/plain"/><en-media hash="bcbe3365e6ac95ea2c0343a2395834dd" type="application/octet-stream"/><br/></div></en-note>]]></content><created>20260417T081156Z</created><updated>20260417T081307Z</updated><note-attributes><source>desktop.win</source><source-application>evernote.win32</source-application></note-attributes><resource><data encoding="base64">
-MTEx
-</data><mime>text/plain</mime><resource-attributes><source-url>file://D:\Users\leon\Desktop\attachments1.txt</source-url><file-name>attachments1.txt</file-name><attachment>true</attachment></resource-attributes></resource><resource><data encoding="base64">
-MjIy
-</data><mime>application/octet-stream</mime><resource-attributes><source-url>file://D:\Users\leon\Desktop\attachments2</source-url><file-name>attachments2</file-name><attachment>true</attachment></resource-attributes></resource></note><note><title>TEST2</title><content><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">
-
-<en-note><div>NO&nbsp;attachments</div></en-note>]]></content><created>20260417T081317Z</created><updated>20260417T081345Z</updated><note-attributes><source>desktop.win</source><source-application>evernote.win32</source-application></note-attributes></note><note><title>TEST3</title><content><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">
-
++<?xml version="1.0" encoding="UTF-8"?>
++<!DOCTYPE en-export SYSTEM "http://xml.evernote.com/pub/evernote-export2.dtd">
++<en-export export-date="20260417T081355Z" application="Evernote/Windows" version="6.x">
++<note><title>TEST1</title><content><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
++<!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">
++
++<en-note><div>TXT</div><div><en-media hash="698d51a19d8a121ce581499d7b701668" type="text/plain"/><en-media hash="bcbe3365e6ac95ea2c0343a2395834dd" type="application/octet-stream"/><br/></div></en-note>]]></content><created>20260417T081156Z</created><updated>20260417T081307Z</updated><note-attributes><source>desktop.win</source><source-application>evernote.win32</source-application></note-attributes><resource><data encoding="base64">
++MTEx
++</data><mime>text/plain</mime><resource-attributes><source-url>file://D:\Users\leon\Desktop\attachments1.txt</source-url><file-name>attachments1.txt</file-name><attachment>true</attachment></resource-attributes></resource><resource><data encoding="base64">
++MjIy
++</data><mime>application/octet-stream</mime><resource-attributes><source-url>file://D:\Users\leon\Desktop\attachments2</source-url><file-name>attachments2</file-name><attachment>true</attachment></resource-attributes></resource></note><note><title>TEST2</title><content><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
++<!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">
++
++<en-note><div>NO&nbsp;attachments</div></en-note>]]></content><created>20260417T081317Z</created><updated>20260417T081345Z</updated><note-attributes><source>desktop.win</source><source-application>evernote.win32</source-application></note-attributes></note><note><title>TEST3</title><content><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
++<!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">
++
+ <en-note>
+ 111
-</en-note>]]></content><created>20260417T081337Z</created><updated>20260417T081340Z</updated><note-attributes><source>desktop.win</source><source-application>evernote.win32</source-application></note-attributes></note></en-export>
++</en-note>]]></content><created>20260417T081337Z</created><updated>20260417T081340Z</updated><note-attributes><source>desktop.win</source><source-application>evernote.win32</source-application></note-attributes></note></en-export>
diff --cc packages/trilium-core/src/services/keyboard_actions.ts
index 268c0487da,0000000000..d9ccc678e9
mode 100644,000000..100644
--- a/packages/trilium-core/src/services/keyboard_actions.ts
+++ b/packages/trilium-core/src/services/keyboard_actions.ts
@@@ -1,883 -1,0 +1,891 @@@
+"use strict";
+
+import optionService from "./options.js";
+import { getLog } from "./log.js";
+import { isElectron, isMac } from "./utils/index.js";
+import type { ActionKeyboardShortcut, KeyboardShortcut } from "@triliumnext/commons";
+import { t } from "i18next";
+
+function getDefaultKeyboardActions() {
+ if (!t("keyboard_actions.note-navigation")) {
+ throw new Error("Keyboard actions loaded before translations.");
+ }
+
+ const DEFAULT_KEYBOARD_ACTIONS: KeyboardShortcut[] = [
+ {
+ separator: t("keyboard_actions.note-navigation")
+ },
+ {
+ actionName: "backInNoteHistory",
+ friendlyName: t("keyboard_action_names.back-in-note-history"),
+ iconClass: "bx bxs-chevron-left",
+ // Mac has a different history navigation shortcuts - https://github.com/zadam/trilium/issues/376
+ defaultShortcuts: isMac() ? ["CommandOrControl+["] : ["Alt+Left"],
+ description: t("keyboard_actions.back-in-note-history"),
+ scope: "window"
+ },
+ {
+ actionName: "forwardInNoteHistory",
+ friendlyName: t("keyboard_action_names.forward-in-note-history"),
+ iconClass: "bx bxs-chevron-right",
+ // Mac has a different history navigation shortcuts - https://github.com/zadam/trilium/issues/376
+ defaultShortcuts: isMac() ? ["CommandOrControl+]"] : ["Alt+Right"],
+ description: t("keyboard_actions.forward-in-note-history"),
+ scope: "window"
+ },
+ {
+ actionName: "jumpToNote",
+ friendlyName: t("keyboard_action_names.jump-to-note"),
+ defaultShortcuts: ["CommandOrControl+J"],
+ description: t("keyboard_actions.open-jump-to-note-dialog"),
+ scope: "window",
+ ignoreFromCommandPalette: true
+ },
+ {
+ actionName: "openTodayNote",
+ friendlyName: t("hidden-subtree.open-today-journal-note-title"),
+ iconClass: "bx bx-calendar",
+ defaultShortcuts: [],
+ description: t("hidden-subtree.open-today-journal-note-title"),
+ scope: "window"
+ },
+ {
+ actionName: "commandPalette",
+ friendlyName: t("keyboard_action_names.command-palette"),
+ defaultShortcuts: ["CommandOrControl+Shift+J"],
+ description: t("keyboard_actions.open-command-palette"),
+ scope: "window",
+ ignoreFromCommandPalette: true
+ },
+ {
+ actionName: "scrollToActiveNote",
+ friendlyName: t("keyboard_action_names.scroll-to-active-note"),
+ defaultShortcuts: ["CommandOrControl+."],
+ iconClass: "bx bx-current-location",
+ description: t("keyboard_actions.scroll-to-active-note"),
+ scope: "window"
+ },
+ {
+ actionName: "quickSearch",
+ friendlyName: t("keyboard_action_names.quick-search"),
+ iconClass: "bx bx-search",
+ defaultShortcuts: ["CommandOrControl+S"],
+ description: t("keyboard_actions.quick-search"),
+ scope: "window"
+ },
+ {
+ actionName: "searchInSubtree",
+ friendlyName: t("keyboard_action_names.search-in-subtree"),
+ defaultShortcuts: ["CommandOrControl+Shift+S"],
+ iconClass: "bx bx-search-alt",
+ description: t("keyboard_actions.search-in-subtree"),
+ scope: "note-tree"
+ },
+ {
+ actionName: "expandSubtree",
+ friendlyName: t("keyboard_action_names.expand-subtree"),
+ defaultShortcuts: [],
+ iconClass: "bx bx-layer-plus",
+ description: t("keyboard_actions.expand-subtree"),
+ scope: "note-tree"
+ },
+ {
+ actionName: "collapseTree",
+ friendlyName: t("keyboard_action_names.collapse-tree"),
+ defaultShortcuts: ["Alt+C"],
+ iconClass: "bx bx-layer-minus",
+ description: t("keyboard_actions.collapse-tree"),
+ scope: "window"
+ },
+ {
+ actionName: "collapseSubtree",
+ friendlyName: t("keyboard_action_names.collapse-subtree"),
+ iconClass: "bx bxs-layer-minus",
+ defaultShortcuts: ["Alt+-"],
+ description: t("keyboard_actions.collapse-subtree"),
+ scope: "note-tree"
+ },
+ {
+ actionName: "sortChildNotes",
+ friendlyName: t("keyboard_action_names.sort-child-notes"),
+ iconClass: "bx bx-sort-down",
+ defaultShortcuts: ["Alt+S"],
+ description: t("keyboard_actions.sort-child-notes"),
+ scope: "note-tree"
+ },
+
+ {
+ separator: t("keyboard_actions.creating-and-moving-notes")
+ },
+ {
+ actionName: "createNoteAfter",
+ friendlyName: t("keyboard_action_names.create-note-after"),
+ iconClass: "bx bx-plus",
+ defaultShortcuts: ["CommandOrControl+O"],
+ description: t("keyboard_actions.create-note-after"),
+ scope: "window"
+ },
+ {
+ actionName: "createNoteInto",
+ friendlyName: t("keyboard_action_names.create-note-into"),
+ iconClass: "bx bx-plus",
+ defaultShortcuts: ["CommandOrControl+P"],
+ description: t("keyboard_actions.create-note-into"),
+ scope: "window"
+ },
+ {
+ actionName: "createNoteIntoInbox",
+ friendlyName: t("keyboard_action_names.create-note-into-inbox"),
+ iconClass: "bx bxs-inbox",
+ defaultShortcuts: ["global:CommandOrControl+Alt+P"],
+ description: t("keyboard_actions.create-note-into-inbox"),
+ scope: "window"
+ },
+ {
+ actionName: "deleteNotes",
+ friendlyName: t("keyboard_action_names.delete-notes"),
+ iconClass: "bx bx-trash",
+ defaultShortcuts: ["Delete"],
+ description: t("keyboard_actions.delete-note"),
+ scope: "note-tree"
+ },
+ {
+ actionName: "moveNoteUp",
+ friendlyName: t("keyboard_action_names.move-note-up"),
+ iconClass: "bx bx-up-arrow-alt",
+ defaultShortcuts: isMac() ? ["Alt+Up"] : ["CommandOrControl+Up"],
+ description: t("keyboard_actions.move-note-up"),
+ scope: "note-tree"
+ },
+ {
+ actionName: "moveNoteDown",
+ friendlyName: t("keyboard_action_names.move-note-down"),
+ iconClass: "bx bx-down-arrow-alt",
+ defaultShortcuts: isMac() ? ["Alt+Down"] : ["CommandOrControl+Down"],
+ description: t("keyboard_actions.move-note-down"),
+ scope: "note-tree"
+ },
+ {
+ actionName: "moveNoteUpInHierarchy",
+ friendlyName: t("keyboard_action_names.move-note-up-in-hierarchy"),
+ iconClass: "bx bx-arrow-from-bottom",
+ defaultShortcuts: isMac() ? ["Alt+Left"] : ["CommandOrControl+Left"],
+ description: t("keyboard_actions.move-note-up-in-hierarchy"),
+ scope: "note-tree"
+ },
+ {
+ actionName: "moveNoteDownInHierarchy",
+ friendlyName: t("keyboard_action_names.move-note-down-in-hierarchy"),
+ iconClass: "bx bx-arrow-from-top",
+ defaultShortcuts: isMac() ? ["Alt+Right"] : ["CommandOrControl+Right"],
+ description: t("keyboard_actions.move-note-down-in-hierarchy"),
+ scope: "note-tree"
+ },
+ {
+ actionName: "editNoteTitle",
+ friendlyName: t("keyboard_action_names.edit-note-title"),
+ iconClass: "bx bx-rename",
+ defaultShortcuts: ["Enter"],
+ description: t("keyboard_actions.edit-note-title"),
+ scope: "note-tree"
+ },
+ {
+ actionName: "editBranchPrefix",
+ friendlyName: t("keyboard_action_names.edit-branch-prefix"),
+ iconClass: "bx bx-rename",
+ defaultShortcuts: ["F2"],
+ description: t("keyboard_actions.edit-branch-prefix"),
+ scope: "note-tree"
+ },
+ {
+ actionName: "cloneNotesTo",
+ friendlyName: t("keyboard_action_names.clone-notes-to"),
+ iconClass: "bx bx-duplicate",
+ defaultShortcuts: ["CommandOrControl+Shift+C"],
+ description: t("keyboard_actions.clone-notes-to"),
+ scope: "window"
+ },
+ {
+ actionName: "moveNotesTo",
+ friendlyName: t("keyboard_action_names.move-notes-to"),
+ iconClass: "bx bx-transfer",
+ defaultShortcuts: ["CommandOrControl+Shift+X"],
+ description: t("keyboard_actions.move-notes-to"),
+ scope: "window"
+ },
+
+ {
+ separator: t("keyboard_actions.note-clipboard")
+ },
+
+ {
+ actionName: "copyNotesToClipboard",
+ friendlyName: t("keyboard_action_names.copy-notes-to-clipboard"),
+ iconClass: "bx bx-copy",
+ defaultShortcuts: ["CommandOrControl+C"],
+ description: t("keyboard_actions.copy-notes-to-clipboard"),
+ scope: "note-tree"
+ },
+ {
+ actionName: "pasteNotesFromClipboard",
+ friendlyName: t("keyboard_action_names.paste-notes-from-clipboard"),
+ iconClass: "bx bx-paste",
+ defaultShortcuts: ["CommandOrControl+V"],
+ description: t("keyboard_actions.paste-notes-from-clipboard"),
+ scope: "note-tree"
+ },
+ {
+ actionName: "cutNotesToClipboard",
+ friendlyName: t("keyboard_action_names.cut-notes-to-clipboard"),
+ iconClass: "bx bx-cut",
+ defaultShortcuts: ["CommandOrControl+X"],
+ description: t("keyboard_actions.cut-notes-to-clipboard"),
+ scope: "note-tree"
+ },
+ {
+ actionName: "selectAllNotesInParent",
+ friendlyName: t("keyboard_action_names.select-all-notes-in-parent"),
+ iconClass: "bx bx-select-multiple",
+ defaultShortcuts: ["CommandOrControl+A"],
+ description: t("keyboard_actions.select-all-notes-in-parent"),
+ scope: "note-tree"
+ },
+ {
+ actionName: "addNoteAboveToSelection",
+ friendlyName: t("keyboard_action_names.add-note-above-to-selection"),
+ defaultShortcuts: ["Shift+Up"],
+ description: t("keyboard_actions.add-note-above-to-the-selection"),
+ scope: "note-tree",
+ ignoreFromCommandPalette: true
+ },
+ {
+ actionName: "addNoteBelowToSelection",
+ friendlyName: t("keyboard_action_names.add-note-below-to-selection"),
+ defaultShortcuts: ["Shift+Down"],
+ description: t("keyboard_actions.add-note-below-to-selection"),
+ scope: "note-tree",
+ ignoreFromCommandPalette: true
+ },
+ {
+ actionName: "duplicateSubtree",
+ friendlyName: t("keyboard_action_names.duplicate-subtree"),
+ iconClass: "bx bx-outline",
+ defaultShortcuts: [],
+ description: t("keyboard_actions.duplicate-subtree"),
+ scope: "note-tree"
+ },
+
+ {
+ separator: t("keyboard_actions.tabs-and-windows")
+ },
+ {
+ actionName: "openNewTab",
+ friendlyName: t("keyboard_action_names.open-new-tab"),
+ iconClass: "bx bx-plus",
+ defaultShortcuts: isElectron() ? ["CommandOrControl+T"] : [],
+ description: t("keyboard_actions.open-new-tab"),
+ scope: "window"
+ },
+ {
+ actionName: "closeActiveTab",
+ friendlyName: t("keyboard_action_names.close-active-tab"),
+ iconClass: "bx bx-minus",
+ defaultShortcuts: isElectron() ? ["CommandOrControl+W"] : [],
+ description: t("keyboard_actions.close-active-tab"),
+ scope: "window"
+ },
+ {
+ actionName: "reopenLastTab",
+ friendlyName: t("keyboard_action_names.reopen-last-tab"),
+ iconClass: "bx bx-undo",
+ defaultShortcuts: isElectron() ? ["CommandOrControl+Shift+T"] : [],
+ isElectronOnly: true,
+ description: t("keyboard_actions.reopen-last-tab"),
+ scope: "window"
+ },
+ {
+ actionName: "activateNextTab",
+ friendlyName: t("keyboard_action_names.activate-next-tab"),
+ iconClass: "bx bx-skip-next",
+ defaultShortcuts: isElectron() ? ["CommandOrControl+Tab", "CommandOrControl+PageDown"] : [],
+ description: t("keyboard_actions.activate-next-tab"),
+ scope: "window"
+ },
+ {
+ actionName: "activatePreviousTab",
+ friendlyName: t("keyboard_action_names.activate-previous-tab"),
+ iconClass: "bx bx-skip-previous",
+ defaultShortcuts: isElectron() ? ["CommandOrControl+Shift+Tab", "CommandOrControl+PageUp"] : [],
+ description: t("keyboard_actions.activate-previous-tab"),
+ scope: "window"
+ },
+ {
+ actionName: "openNewWindow",
+ friendlyName: t("keyboard_action_names.open-new-window"),
+ iconClass: "bx bx-window-open",
+ defaultShortcuts: [],
+ description: t("keyboard_actions.open-new-window"),
+ scope: "window"
+ },
+ {
+ actionName: "toggleTray",
+ friendlyName: t("keyboard_action_names.toggle-system-tray-icon"),
+ iconClass: "bx bx-show",
+ defaultShortcuts: [],
+ isElectronOnly: true,
+ description: t("keyboard_actions.toggle-tray"),
+ scope: "window"
+ },
+ {
+ actionName: "toggleZenMode",
+ friendlyName: t("keyboard_action_names.toggle-zen-mode"),
+ iconClass: "bx bxs-yin-yang",
+ defaultShortcuts: ["F9"],
+ description: t("keyboard_actions.toggle-zen-mode"),
+ scope: "window"
+ },
+ {
+ actionName: "firstTab",
+ friendlyName: t("keyboard_action_names.switch-to-first-tab"),
+ iconClass: "bx bx-rectangle",
+ defaultShortcuts: ["CommandOrControl+1"],
+ description: t("keyboard_actions.first-tab"),
+ scope: "window"
+ },
+ {
+ actionName: "secondTab",
+ friendlyName: t("keyboard_action_names.switch-to-second-tab"),
+ iconClass: "bx bx-rectangle",
+ defaultShortcuts: ["CommandOrControl+2"],
+ description: t("keyboard_actions.second-tab"),
+ scope: "window"
+ },
+ {
+ actionName: "thirdTab",
+ friendlyName: t("keyboard_action_names.switch-to-third-tab"),
+ iconClass: "bx bx-rectangle",
+ defaultShortcuts: ["CommandOrControl+3"],
+ description: t("keyboard_actions.third-tab"),
+ scope: "window"
+ },
+ {
+ actionName: "fourthTab",
+ friendlyName: t("keyboard_action_names.switch-to-fourth-tab"),
+ iconClass: "bx bx-rectangle",
+ defaultShortcuts: ["CommandOrControl+4"],
+ description: t("keyboard_actions.fourth-tab"),
+ scope: "window"
+ },
+ {
+ actionName: "fifthTab",
+ friendlyName: t("keyboard_action_names.switch-to-fifth-tab"),
+ iconClass: "bx bx-rectangle",
+ defaultShortcuts: ["CommandOrControl+5"],
+ description: t("keyboard_actions.fifth-tab"),
+ scope: "window"
+ },
+ {
+ actionName: "sixthTab",
+ friendlyName: t("keyboard_action_names.switch-to-sixth-tab"),
+ iconClass: "bx bx-rectangle",
+ defaultShortcuts: ["CommandOrControl+6"],
+ description: t("keyboard_actions.sixth-tab"),
+ scope: "window"
+ },
+ {
+ actionName: "seventhTab",
+ friendlyName: t("keyboard_action_names.switch-to-seventh-tab"),
+ iconClass: "bx bx-rectangle",
+ defaultShortcuts: ["CommandOrControl+7"],
+ description: t("keyboard_actions.seventh-tab"),
+ scope: "window"
+ },
+ {
+ actionName: "eigthTab",
+ friendlyName: t("keyboard_action_names.switch-to-eighth-tab"),
+ iconClass: "bx bx-rectangle",
+ defaultShortcuts: ["CommandOrControl+8"],
+ description: t("keyboard_actions.eight-tab"),
+ scope: "window"
+ },
+ {
+ actionName: "ninthTab",
+ friendlyName: t("keyboard_action_names.switch-to-ninth-tab"),
+ iconClass: "bx bx-rectangle",
+ defaultShortcuts: ["CommandOrControl+9"],
+ description: t("keyboard_actions.ninth-tab"),
+ scope: "window"
+ },
+ {
+ actionName: "lastTab",
+ friendlyName: t("keyboard_action_names.switch-to-last-tab"),
+ iconClass: "bx bx-rectangle",
+ defaultShortcuts: ["CommandOrControl+0"],
+ description: t("keyboard_actions.last-tab"),
+ scope: "window"
+ },
+
+ {
+ separator: t("keyboard_actions.dialogs")
+ },
+ {
+ friendlyName: t("keyboard_action_names.show-note-source"),
+ actionName: "showNoteSource",
+ iconClass: "bx bx-code",
+ defaultShortcuts: [],
+ description: t("keyboard_actions.show-note-source"),
+ scope: "window"
+ },
+ {
+ friendlyName: t("keyboard_action_names.show-options"),
+ actionName: "showOptions",
+ iconClass: "bx bx-cog",
+ defaultShortcuts: [],
+ description: t("keyboard_actions.show-options"),
+ scope: "window"
+ },
+ {
+ friendlyName: t("keyboard_action_names.show-revisions"),
+ actionName: "showRevisions",
+ iconClass: "bx bx-history",
+ defaultShortcuts: [],
+ description: t("keyboard_actions.show-revisions"),
+ scope: "window"
+ },
+ {
+ friendlyName: t("keyboard_action_names.show-recent-changes"),
+ actionName: "showRecentChanges",
+ iconClass: "bx bx-history",
+ defaultShortcuts: [],
+ description: t("keyboard_actions.show-recent-changes"),
+ scope: "window"
+ },
+ {
+ friendlyName: t("keyboard_action_names.show-sql-console"),
+ actionName: "showSQLConsole",
+ iconClass: "bx bx-data",
+ defaultShortcuts: ["Alt+O"],
+ description: t("keyboard_actions.show-sql-console"),
+ scope: "window"
+ },
+ {
+ friendlyName: t("keyboard_action_names.show-backend-log"),
+ actionName: "showBackendLog",
+ iconClass: "bx bx-detail",
+ defaultShortcuts: [],
+ description: t("keyboard_actions.show-backend-log"),
+ scope: "window"
+ },
+ {
+ friendlyName: t("keyboard_action_names.show-help"),
+ actionName: "showHelp",
+ iconClass: "bx bx-help-circle",
+ defaultShortcuts: ["F1"],
+ description: t("keyboard_actions.show-help"),
+ scope: "window"
+ },
+ {
+ friendlyName: t("keyboard_action_names.show-cheatsheet"),
+ actionName: "showCheatsheet",
+ iconClass: "bx bxs-keyboard",
+ defaultShortcuts: ["Shift+F1"],
+ description: t("keyboard_actions.show-cheatsheet"),
+ scope: "window"
+ },
+
+ {
+ separator: t("keyboard_actions.text-note-operations")
+ },
+
+ {
+ friendlyName: t("keyboard_action_names.add-link-to-text"),
+ actionName: "addLinkToText",
+ iconClass: "bx bx-link",
+ defaultShortcuts: ["CommandOrControl+L"],
+ description: t("keyboard_actions.add-link-to-text"),
+ scope: "text-detail"
+ },
+ {
+ friendlyName: t("keyboard_action_names.follow-link-under-cursor"),
+ actionName: "followLinkUnderCursor",
+ iconClass: "bx bx-link-external",
+ defaultShortcuts: ["CommandOrControl+Enter"],
+ description: t("keyboard_actions.follow-link-under-cursor"),
+ scope: "text-detail"
+ },
+ {
+ friendlyName: t("keyboard_action_names.insert-date-and-time-to-text"),
+ actionName: "insertDateTimeToText",
+ iconClass: "bx bx-calendar-event",
+ defaultShortcuts: ["Alt+T"],
+ description: t("keyboard_actions.insert-date-and-time-to-text"),
+ scope: "text-detail"
+ },
+ {
+ friendlyName: t("keyboard_action_names.paste-markdown-into-text"),
+ actionName: "pasteMarkdownIntoText",
+ iconClass: "bx bxl-markdown",
+ defaultShortcuts: [],
+ description: t("keyboard_actions.paste-markdown-into-text"),
+ scope: "text-detail"
+ },
+ {
+ friendlyName: t("keyboard_action_names.cut-into-note"),
+ actionName: "cutIntoNote",
+ iconClass: "bx bx-cut",
+ defaultShortcuts: [],
+ description: t("keyboard_actions.cut-into-note"),
+ scope: "text-detail"
+ },
+ {
+ friendlyName: t("keyboard_action_names.add-include-note-to-text"),
+ actionName: "addIncludeNoteToText",
+ iconClass: "bx bx-note",
+ defaultShortcuts: [],
+ description: t("keyboard_actions.add-include-note-to-text"),
+ scope: "text-detail"
+ },
+ {
+ friendlyName: t("keyboard_action_names.edit-read-only-note"),
+ actionName: "editReadOnlyNote",
+ iconClass: "bx bx-edit-alt",
+ defaultShortcuts: [],
+ description: t("keyboard_actions.edit-readonly-note"),
+ scope: "window"
+ },
+
+ {
+ separator: t("keyboard_actions.attributes-labels-and-relations")
+ },
+
+ {
+ friendlyName: t("keyboard_action_names.add-new-label"),
+ actionName: "addNewLabel",
+ iconClass: "bx bx-hash",
+ defaultShortcuts: ["Alt+L"],
+ description: t("keyboard_actions.add-new-label"),
+ scope: "window"
+ },
+ {
+ friendlyName: t("keyboard_action_names.add-new-relation"),
+ actionName: "addNewRelation",
+ iconClass: "bx bx-transfer",
+ defaultShortcuts: ["Alt+R"],
+ description: t("keyboard_actions.create-new-relation"),
+ scope: "window"
+ },
+
+ {
+ separator: t("keyboard_actions.ribbon-tabs")
+ },
+
+ {
+ friendlyName: t("keyboard_action_names.toggle-ribbon-tab-classic-editor"),
+ actionName: "toggleRibbonTabClassicEditor",
+ iconClass: "bx bx-text",
+ defaultShortcuts: [],
+ description: t("keyboard_actions.toggle-classic-editor-toolbar"),
+ scope: "window"
+ },
+ {
+ actionName: "toggleRibbonTabBasicProperties",
+ friendlyName: t("keyboard_action_names.toggle-ribbon-tab-basic-properties"),
+ iconClass: "bx bx-slider",
+ defaultShortcuts: [],
+ description: t("keyboard_actions.toggle-basic-properties"),
+ scope: "window"
+ },
+ {
+ actionName: "toggleRibbonTabBookProperties",
+ friendlyName: t("keyboard_action_names.toggle-ribbon-tab-book-properties"),
+ iconClass: "bx bx-book",
+ defaultShortcuts: [],
+ description: t("keyboard_actions.toggle-book-properties"),
+ scope: "window"
+ },
+ {
+ actionName: "toggleRibbonTabFileProperties",
+ friendlyName: t("keyboard_action_names.toggle-ribbon-tab-file-properties"),
+ iconClass: "bx bx-file",
+ defaultShortcuts: [],
+ description: t("keyboard_actions.toggle-file-properties"),
+ scope: "window"
+ },
+ {
+ actionName: "toggleRibbonTabImageProperties",
+ friendlyName: t("keyboard_action_names.toggle-ribbon-tab-image-properties"),
+ iconClass: "bx bx-image",
+ defaultShortcuts: [],
+ description: t("keyboard_actions.toggle-image-properties"),
+ scope: "window"
+ },
+ {
+ actionName: "toggleRibbonTabOwnedAttributes",
+ friendlyName: t("keyboard_action_names.toggle-ribbon-tab-owned-attributes"),
+ iconClass: "bx bx-list-check",
+ defaultShortcuts: ["Alt+A"],
+ description: t("keyboard_actions.toggle-owned-attributes"),
+ scope: "window"
+ },
+ {
+ actionName: "toggleRibbonTabInheritedAttributes",
+ friendlyName: t("keyboard_action_names.toggle-ribbon-tab-inherited-attributes"),
+ iconClass: "bx bx-list-plus",
+ defaultShortcuts: [],
+ description: t("keyboard_actions.toggle-inherited-attributes"),
+ scope: "window"
+ },
+ // TODO: Remove or change since promoted attributes have been changed.
+ {
+ actionName: "toggleRibbonTabPromotedAttributes",
+ friendlyName: t("keyboard_action_names.toggle-ribbon-tab-promoted-attributes"),
+ iconClass: "bx bx-star",
+ defaultShortcuts: [],
+ description: t("keyboard_actions.toggle-promoted-attributes"),
+ scope: "window"
+ },
+ {
+ actionName: "toggleRibbonTabNoteMap",
+ friendlyName: t("keyboard_action_names.toggle-ribbon-tab-note-map"),
+ iconClass: "bx bxs-network-chart",
+ defaultShortcuts: [],
+ description: t("keyboard_actions.toggle-link-map"),
+ scope: "window"
+ },
+ {
+ actionName: "toggleRibbonTabNoteInfo",
+ friendlyName: t("keyboard_action_names.toggle-ribbon-tab-note-info"),
+ iconClass: "bx bx-info-circle",
+ defaultShortcuts: [],
+ description: t("keyboard_actions.toggle-note-info"),
+ scope: "window"
+ },
+ {
+ actionName: "toggleRibbonTabNotePaths",
+ friendlyName: t("keyboard_action_names.toggle-ribbon-tab-note-paths"),
+ iconClass: "bx bx-collection",
+ defaultShortcuts: [],
+ description: t("keyboard_actions.toggle-note-paths"),
+ scope: "window"
+ },
+ {
+ actionName: "toggleRibbonTabSimilarNotes",
+ friendlyName: t("keyboard_action_names.toggle-ribbon-tab-similar-notes"),
+ iconClass: "bx bx-bar-chart",
+ defaultShortcuts: [],
+ description: t("keyboard_actions.toggle-similar-notes"),
+ scope: "window"
+ },
+
+ {
+ separator: t("keyboard_actions.other")
+ },
+
+ {
+ actionName: "toggleRightPane",
+ friendlyName: t("keyboard_action_names.toggle-right-pane"),
+ iconClass: "bx bx-dock-right",
+ defaultShortcuts: [],
+ description: t("keyboard_actions.toggle-right-pane"),
+ scope: "window"
+ },
+ {
+ actionName: "printActiveNote",
+ friendlyName: t("keyboard_action_names.print-active-note"),
+ iconClass: "bx bx-printer",
+ defaultShortcuts: [],
+ description: t("keyboard_actions.print-active-note"),
+ scope: "window"
+ },
+ {
+ actionName: "exportAsPdf",
+ friendlyName: t("keyboard_action_names.export-active-note-as-pdf"),
+ iconClass: "bx bxs-file-pdf",
+ defaultShortcuts: [],
+ description: t("keyboard_actions.export-as-pdf"),
+ scope: "window"
+ },
+ {
+ actionName: "openNoteExternally",
+ friendlyName: t("keyboard_action_names.open-note-externally"),
+ iconClass: "bx bx-file-find",
+ defaultShortcuts: [],
+ description: t("keyboard_actions.open-note-externally"),
+ scope: "window"
+ },
+ {
+ actionName: "renderActiveNote",
+ friendlyName: t("keyboard_action_names.render-active-note"),
+ iconClass: "bx bx-refresh",
+ defaultShortcuts: [],
+ description: t("keyboard_actions.render-active-note"),
+ scope: "window"
+ },
+ {
+ actionName: "runActiveNote",
+ friendlyName: t("keyboard_action_names.run-active-note"),
+ iconClass: "bx bx-play",
+ defaultShortcuts: ["CommandOrControl+Enter"],
+ description: t("keyboard_actions.run-active-note"),
+ scope: "code-detail"
+ },
+ {
+ actionName: "toggleNoteHoisting",
+ friendlyName: t("keyboard_action_names.toggle-note-hoisting"),
+ iconClass: "bx bx-chevrons-up",
+ defaultShortcuts: ["Alt+H"],
+ description: t("keyboard_actions.toggle-note-hoisting"),
+ scope: "window"
+ },
+ {
+ actionName: "unhoist",
+ friendlyName: t("keyboard_action_names.unhoist-note"),
+ iconClass: "bx bx-door-open",
+ defaultShortcuts: ["Alt+U"],
+ description: t("keyboard_actions.unhoist"),
+ scope: "window"
+ },
+ {
+ actionName: "reloadFrontendApp",
+ friendlyName: t("keyboard_action_names.reload-frontend-app"),
+ iconClass: "bx bx-refresh",
+ defaultShortcuts: ["F5", "CommandOrControl+R"],
+ description: t("keyboard_actions.reload-frontend-app"),
+ scope: "window"
+ },
+ {
+ actionName: "openDevTools",
+ friendlyName: t("keyboard_action_names.open-developer-tools"),
+ iconClass: "bx bx-bug-alt",
+ defaultShortcuts: isElectron() ? ["CommandOrControl+Shift+I"] : [],
+ isElectronOnly: true,
+ description: t("keyboard_actions.open-dev-tools"),
+ scope: "window"
+ },
+ {
+ actionName: "findInText",
+ friendlyName: t("keyboard_action_names.find-in-text"),
+ iconClass: "bx bx-search",
+ defaultShortcuts: isElectron() ? ["CommandOrControl+F"] : [],
+ description: t("keyboard_actions.find-in-text"),
+ scope: "window"
+ },
+ {
+ actionName: "toggleLeftPane",
+ friendlyName: t("keyboard_action_names.toggle-left-pane"),
+ iconClass: "bx bx-sidebar",
+ defaultShortcuts: [],
+ description: t("keyboard_actions.toggle-left-note-tree-panel"),
+ scope: "window"
+ },
+ {
+ actionName: "toggleFullscreen",
+ friendlyName: t("keyboard_action_names.toggle-full-screen"),
+ iconClass: "bx bx-fullscreen",
+ defaultShortcuts: ["F11"],
+ description: t("keyboard_actions.toggle-full-screen"),
+ scope: "window"
+ },
+ {
+ actionName: "zoomOut",
+ friendlyName: t("keyboard_action_names.zoom-out"),
+ iconClass: "bx bx-zoom-out",
+ defaultShortcuts: isElectron() ? ["CommandOrControl+-"] : [],
+ isElectronOnly: true,
+ description: t("keyboard_actions.zoom-out"),
+ scope: "window"
+ },
+ {
+ actionName: "zoomIn",
+ friendlyName: t("keyboard_action_names.zoom-in"),
+ iconClass: "bx bx-zoom-in",
+ description: t("keyboard_actions.zoom-in"),
+ defaultShortcuts: isElectron() ? ["CommandOrControl+="] : [],
+ isElectronOnly: true,
+ scope: "window"
+ },
+ {
+ actionName: "zoomReset",
+ friendlyName: t("keyboard_action_names.reset-zoom-level"),
+ iconClass: "bx bx-search-alt",
+ description: t("keyboard_actions.reset-zoom-level"),
+ defaultShortcuts: isElectron() ? ["CommandOrControl+0"] : [],
+ isElectronOnly: true,
+ scope: "window"
+ },
+ {
+ actionName: "copyWithoutFormatting",
+ friendlyName: t("keyboard_action_names.copy-without-formatting"),
+ iconClass: "bx bx-copy-alt",
+ defaultShortcuts: ["CommandOrControl+Alt+C"],
+ description: t("keyboard_actions.copy-without-formatting"),
+ scope: "text-detail"
+ },
+ {
+ actionName: "forceSaveRevision",
+ friendlyName: t("keyboard_action_names.force-save-revision"),
+ iconClass: "bx bx-save",
+ defaultShortcuts: [],
+ description: t("keyboard_actions.force-save-revision"),
+ scope: "window"
++ },
++ {
++ actionName: "saveNamedRevision",
++ friendlyName: t("keyboard_action_names.save-named-revision"),
++ iconClass: "bx bx-purchase-tag",
++ defaultShortcuts: [],
++ description: t("keyboard_actions.save-named-revision"),
++ scope: "window"
+ }
+ ];
+
+ /*
+ * Apply macOS-specific tweaks.
+ */
+ const platformModifier = isMac() ? "Meta" : "Ctrl";
+
+ for (const action of DEFAULT_KEYBOARD_ACTIONS) {
+ if ("defaultShortcuts" in action && action.defaultShortcuts) {
+ action.defaultShortcuts = action.defaultShortcuts.map((shortcut) => shortcut.replace("CommandOrControl", platformModifier));
+ }
+ }
+
+ return DEFAULT_KEYBOARD_ACTIONS;
+}
+
+function getKeyboardActions() {
+ const actions: KeyboardShortcut[] = JSON.parse(JSON.stringify(getDefaultKeyboardActions()));
+
+ for (const action of actions) {
+ if ("effectiveShortcuts" in action && action.effectiveShortcuts) {
+ action.effectiveShortcuts = action.defaultShortcuts ? action.defaultShortcuts.slice() : [];
+ }
+ }
+
+ const log = getLog();
+ for (const option of optionService.getOptions()) {
+ if (option.name.startsWith("keyboardShortcuts")) {
+ let actionName = option.name.substring(17);
+ actionName = actionName.charAt(0).toLowerCase() + actionName.slice(1);
+
+ const action = actions.find((ea) => "actionName" in ea && ea.actionName === actionName) as ActionKeyboardShortcut;
+
+ if (action) {
+ try {
+ action.effectiveShortcuts = JSON.parse(option.value);
+ } catch (e) {
+ log.error(`Could not parse shortcuts for action ${actionName}`);
+ }
+ } else {
+ log.info(`Keyboard action ${actionName} found in database, but not in action definition.`);
+ }
+ }
+ }
+
+ return actions;
+}
+
+export default {
+ getDefaultKeyboardActions,
+ getKeyboardActions
+};
diff --cc packages/trilium-core/src/services/migration.ts
index 8084d834ac,4edb9fb028..209ad6f76b
--- a/packages/trilium-core/src/services/migration.ts
+++ b/packages/trilium-core/src/services/migration.ts
@@@ -131,8 -130,13 +131,13 @@@ function isDbUpToDate()
async function migrateIfNecessary() {
const currentDbVersion = getDbVersion();
+ if (isNaN(currentDbVersion)) {
- await crash(t("migration.invalid_db_version"));
++ getPlatform().crash(t("migration.invalid_db_version"));
+ return;
+ }
+
- if (currentDbVersion > appInfo.dbVersion && process.env.TRILIUM_IGNORE_DB_VERSION !== "true") {
- await crash(t("migration.wrong_db_version", { version: currentDbVersion, targetVersion: appInfo.dbVersion }));
+ if (currentDbVersion > appInfo.dbVersion && getPlatform().getEnv("TRILIUM_IGNORE_DB_VERSION") !== "true") {
+ getPlatform().crash(t("migration.wrong_db_version", { version: currentDbVersion, targetVersion: appInfo.dbVersion }));
}
if (!isDbUpToDate()) {
diff --cc packages/trilium-core/src/services/options_init.ts
index 8d814b752f,0000000000..f445ce964b
mode 100644,000000..100644
--- a/packages/trilium-core/src/services/options_init.ts
+++ b/packages/trilium-core/src/services/options_init.ts
@@@ -1,305 -1,0 +1,313 @@@
+import { type KeyboardShortcutWithRequiredActionName, type OptionMap, type OptionNames, SANITIZER_DEFAULT_ALLOWED_TAGS } from "@triliumnext/commons";
+
+import appInfo from "./app_info.js";
+import { getPlatform } from "./platform.js";
+import dateUtils from "./utils/date.js";
+import keyboardActions from "./keyboard_actions.js";
+import { getLog } from "./log.js";
+import optionService from "./options.js";
+import { isWindows, randomSecureToken } from "./utils/index.js";
+
+export function initDocumentOptions() {
+ optionService.createOption("documentId", randomSecureToken(16), false);
+ optionService.createOption("documentSecret", randomSecureToken(16), false);
+}
+
+/**
+ * Contains additional options to be initialized for a new database, containing the information entered by the user.
+ */
+interface NotSyncedOpts {
+ syncServerHost?: string;
+ syncProxy?: string;
+}
+
+/**
+ * Represents a correspondence between an option and its default value, to be initialized when the database is missing that particular option (after a migration from an older version, or when creating a new database).
+ */
+interface DefaultOption {
+ name: OptionNames;
+ /**
+ * The value to initialize the option with, if the option is not already present in the database.
+ *
+ * If a function is passed Gin instead, the function is called if the option does not exist (with access to the current options) and the return value is used instead. Useful to migrate a new option with a value depending on some other option that might be initialized.
+ */
+ value: string | ((options: OptionMap) => string);
+ isSynced: boolean;
+}
+
+/**
+ * Initializes the default options for new databases only.
+ *
+ * @param initialized `true` if the database has been fully initialized (i.e. a new database was created), or `false` if the database is created for sync.
+ * @param opts additional options to be initialized, for example the sync configuration.
+ */
+export async function initNotSyncedOptions(initialized: boolean, opts: NotSyncedOpts = {}) {
+ optionService.createOption(
+ "openNoteContexts",
+ JSON.stringify([
+ {
+ notePath: "root",
+ active: true
+ }
+ ]),
+ false
+ );
+
+ optionService.createOption("lastDailyBackupDate", dateUtils.utcNowDateTime(), false);
+ optionService.createOption("lastWeeklyBackupDate", dateUtils.utcNowDateTime(), false);
+ optionService.createOption("lastMonthlyBackupDate", dateUtils.utcNowDateTime(), false);
+ optionService.createOption("dbVersion", appInfo.dbVersion.toString(), false);
+
+ optionService.createOption("initialized", initialized ? "true" : "false", false);
+
+ optionService.createOption("lastSyncedPull", "0", false);
+ optionService.createOption("lastSyncedPush", "0", false);
+
+ optionService.createOption("theme", "next", false);
+ optionService.createOption("textNoteEditorType", "ckeditor-classic", true);
+
+ optionService.createOption("syncServerHost", opts.syncServerHost || "", false);
+ optionService.createOption("syncServerTimeout", "120", false); // 120 seconds (2 minutes)
+ optionService.createOption("syncProxy", opts.syncProxy || "", false);
+}
+
+/**
+ * Migrates a sync timeout value from milliseconds to seconds.
+ * Values >= 1000 are assumed to be in milliseconds (since 1000+ seconds = 16+ minutes is unlikely).
+ * TimeSelector stores values in seconds; the scale is only used for display.
+ *
+ * @returns The value in seconds and preferred display scale, or null if no migration is needed.
+ */
+export function migrateSyncTimeoutFromMilliseconds(milliseconds: number): { value: number; scale: number } | null {
+ if (isNaN(milliseconds) || milliseconds < 1000) {
+ return null;
+ }
+
+ const seconds = Math.round(milliseconds / 1000);
+
+ // Value is always stored in seconds; scale determines display unit
+ if (seconds >= 60 && seconds % 60 === 0) {
+ return { value: seconds, scale: 60 }; // display as minutes
+ }
+ return { value: seconds, scale: 1 }; // display as seconds
+}
+
+/**
+ * Contains all the default options that must be initialized on new and existing databases (at startup). The value can also be determined based on other options, provided they have already been initialized.
+ */
+const defaultOptions: DefaultOption[] = [
+ {
+ name: "syncServerTimeoutTimeScale",
+ value: (optionsMap) => {
+ const timeout = parseInt(optionsMap.syncServerTimeout || "120", 10);
+ const migrated = migrateSyncTimeoutFromMilliseconds(timeout);
+ if (migrated) {
+ optionService.setOption("syncServerTimeout", String(migrated.value));
+ getLog().info(`Migrated syncServerTimeout from ${timeout}ms to ${migrated.value}s`);
+ return String(migrated.scale);
+ }
+ return "60"; // default to minutes
+ },
+ isSynced: false
+ },
+ { name: "revisionSnapshotTimeInterval", value: "600", isSynced: true },
+ { name: "revisionSnapshotTimeIntervalTimeScale", value: "60", isSynced: true }, // default to Minutes
+ { name: "revisionSnapshotNumberLimit", value: "-1", isSynced: true },
+ { name: "protectedSessionTimeout", value: "600", isSynced: true },
+ { name: "protectedSessionTimeoutTimeScale", value: "60", isSynced: true },
+ { name: "zoomFactor", value: () => isWindows() ? "0.9" : "1.0", isSynced: false },
+ { name: "overrideThemeFonts", value: "false", isSynced: false },
+ { name: "mainFontFamily", value: "theme", isSynced: false },
+ { name: "mainFontSize", value: "100", isSynced: false },
+ { name: "treeFontFamily", value: "theme", isSynced: false },
+ { name: "treeFontSize", value: "100", isSynced: false },
+ { name: "detailFontFamily", value: "theme", isSynced: false },
+ { name: "detailFontSize", value: "110", isSynced: false },
+ { name: "monospaceFontFamily", value: "theme", isSynced: false },
+ { name: "monospaceFontSize", value: "110", isSynced: false },
+ { name: "spellCheckEnabled", value: "true", isSynced: false },
+ { name: "spellCheckLanguageCode", value: "en-US", isSynced: false },
+ { name: "imageMaxWidthHeight", value: "2000", isSynced: true },
+ { name: "imageJpegQuality", value: "75", isSynced: true },
+ { name: "autoFixConsistencyIssues", value: "true", isSynced: false },
+ { name: "vimKeymapEnabled", value: "false", isSynced: false },
+ { name: "codeLineWrapEnabled", value: "true", isSynced: false },
++ { name: "codeNoteTabWidth", value: "4", isSynced: true },
++ { name: "codeNoteIndentWithTabs", value: "false", isSynced: true },
+ {
+ name: "codeNotesMimeTypes",
+ value: '["text/x-csrc","text/x-c++src","text/x-csharp","text/css","text/x-elixir","text/x-go","text/x-groovy","text/x-haskell","text/html","message/http","text/x-java","application/javascript;env=frontend","application/javascript;env=backend","application/json","text/x-kotlin","text/x-markdown","text/x-perl","text/x-php","text/x-python","text/x-ruby",null,"text/x-sql","text/x-sqlite;schema=trilium","text/x-swift","text/xml","text/x-yaml","text/x-sh","application/typescript"]',
+ isSynced: true
+ },
+ { name: "leftPaneWidth", value: "25", isSynced: false },
+ { name: "leftPaneVisible", value: "true", isSynced: false },
+ { name: "rightPaneWidth", value: "25", isSynced: false },
+ { name: "rightPaneVisible", value: "true", isSynced: false },
+ { name: "rightPaneCollapsedItems", value: "[]", isSynced: false },
+ { name: "nativeTitleBarVisible", value: "false", isSynced: false },
+ { name: "eraseEntitiesAfterTimeInSeconds", value: "604800", isSynced: true }, // default is 7 days
+ { name: "eraseEntitiesAfterTimeScale", value: "86400", isSynced: true }, // default 86400 seconds = Day
+ { name: "hideArchivedNotes_main", value: "false", isSynced: false },
+ { name: "debugModeEnabled", value: "false", isSynced: false },
+ { name: "headingStyle", value: "underline", isSynced: true },
+ { name: "autoCollapseNoteTree", value: "true", isSynced: true },
+ { name: "autoReadonlySizeText", value: "32000", isSynced: false },
+ { name: "autoReadonlySizeCode", value: "64000", isSynced: false },
+ { name: "dailyBackupEnabled", value: "true", isSynced: false },
+ { name: "weeklyBackupEnabled", value: "true", isSynced: false },
+ { name: "monthlyBackupEnabled", value: "true", isSynced: false },
+ { name: "maxContentWidth", value: "1200", isSynced: false },
+ { name: "centerContent", value: "false", isSynced: false },
+ { name: "compressImages", value: "true", isSynced: true },
+ { name: "downloadImagesAutomatically", value: "true", isSynced: true },
+ { name: "minTocHeadings", value: "5", isSynced: true },
+ { name: "highlightsList", value: '["underline","color","bgColor"]', isSynced: true },
+ { name: "checkForUpdates", value: "true", isSynced: true },
+ { name: "disableTray", value: "false", isSynced: false },
+ { name: "eraseUnusedAttachmentsAfterSeconds", value: "2592000", isSynced: true }, // default 30 days
+ { name: "eraseUnusedAttachmentsAfterTimeScale", value: "86400", isSynced: true }, // default 86400 seconds = Day
+ { name: "logRetentionDays", value: "90", isSynced: false }, // default 90 days
+ { name: "customSearchEngineName", value: "DuckDuckGo", isSynced: true },
+ { name: "customSearchEngineUrl", value: "https://duckduckgo.com/?q={keyword}", isSynced: true },
++
++ // Search settings
++ { name: "searchEnableFuzzyMatching", value: "true", isSynced: true },
++ { name: "searchAutocompleteFuzzy", value: "false", isSynced: true },
++
+ { name: "editedNotesOpenInRibbon", value: "true", isSynced: true },
+ { name: "mfaEnabled", value: "false", isSynced: false },
+ { name: "mfaMethod", value: "totp", isSynced: false },
+ { name: "encryptedRecoveryCodes", value: "false", isSynced: false },
+ { name: "userSubjectIdentifierSaved", value: "false", isSynced: false },
+
+ // Appearance
+ { name: "splitEditorOrientation", value: "horizontal", isSynced: true },
+ {
+ name: "codeNoteTheme",
+ value: (optionsMap) => {
+ switch (optionsMap.theme) {
+ case "light":
+ case "next-light":
+ return "default:vs-code-light";
+ case "dark":
+ case "next-dark":
+ default:
+ return "default:vs-code-dark";
+ }
+ },
+ isSynced: false
+ },
+ { name: "motionEnabled", value: "true", isSynced: false },
+ { name: "shadowsEnabled", value: "true", isSynced: false },
+ { name: "backdropEffectsEnabled", value: "true", isSynced: false },
+ { name: "smoothScrollEnabled", value: "true", isSynced: false },
+ { name: "newLayout", value: "true", isSynced: true },
+
+ // Internationalization
+ { name: "locale", value: "en", isSynced: true },
+ { name: "formattingLocale", value: "", isSynced: true }, // no value means auto-detect
+ { name: "firstDayOfWeek", value: "1", isSynced: true },
+ { name: "firstWeekOfYear", value: "0", isSynced: true },
+ { name: "minDaysInFirstWeek", value: "4", isSynced: true },
+ { name: "languages", value: "[]", isSynced: true },
+
+ // Code block configuration
+ {
+ name: "codeBlockTheme",
+ value: (optionsMap) => {
+ if (optionsMap.theme === "light") {
+ return "default:stackoverflow-light";
+ }
+ return "default:stackoverflow-dark";
+
+ },
+ isSynced: false
+ },
+ { name: "codeBlockWordWrap", value: "false", isSynced: true },
++ { name: "codeBlockTabWidth", value: "4", isSynced: true },
+
+ // Text note configuration
+ { name: "textNoteEditorType", value: "ckeditor-balloon", isSynced: true },
+ { name: "textNoteEditorMultilineToolbar", value: "false", isSynced: true },
+ { name: "textNoteEmojiCompletionEnabled", value: "true", isSynced: true },
+ { name: "textNoteCompletionEnabled", value: "true", isSynced: true },
+ { name: "textNoteSlashCommandsEnabled", value: "true", isSynced: true },
+ { name: "includeNoteDefaultBoxSize", value: "medium", isSynced: true },
+
+ // HTML import configuration
+ { name: "layoutOrientation", value: "vertical", isSynced: false },
+ { name: "backgroundEffects", value: "true", isSynced: false },
+ {
+ name: "allowedHtmlTags",
+ value: JSON.stringify(SANITIZER_DEFAULT_ALLOWED_TAGS),
+ isSynced: true
+ },
+
+ // Share settings
+ { name: "redirectBareDomain", value: "false", isSynced: true },
+ { name: "showLoginInShareTheme", value: "false", isSynced: true },
+
+ {
+ name: "seenCallToActions",
+ value: JSON.stringify([
+ "new_layout", "background_effects", "next_theme"
+ ]),
+ isSynced: true
+ },
+ { name: "experimentalFeatures", value: "[]", isSynced: true },
+
+ // AI / LLM
+ { name: "llmProviders", value: "[]", isSynced: true },
+ { name: "mcpEnabled", value: "false", isSynced: false },
+
+ // OCR options
+ { name: "ocrAutoProcessImages", value: "false", isSynced: true },
+ { name: "ocrMinConfidence", value: "0.75", isSynced: true },
+];
+
+/**
+ * Initializes the options, by checking which options from {@link #allDefaultOptions()} are missing and registering them. It will also check some environment variables such as safe mode, to make any necessary adjustments.
+ *
+ * This method is called regardless of whether a new database is created, or an existing database is used.
+ */
+export function initStartupOptions() {
+ const optionsMap = optionService.getOptionMap();
+
+ const allDefaultOptions = defaultOptions.concat(getKeyboardDefaultOptions());
+
+ const log = getLog();
+ for (const { name, value, isSynced } of allDefaultOptions) {
+ if (!(name in optionsMap)) {
+ let resolvedValue;
+ if (typeof value === "function") {
+ resolvedValue = value(optionsMap);
+ } else {
+ resolvedValue = value;
+ }
+
+ optionService.createOption(name, resolvedValue, isSynced);
+ log.info(`Created option "${name}" with default value "${resolvedValue}"`);
+ }
+ }
+
+ if (getPlatform().getEnv("TRILIUM_START_NOTE_ID") || getPlatform().getEnv("TRILIUM_SAFE_MODE")) {
+ optionService.setOption(
+ "openNoteContexts",
+ JSON.stringify([
+ {
+ notePath: getPlatform().getEnv("TRILIUM_START_NOTE_ID") || "root",
+ active: true
+ }
+ ])
+ );
+ }
+}
+
+function getKeyboardDefaultOptions() {
+ return (keyboardActions.getDefaultKeyboardActions().filter((ka) => "actionName" in ka) as KeyboardShortcutWithRequiredActionName[]).map((ka) => ({
+ name: `keyboardShortcuts${ka.actionName.charAt(0).toUpperCase()}${ka.actionName.slice(1)}`,
+ value: JSON.stringify(ka.defaultShortcuts),
+ isSynced: false
+ })) as DefaultOption[];
+}
+
diff --cc packages/trilium-core/src/services/sanitizer.spec.ts
index 807e73c70b,6af366a329..734f5f69a1
--- a/packages/trilium-core/src/services/sanitizer.spec.ts
+++ b/packages/trilium-core/src/services/sanitizer.spec.ts
@@@ -48,6 -48,28 +48,28 @@@ describe("sanitize", () =>
</tbody>
</table>
</figure>`;
- expect(html_sanitizer.sanitize(dirty)).toBe(clean);
+ expect(sanitizeHtml(dirty)).toBe(clean);
});
+
+ describe("bookmark anchors", () => {
+ it("preserves id attribute on empty <a> tags (CKEditor bookmarks)", () => {
+ const dirty = `<a id="my-bookmark"></a>`;
+ expect(html_sanitizer.sanitize(dirty)).toBe(dirty);
+ });
+
+ it("preserves id attribute on <a> tags with bookmark class", () => {
+ const dirty = `<a id="chapter-1" class="ck-bookmark"></a>`;
+ expect(html_sanitizer.sanitize(dirty)).toBe(dirty);
+ });
+
+ it("strips id attribute from non-anchor tags to prevent DOM clobbering", () => {
+ const dirty = `<div id="loginForm">content</div>`;
+ expect(html_sanitizer.sanitize(dirty)).toBe(`<div>content</div>`);
+ });
+
+ it("strips id attribute from <img> tags to prevent DOM clobbering", () => {
+ const dirty = `<img id="someId" src="test.png" />`;
+ expect(html_sanitizer.sanitize(dirty)).toBe(`<img src="test.png" />`);
+ });
+ });
});
diff --cc packages/trilium-core/src/services/search/expressions/note_flat_text.ts
index 950fe59bee,b12413738e..17beffb721
--- a/packages/trilium-core/src/services/search/expressions/note_flat_text.ts
+++ b/packages/trilium-core/src/services/search/expressions/note_flat_text.ts
@@@ -1,10 -1,14 +1,10 @@@
-"use strict";
-
+import becca_service from "../../../becca/becca_service.js";
+import becca from "../../../becca/becca.js";
import type BNote from "../../../becca/entities/bnote.js";
+import NoteSet from "../note_set.js";
import type SearchContext from "../search_context.js";
- import { fuzzyMatchWord, fuzzyMatchWordWithResult,normalizeSearchText } from "../utils/text_utils.js";
-
++import { fuzzyMatchWordWithResult, normalizeSearchText } from "../utils/text_utils.js";
import Expression from "./expression.js";
-import NoteSet from "../note_set.js";
-import becca from "../../../becca/becca.js";
-import { normalize } from "../../utils.js";
-import { normalizeSearchText, fuzzyMatchWordWithResult } from "../utils/text_utils.js";
-import beccaService from "../../../becca/becca_service.js";
class NoteFlatTextExp extends Expression {
tokens: string[];
@@@ -19,6 -23,18 +19,18 @@@
execute(inputNoteSet: NoteSet, executionContext: any, searchContext: SearchContext) {
const resultNoteSet = new NoteSet();
+ // Cache normalized titles to avoid redundant normalize+getNoteTitle calls
+ const titleCache = new Map<string, string>();
+ const getNormalizedTitle = (noteId: string, parentNoteId: string): string => {
+ const key = `${noteId}-${parentNoteId}`;
+ let cached = titleCache.get(key);
+ if (cached === undefined) {
- cached = normalizeSearchText(beccaService.getNoteTitle(noteId, parentNoteId));
++ cached = normalizeSearchText(becca_service.getNoteTitle(noteId, parentNoteId));
+ titleCache.set(key, cached);
+ }
+ return cached;
+ };
+
/**
* @param note
* @param remainingTokens - tokens still needed to be found in the path towards root
diff --cc packages/trilium-core/src/services/search/utils/text_utils.ts
index 84b6a66d23,87a171a7eb..8048dc709a
--- a/packages/trilium-core/src/services/search/utils/text_utils.ts
+++ b/packages/trilium-core/src/services/search/utils/text_utils.ts
@@@ -273,24 -297,24 +297,24 @@@ export function fuzzyMatchWordWithResul
if (token.length === 0 || text.length === 0) {
return null;
}
-
+
try {
- // Normalize both strings for comparison
+ // Normalize for comparison — some callers pass pre-normalized text,
+ // others don't, so this function must be self-contained.
const normalizedToken = token.toLowerCase();
const normalizedText = text.toLowerCase();
// Exact match check first (most common case)
if (normalizedText.includes(normalizedToken)) {
- // Find the exact match in the original text to preserve case
- const exactMatch = text.match(new RegExp(escapeRegExp(token), 'i'));
- return exactMatch ? exactMatch[0] : token;
+ // Find the exact match position and return the original substring with case preserved
+ const matchIndex = normalizedText.indexOf(normalizedToken);
+ return text.substring(matchIndex, matchIndex + normalizedToken.length);
}
- // For fuzzy matching, we need to check individual words in the text
- // Split the text into words and check each word against the token
+ // For fuzzy matching, split into words and check each against the token
const words = normalizedText.split(/\s+/).filter(word => word.length > 0);
const originalWords = text.split(/\s+/).filter(word => word.length > 0);
-
+
for (let i = 0; i < words.length; i++) {
const word = words[i];
const originalWord = originalWords[i];
diff --cc packages/trilium-core/src/test/fixtures/document.db
index 371c3a1329,f5cf761826..f5cf761826
Binary files differ
diff --cc packages/trilium-e2e/package.json
index db10fca3fd,3c0dd5b162..ca01d0a026
--- a/packages/trilium-e2e/package.json
+++ b/packages/trilium-e2e/package.json
@@@ -1,9 -1,11 +1,9 @@@
{
- "name": "@triliumnext/server-e2e",
+ "name": "@triliumnext/trilium-e2e",
"version": "0.0.1",
"private": true,
- "scripts": {
- "e2e": "playwright test"
- },
+ "scripts": {},
"devDependencies": {
- "dotenv": "17.4.1"
+ "dotenv": "17.4.2"
}
}
diff --cc packages/trilium-e2e/src/settings.spec.ts
index e59d6a8c7a,26bf614d57..d1262f0832
--- a/packages/trilium-e2e/src/settings.spec.ts
+++ b/packages/trilium-e2e/src/settings.spec.ts
@@@ -4,15 -4,15 +4,15 @@@ import App from "./support/app"
test("Native Title Bar not displayed on web", async ({ page, context }) => {
const app = new App(page, context);
- await app.goto({ url: "http://localhost:8082/#root/_hidden/_options/_optionsAppearance" });
+ await app.goto({ url: "/#root/_hidden/_options/_optionsAppearance" });
- await expect(app.currentNoteSplitContent.getByRole("heading", { name: "Theme" })).toBeVisible();
+ await expect(app.currentNoteSplitContent.getByRole("heading", { name: "User Interface" })).toBeVisible();
await expect(app.currentNoteSplitContent.getByRole("heading", { name: "Native Title Bar (requires" })).toBeHidden();
});
test("Tray settings not displayed on web", async ({ page, context }) => {
const app = new App(page, context);
- await app.goto({ url: "http://localhost:8082/#root/_hidden/_options/_optionsOther" });
+ await app.goto({ url: "/#root/_hidden/_options/_optionsOther" });
- await expect(app.currentNoteSplitContent.getByRole("heading", { name: "Note Erasure Timeout" })).toBeVisible();
+ await expect(app.currentNoteSplitContent.getByRole("heading", { name: "Deleted Notes" })).toBeVisible();
await expect(app.currentNoteSplitContent.getByRole("heading", { name: "Tray" })).toBeHidden();
});
diff --cc pnpm-lock.yaml
index 801f4be354,6eb381bda8..1628291fe0
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@@ -172,30 -172,23 +172,30 @@@ importers
specifier: 6.0.2
version: 6.0.2
typescript-eslint:
- specifier: 8.58.1
+ specifier: 8.58.2
vite:
- specifier: 8.0.7
+ specifier: 8.0.8
vite-plugin-dts:
specifier: 4.5.4
vitest:
- specifier: 4.1.3
+ specifier: 4.1.4
apps/build-docs:
+ dependencies:
+ '@triliumnext/core':
+ specifier: workspace:*
+ version: link:../../packages/trilium-core
+ '@triliumnext/server':
+ specifier: workspace:*
+ version: link:../server
devDependencies:
'@redocly/cli':
- specifier: 2.26.0
+ specifier: 2.28.0
archiver:
specifier: 7.0.1
version: 7.0.1
@@@ -424,234 -420,8 +427,234 @@@
version: 0.7.2
vite-plugin-static-copy:
specifier: 4.0.1
+ apps/client-standalone:
+ dependencies:
+ '@excalidraw/excalidraw':
+ specifier: 0.18.0
+ '@fullcalendar/core':
+ specifier: 6.1.20
+ version: 6.1.20
+ '@fullcalendar/daygrid':
+ specifier: 6.1.20
+ version: 6.1.20(@fullcalendar/[email protected])
+ '@fullcalendar/interaction':
+ specifier: 6.1.20
+ version: 6.1.20(@fullcalendar/[email protected])
+ '@fullcalendar/list':
+ specifier: 6.1.20
+ version: 6.1.20(@fullcalendar/[email protected])
+ '@fullcalendar/multimonth':
+ specifier: 6.1.20
+ version: 6.1.20(@fullcalendar/[email protected])
+ '@fullcalendar/timegrid':
+ specifier: 6.1.20
+ version: 6.1.20(@fullcalendar/[email protected])
+ '@maplibre/maplibre-gl-leaflet':
+ specifier: 0.1.3
+ '@mermaid-js/layout-elk':
+ specifier: 0.2.1
+ version: 0.2.1([email protected])
+ '@mind-elixir/node-menu':
+ specifier: 5.0.1
+ version: 5.0.1([email protected])
+ '@popperjs/core':
+ specifier: 2.11.8
+ version: 2.11.8
+ '@preact/signals':
+ specifier: 2.9.0
+ version: 2.9.0([email protected])
+ '@sqlite.org/sqlite-wasm':
+ specifier: 3.51.1-build2
+ version: 3.51.1-build2
+ '@triliumnext/ckeditor5':
+ specifier: workspace:*
+ version: link:../../packages/ckeditor5
+ '@triliumnext/codemirror':
+ specifier: workspace:*
+ version: link:../../packages/codemirror
+ '@triliumnext/commons':
+ specifier: workspace:*
+ version: link:../../packages/commons
+ '@triliumnext/core':
+ specifier: workspace:*
+ version: link:../../packages/trilium-core
+ '@triliumnext/highlightjs':
+ specifier: workspace:*
+ version: link:../../packages/highlightjs
+ '@triliumnext/share-theme':
+ specifier: workspace:*
+ version: link:../../packages/share-theme
+ '@triliumnext/split.js':
+ specifier: workspace:*
+ version: link:../../packages/splitjs
+ '@zumer/snapdom':
+ specifier: 2.8.0
+ version: 2.8.0
+ aes-js:
+ specifier: 3.1.2
+ version: 3.1.2
+ autocomplete.js:
+ specifier: 0.38.1
+ version: 0.38.1
+ bootstrap:
+ specifier: 5.3.8
+ version: 5.3.8(@popperjs/[email protected])
+ boxicons:
+ specifier: 2.1.4
+ version: 2.1.4
+ clsx:
+ specifier: 2.1.1
+ version: 2.1.1
+ color:
+ specifier: 5.0.3
+ version: 5.0.3
+ debounce:
+ specifier: 3.0.0
+ version: 3.0.0
+ draggabilly:
+ specifier: 3.0.0
+ version: 3.0.0
+ fflate:
+ specifier: 0.8.2
+ version: 0.8.2
+ force-graph:
+ specifier: 1.51.2
+ version: 1.51.2
+ globals:
+ specifier: 17.4.0
+ version: 17.4.0
+ i18next:
+ specifier: 26.0.4
+ version: 26.0.4([email protected])
+ i18next-http-backend:
+ specifier: 3.0.4
+ version: 3.0.4([email protected])
+ jquery:
+ specifier: 4.0.0
+ version: 4.0.0
+ jquery.fancytree:
+ specifier: 2.38.5
+ version: 2.38.5([email protected])
+ js-md5:
+ specifier: 0.8.3
+ version: 0.8.3
+ js-sha1:
+ specifier: 0.7.0
+ version: 0.7.0
+ js-sha256:
+ specifier: 0.11.1
+ version: 0.11.1
+ js-sha512:
+ specifier: 0.9.0
+ version: 0.9.0
+ jsplumb:
+ specifier: 2.15.6
+ version: 2.15.6
+ katex:
+ specifier: 0.16.45
+ version: 0.16.45
+ knockout:
+ specifier: 3.5.1
+ version: 3.5.1
+ leaflet:
+ specifier: 1.9.4
+ version: 1.9.4
+ leaflet-gpx:
+ specifier: 2.2.0
+ version: 2.2.0
+ mark.js:
+ specifier: 8.11.1
+ version: 8.11.1
+ marked:
+ specifier: 18.0.0
+ version: 18.0.0
+ mermaid:
+ specifier: 11.14.0
+ version: 11.14.0
+ mind-elixir:
+ specifier: 5.10.0
+ version: 5.10.0
+ normalize.css:
+ specifier: 8.0.1
+ version: 8.0.1
+ panzoom:
+ specifier: 9.4.4
+ version: 9.4.4
+ preact:
+ specifier: 10.29.1
+ version: 10.29.1
+ react-i18next:
+ specifier: 17.0.2
+ react-window:
+ specifier: 2.2.7
+ reveal.js:
+ specifier: 6.0.0
+ version: 6.0.0
+ scrypt-js:
+ specifier: 3.0.1
+ version: 3.0.1
+ svg-pan-zoom:
+ specifier: 3.6.2
+ version: 3.6.2
+ tabulator-tables:
+ specifier: 6.4.0
+ version: 6.4.0
+ vanilla-js-wheel-zoom:
+ specifier: 9.0.4
+ version: 9.0.4
+ devDependencies:
+ '@ckeditor/ckeditor5-inspector':
+ specifier: 5.0.0
+ version: 5.0.0
+ '@preact/preset-vite':
+ specifier: 2.10.2
+ '@types/aes-js':
+ specifier: 3.1.4
+ version: 3.1.4
+ '@types/bootstrap':
+ specifier: 5.2.10
+ version: 5.2.10
+ '@types/jquery':
+ specifier: 4.0.0
+ version: 4.0.0
+ '@types/leaflet':
+ specifier: 1.9.21
+ version: 1.9.21
+ '@types/leaflet-gpx':
+ specifier: 1.3.8
+ version: 1.3.8
+ '@types/mark.js':
+ specifier: 8.11.12
+ version: 8.11.12
+ '@types/reveal.js':
+ specifier: 5.2.2
+ version: 5.2.2
+ '@types/tabulator-tables':
+ specifier: 6.3.1
+ version: 6.3.1
+ copy-webpack-plugin:
+ specifier: 14.0.0
+ cross-env:
+ specifier: 7.0.3
+ version: 7.0.3
+ happy-dom:
+ specifier: 20.8.9
+ script-loader:
+ specifier: 0.7.2
+ version: 0.7.2
+ vite-plugin-static-copy:
+ specifier: 4.0.1
+
apps/db-compare:
dependencies:
colors:
@@@ -837,9 -595,15 +840,9 @@@
js-yaml:
specifier: 4.1.1
version: 4.1.1
- node-html-parser:
- specifier: 7.1.0
- version: 7.1.0
- sucrase:
- specifier: 3.35.1
- version: 3.35.1
unpdf:
- specifier: 1.4.0
- version: 1.4.0(@napi-rs/[email protected])
+ specifier: 1.6.0
+ version: 1.6.0(@napi-rs/[email protected])
devDependencies:
'@braintree/sanitize-url':
specifier: 7.1.2
@@@ -1060,9 -863,15 +1063,9 @@@
turnish:
specifier: 1.8.0
version: 1.8.0
- unescape:
- specifier: 1.0.1
- version: 1.0.1
vite:
- specifier: 8.0.7
+ specifier: 8.0.8
- ws:
- specifier: 8.20.0
xml2js:
specifier: 0.6.2
version: 0.6.2
@@@ -1635,73 -1453,12 +1641,73 @@@
specifier: 1.0.3
version: 1.0.3([email protected])
happy-dom:
- specifier: 20.8.9
+ specifier: 20.9.0
vitest:
- specifier: 4.1.3
+ specifier: 4.1.4
+ packages/trilium-core:
+ dependencies:
+ '@braintree/sanitize-url':
+ specifier: 7.1.1
+ version: 7.1.1
+ '@triliumnext/commons':
+ specifier: workspace:*
+ version: link:../commons
+ '@triliumnext/turndown-plugin-gfm':
+ specifier: workspace:*
+ version: link:../turndown-plugin-gfm
+ async-mutex:
+ specifier: 0.5.0
+ version: 0.5.0
+ chardet:
+ specifier: 2.1.1
+ version: 2.1.1
+ escape-html:
+ specifier: 1.0.3
+ version: 1.0.3
+ i18next:
+ specifier: 26.0.4
+ version: 26.0.4([email protected])
+ mime-types:
+ specifier: 3.0.2
+ version: 3.0.2
+ node-html-parser:
+ specifier: 7.1.0
+ version: 7.1.0
+ sanitize-filename:
+ specifier: 1.6.4
+ version: 1.6.4
+ sanitize-html:
+ specifier: 2.17.2
+ version: 2.17.2
+ strip-bom:
+ specifier: 5.0.0
+ version: 5.0.0
+ sucrase:
+ specifier: 3.35.1
+ version: 3.35.1
+ unescape:
+ specifier: 1.0.1
+ version: 1.0.1
+ devDependencies:
+ '@types/escape-html':
+ specifier: 1.0.4
+ version: 1.0.4
+ '@types/mime-types':
+ specifier: 3.0.1
+ version: 3.0.1
+ '@types/sanitize-html':
+ specifier: 2.16.1
+ version: 2.16.1
+
+ packages/trilium-e2e:
+ devDependencies:
+ dotenv:
- specifier: 17.4.1
- version: 17.4.1
++ specifier: 17.4.2
++ version: 17.4.2
+
packages/turndown-plugin-gfm:
devDependencies:
happy-dom:
@@@ -6803,6 -6680,10 +6945,11 @@@ packages
resolution: {integrity: sha512-9k/gHF6n/pAi/9tqr3m3aqkuiNosYTurLLUtc7xQ9sxB/wm7WPygCv8GYa6mS0fLJEHhqMC1ATYhz++U/lRHqg==}
engines: {node: '>=10.0.0'}
+ '@xmldom/[email protected]':
+ resolution: {integrity: sha512-qycIHAucxy/LXAYIjmLmtQ8q9GPnMbnjG1KXhWm9o5sCr6pOYDATkMPiTNa6/v8eELyqOQ2FsEqeoFYmgv/gJg==}
+ engines: {node: '>=14.6'}
++ deprecated: this version has critical issues, please update to the latest version
+
resolution: {integrity: sha512-DX8nKgqcGwsc0eJSqYt5lwP4DH5FlHnmuWWBRy7X0NcaGR0ZtuyeESgMwTYVEtxmsNGY+qit4QYT/MIYTOTPeA==}
@@@ -9322,10 -9204,10 +9473,14 @@@
resolution: {integrity: sha512-c/c15i26VrJ4IRt5Z89DnIzCGDn9EcebibhAOjw5ibqEHsE1wLUgkPn9RDmNcUKyU87GeaL633nyJ+pplFR2ZQ==}
engines: {node: '>=18'}
+ resolution: {integrity: sha512-hjrNztw/VajQwOLsMNT1cbJiH2muO3OROCHnbehc8eY5JyD2gqz4AcMHPqgaOR59DjgUjYAYLeH699g/eWi2jw==}
+ engines: {node: '>=18'}
+
+ resolution: {integrity: sha512-qoV+HK2yFl/366t2/Cb3+xxPUo5BuMynomoDmiaZBIdbs+0pYbjfZU+twLhGKp4uCZ/+NbtpVepH5bGCxRyy2g==}
+ engines: {node: '>=18'}
+
resolution: {integrity: sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==}
engines: {node: '>= 0.4'}
@@@ -9375,10 -9257,10 +9530,14 @@@
engines: {node: '>=0.4.7'}
hasBin: true
+ resolution: {integrity: sha512-Tz23LR9T9jOGVZm2x1EPdXqwA37G/owYMxRwU0E4miurAtFsPMQ1d2Jc2okUaSjZqAFz2oEn3FLXC5a0a+siyA==}
+ engines: {node: '>=20.0.0'}
+
+ resolution: {integrity: sha512-GZZ9mKe8r646NUAf/zemnGbjYh4Bt8/MqASJY+pSm5ZDtc3YQox+4gsLI7yi1hba6o+eCsGxpHn5+iEVn31/FQ==}
+ engines: {node: '>=20.0.0'}
+
resolution: {integrity: sha512-R3pbpkcIqv2Pm3dUwgjclDRVmWpTJW2DcMzcIhEXEx1oh/CEMObMm3KLmRJOdvhM7o4uQBnwr8pzRK2sJWIqfg==}
engines: {node: '>= 0.4'}
@@@ -11103,11 -10974,16 +11266,6 @@@
engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
hasBin: true
- resolution: {integrity: sha512-7ZtY5KTCNheRGfEFxnedV5zFiORN1+Y1N6zvPTnHQd8ENUvfaDBeuJDZb2bN/oXwXxu3qkTXDzy57W5vAmDTBw==}
- engines: {node: ^14 || ^16 || >=18}
- hasBin: true
-
-- resolution: {integrity: sha512-Ir/+ZpE9fDsNH0hQ3C68uyThDXzYcim2EqcZ8zn8Chtt1iylPT9xXJB0kPCnqzgcEGikO9RxSrh63MsmVCU7Fw==}
-- engines: {node: ^18 || >=20}
-- hasBin: true
--
resolution: {integrity: sha512-ua3NDgISf6jdwezAheMOk4mbE1LXjm1DfMUDMuJf4AqxLFK3ccGpgWizwa5YV7Yz9EpXwEaWoRXSb/BnV0t5dQ==}
engines: {node: ^18 || >=20}
@@@ -12024,22 -11897,22 +12182,38 @@@
peerDependencies:
react: ^19.2.4
+ resolution: {integrity: sha512-shBftH2vaTWK2Bsp7FiL+cevx3xFJlvFxmsDFQSrJc+6twHkP0tv/bGa01VVWzpreUVVwU+3Hev5iFqRg65RwA==}
+ peerDependencies:
+ i18next: '>= 26.0.1'
+ react: '>= 16.8.0'
+ react-dom: '*'
+ react-native: '*'
+ typescript: ^5 || ^6
+ peerDependenciesMeta:
+ react-dom:
+ optional: true
+ react-native:
+ optional: true
+ typescript:
+ optional: true
+
+ resolution: {integrity: sha512-x4xjvUNZ56T+zfXWNedNnCET9Xq1IBYWX7IsWo5cCQ/RT+Rm7GWqt0h9PShFi4IhyMnsdiu1C6Jc4DE+/S3PFQ==}
+ peerDependencies:
+ i18next: '>= 26.0.1'
+ react: '>= 16.8.0'
+ react-dom: '*'
+ react-native: '*'
+ typescript: ^5 || ^6
+ peerDependenciesMeta:
+ react-dom:
+ optional: true
+ react-native:
+ optional: true
+ typescript:
+ optional: true
+
resolution: {integrity: sha512-mmRvA9aKP7zu9kVfP1AX1egX8tFlnE3DDXq92z0JTZezfOpmeQBzr77O1+mTV54OOmn+M2t6c5kFD5VnuFoM7A==}
peerDependencies:
@@@ -12325,9 -12198,9 +12499,12 @@@
resolution: {integrity: sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==}
engines: {iojs: '>=1.0.0', node: '>=0.10.0'}
+ resolution: {integrity: sha512-RayDr1FL3Jglnf6p9xHGJ0U18va96PiuLs/JHnd1cdDOXvC+3lsXKe6ujl7PX0pvnhNW2Tpqnr6PEKpJVO2exw==}
+
+ resolution: {integrity: sha512-9eacArNIgqO2HGWOK+93gJNn+gvdGDVbSq+i2u3Ja9kjiHps0XNLpgYTZTYjKRH91uXy3clGimeGiw4umHG/tg==}
+
resolution: {integrity: sha512-q1b3N5QkRUWUl7iyylaaj3kOpIT0N2i9MqIEQXP73GVsN9cw3fdx8X63cEmWhJGi2PPCF23Ijp7ktmd39rawIA==}
@@@ -16634,7 -16659,7 +16968,7 @@@ snapshots
lodash.debounce: 4.0.8
lodash.throttle: 4.1.1
- nanoid: 5.1.5
- nanoid: 4.0.2
++ nanoid: 5.1.7
open-color: 1.9.1
pako: 2.0.3
perfect-freehand: 1.2.0
@@@ -16662,7 -16687,7 +16996,7 @@@
dependencies:
'@excalidraw/markdown-to-text': 0.1.2
mermaid: 11.14.0
-- nanoid: 5.1.5
++ nanoid: 5.1.7
'@excalidraw/[email protected]': {}
@@@ -17960,23 -18036,7 +18345,23 @@@
'@popperjs/[email protected]': {}
+ dependencies:
+ '@babel/core': 7.29.0
+ '@babel/plugin-transform-react-jsx': 7.27.1(@babel/[email protected])
+ '@babel/plugin-transform-react-jsx-development': 7.27.1(@babel/[email protected])
+ '@rollup/pluginutils': 4.2.1
+ babel-plugin-transform-hook-names: 1.0.2(@babel/[email protected])
+ debug: 4.4.3
+ picocolors: 1.1.1
+ transitivePeerDependencies:
+ - preact
+ - supports-color
+
dependencies:
'@babel/core': 7.29.0
'@babel/plugin-transform-react-jsx': 7.27.1(@babel/[email protected])
@@@ -24690,8 -24753,8 +25082,10 @@@
+
+
dependencies:
define-properties: 1.2.1
@@@ -24750,9 -24813,9 +25144,21 @@@
optionalDependencies:
uglify-js: 3.19.3
+ dependencies:
- '@types/node': 24.12.0
++ '@types/node': 24.12.2
++ '@types/whatwg-mimetype': 3.0.2
++ '@types/ws': 8.18.1
++ entities: 7.0.1
++ whatwg-mimetype: 3.0.0
++ transitivePeerDependencies:
++ - bufferutil
++ - utf-8-validate
++
+ dependencies:
+ '@types/node': 24.12.2
'@types/whatwg-mimetype': 3.0.2
'@types/ws': 8.18.1
entities: 7.0.1
@@@ -26786,8 -26838,10 +27191,6 @@@
-
--
@@@ -27775,17 -27826,17 +28177,28 @@@
react: 19.2.4
scheduler: 0.27.0
+ dependencies:
+ '@babel/runtime': 7.29.2
+ html-parse-stringify: 3.0.1
+ i18next: 26.0.4([email protected])
+ react: 19.2.4
+ use-sync-external-store: 1.6.0([email protected])
+ optionalDependencies:
+ react-dom: 19.2.4([email protected])
+ typescript: 6.0.2
+
+ dependencies:
+ '@babel/runtime': 7.29.2
+ html-parse-stringify: 3.0.1
+ i18next: 26.0.4([email protected])
+ react: 19.2.4
+ use-sync-external-store: 1.6.0([email protected])
+ optionalDependencies:
+ react-dom: 19.2.4([email protected])
+ typescript: 6.0.2
+
dependencies:
detect-it: 3.0.7
@@@ -28159,8 -28210,8 +28572,10 @@@
+
+