Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
Merge remote-tracking branch 'origin/main' into standalone
Elian Doranb52e65278e65
diff --cc CLAUDE.mdindex 5eb93b3a5c,acec08b8ae..747564ec34--- a/CLAUDE.md+++ b/CLAUDE.md@@@ -157,15 -120,14 +157,16 @@@ SQLite via `better-sqlite3`. SQL abstra- Supported languages: English, German, Spanish, French, Romanian, Chinese- **Only add new translation keys to `en/translation.json`** — translations for other languages are managed via Weblate and will be contributed by the community- Third-party components (e.g., mind-map context menu) should use i18next `t()` for their labels, with the English strings added to `en/translation.json` under a dedicated namespace (e.g., `"mind-map"`)+ - When a translated string contains **interpolated components** (e.g. links, note references) whose order may vary across languages, use `<Trans>` from `react-i18next` instead of `t()`. This lets translators reorder components freely (e.g. `"<Note/> in <Parent/>"` vs `"in <Parent/>, <Note/>"`)-### Security Considerations-- Per-note encryption with granular protected sessions-- CSRF protection for API endpoints-- OpenID and TOTP authentication support-- Sanitization of user-generated content+Three inheritance mechanisms:+1. **Standard**: `note.getInheritableAttributes()` walks parent tree+2. **Child prefix**: `child:label` on parent copies to children+3. **Template relation**: `#template=noteNoteId` includes template's inheritable attributes++### Attribute Inheritance+Use `note.getOwnedAttribute()` for direct, `note.getAttribute()` for inherited.### Client-Side API Restrictions- **Do not use `crypto.randomUUID()`** or other Web Crypto APIs that require secure contexts - Trilium can run over HTTP, not just HTTPS- Use `randomString()` from `apps/client/src/services/utils.ts` for generating IDs instead@@@ -175,44 -137,40 +176,63 @@@- Import shared types directly from `@triliumnext/commons` - do not re-export them from app-specific modules- Keep app-specific types (e.g., `LlmProvider` for server, `StreamCallbacks` for client) in their respective apps-## Common Development Tasks+## Important Patterns++- **Protected notes**: Check `note.isContentAvailable()` before accessing content; use `note.getTitleOrProtected()` for safe title access+- **Long operations**: Use `TaskContext` for progress reporting via WebSocket+- **Event system** (`packages/trilium-core/src/services/events.ts`): Events emitted in order (notes → branches → attributes) during load for referential integrity+- **Search**: Expression-based, scoring happens in-memory — cannot add SQL-level LIMIT/OFFSET without losing scoring+- **Widget cleanup**: Unsubscribe from events in `cleanup()`/`doDestroy()` to prevent memory leaks++## Code Style++- 4-space indentation, semicolons always required+- Double quotes (enforced by format config)+- Max line length: 100 characters+- Unix line endings+- Import sorting via `eslint-plugin-simple-import-sort`++## Testing++- **Server tests** (`apps/server/spec/`): Vitest, must run sequentially (shared DB), forks pool, max 6 workers+- **Client tests** (`apps/client/src/`): Vitest with happy-dom environment, can run in parallel+- **E2E tests** (`apps/server-e2e/`): Playwright, Chromium, server started automatically on port 8082+- **ETAPI tests** (`apps/server/spec/etapi/`): External API contract tests++## Documentation-### Adding New Note Types-1. Create widget in `apps/client/src/widgets/type_widgets/`-2. Register in `apps/client/src/services/note_types.ts`-3. Add backend handling in `apps/server/src/services/notes.ts`+- `docs/Script API/` — Auto-generated, never edit directly+- `docs/User Guide/` — Edit via `pnpm edit-docs:edit-docs`, not manually+- `docs/Developer Guide/` and `docs/Release Notes/` — Safe for direct Markdown editing-### Extending Search-- Search expressions handled in `apps/server/src/services/search/`-- Add new search operators in search context files+## Key Entry Points-### Custom CKEditor Plugins-- Create new package in `packages/` following existing plugin structure-- Register in `packages/ckeditor5/src/plugins.ts`+- `apps/server/src/main.ts` — Server startup+- `apps/client/src/desktop.ts` — Client initialization+- `packages/trilium-core/src/becca/becca.ts` — Backend data management+- `apps/client/src/services/froca.ts` — Frontend cache+- `apps/server/src/routes/routes.ts` — API route registration+- `packages/trilium-core/src/services/sql/sql.ts` — Database abstraction+ ### Adding New LLM Tools+ Tools are defined using `defineTools()` in `apps/server/src/services/llm/tools/` and automatically registered for both the LLM chat and MCP server.++ 1. Add the tool definition in the appropriate module (`note_tools.ts`, `attribute_tools.ts`, `attachment_tools.ts`, `hierarchy_tools.ts`) or create a new module+ 2. Each tool needs: `description`, `inputSchema` (Zod), `execute` function, and optionally `mutates: true` for write operations+ 3. If creating a new module, wrap tools in `defineTools({...})` and add the registry to `allToolRegistries` in `tools/index.ts`+ 4. Add a client-side friendly name in `apps/client/src/translations/en/translation.json` under `llm.tools.<tool_name>` — use **imperative tense** (e.g. "Search notes", "Create note", "Get attributes"), not present continuous+ 5. Use ETAPI (`apps/server/src/etapi/`) as inspiration for what fields to expose, but **do not import ETAPI mappers** — inline the field mappings directly in the tool so the LLM layer stays decoupled from the API layer++ ### Updating PDF.js+ 1. Update `pdfjs-dist` version in `packages/pdfjs-viewer/package.json`+ 2. Run `npx tsx scripts/update-viewer.ts` from that directory+ 3. Run `pnpm build` to verify success+ 4. Commit all changes including updated viewer files++ ### Database Migrations+ - Add migration scripts in `apps/server/src/migrations/`+ - Update schema in `apps/server/src/assets/db/schema.sql`+### Server-Side Static Assets- Static assets (templates, SQL, translations, etc.) go in `apps/server/src/assets/`- Access them at runtime via `RESOURCE_DIR` from `apps/server/src/services/resource_dir.ts` (e.g. `path.join(RESOURCE_DIR, "llm", "skills", "file.md")`)diff --cc apps/client/package.jsonindex 587faf4e7a,4b48c04d14..4be0939e81--- a/apps/client/package.json+++ b/apps/client/package.json@@@ -90,6 -90,6 +90,6 @@@"happy-dom": "20.8.9","lightningcss": "1.32.0","script-loader": "0.7.2",- "vite-plugin-static-copy": "3.4.0"+ "vite-plugin-static-copy": "4.0.0"}-}+}diff --cc apps/server/package.jsonindex ee2c2d1269,089390b0a6..c603d92c33--- a/apps/server/package.json+++ b/apps/server/package.json@@@ -31,11 -31,16 +31,14 @@@},"dependencies": {"@ai-sdk/anthropic": "3.0.64",- "@ai-sdk/google": "3.0.54",+ "@ai-sdk/google": "3.0.55","@ai-sdk/openai": "3.0.49",+ "@modelcontextprotocol/sdk": "^1.12.1","ai": "6.0.142","better-sqlite3": "12.8.0",- "html-to-text": "9.0.5"+ "html-to-text": "9.0.5",+ "js-yaml": "4.1.1",- "node-html-parser": "7.1.0",- "sucrase": "3.35.1",+ "unpdf": "1.4.0"},"devDependencies": {"@braintree/sanitize-url": "7.1.2",@@@ -56,8 -62,12 +59,9 @@@"@types/fs-extra": "11.0.4","@types/html": "1.0.4","@types/ini": "4.1.1",+ "@types/js-yaml": "4.0.9",- "@types/mime-types": "3.0.1","@types/multer": "2.1.0","@types/safe-compare": "1.1.2",- "@types/sanitize-html": "2.16.1",- "@types/sax": "1.2.7","@types/serve-favicon": "2.5.7","@types/serve-static": "2.2.0","@types/stream-throttle": "0.1.4",@@@ -103,13 -116,18 +107,14 @@@"jimp": "1.6.0","lorem-ipsum": "2.0.8","marked": "17.0.5",- "mime-types": "3.0.2","multer": "2.1.1","normalize-strings": "1.1.1",+ "officeparser": "6.0.7","rand-token": "1.0.1","safe-compare": "1.1.4",- "sanitize-filename": "1.6.4",- "sanitize-html": "2.17.2","sax": "1.6.0","serve-favicon": "2.5.1",- "stream-throttle": "0.1.3",- "strip-bom": "5.0.0",+ "stream-throttle": "0.1.3","striptags": "3.2.0","supertest": "7.2.2","swagger-jsdoc": "6.2.8",@@@ -116,8 -135,10 +122,8 @@@"time2fa": "1.4.2","tmp": "0.2.5","turnish": "1.8.0",- "unescape": "1.0.1","vite": "8.0.3",- "ws": "8.20.0","xml2js": "0.6.2",- "yauzl": "3.2.1"+ "yauzl": "3.3.0"}}diff --cc apps/server/src/app.tsindex 838cbb0153,ffd33600dd..039a1fcf0a--- a/apps/server/src/app.ts+++ b/apps/server/src/app.ts@@@ -14,8 -14,10 +14,9 @@@ import favicon from "serve-favicon"import assets from "./routes/assets.js";import custom from "./routes/custom.js";import error_handlers from "./routes/error_handlers.js";+ import mcpRoutes from "./routes/mcp.js";import routes from "./routes/routes.js";import config from "./services/config.js";-import { startScheduledCleanup } from "./services/erase.js";import log from "./services/log.js";import openID from "./services/open_id.js";import { RESOURCE_DIR } from "./services/resource_dir.js";diff --cc apps/server/src/assets/translations/ru/server.jsonindex 8aeb50d3bb,cf1b01bcbb..401bb4f663--- a/apps/server/src/assets/translations/ru/server.json+++ b/apps/server/src/assets/translations/ru/server.json@@@ -309,8 -312,39 +312,9 @@@"button": "Установить пароль","description": "Прежде чем начать использовать Trilium через веб-браузер, вам необходимо установить пароль. Этот пароль будет использоваться для входа."},- "setup": {- "next": "Далее",- "title": "Настройка",- "heading": "Настройка Trilium",- "new-document": "Я новый пользователь и хочу создать новый документ Trilium для своих заметок",- "sync-from-desktop": "У меня уже есть настольное приложение, и я хочу настроить синхронизацию с ним",- "sync-from-server": "У меня уже есть сервер, и я хочу настроить синхронизацию с ним",- "init-in-progress": "Идет инициализация документа",- "redirecting": "Вскоре вы будете перенаправлены на страницу приложения."- },- "setup_sync-from-server": {- "server-host-placeholder": "https://<hostname>:<port>",- "proxy-server-placeholder": "https://<hostname>:<port>",- "password": "Пароль",- "password-placeholder": "Пароль",- "back": "Назад",- "finish-setup": "Завершение настройки",- "heading": "Синхронизация с сервера",- "instructions": "Введите адрес сервера Trilium и учётные данные ниже. Документ Trilium будет полностью загружен с сервера и синхронизирован с ним. В зависимости от размера документа и скорости вашего соединения, это может занять некоторое время.",- "server-host": "Адрес сервера Trilium",- "proxy-server": "Прокси-сервер (необязательно)",- "note": "Заметка:",- "proxy-instruction": "Если оставить настройки прокси-сервера пустыми, будет использоваться системный прокси-сервер (применимо только к настольному приложению)"- },- "setup_sync-in-progress": {- "outstanding-items-default": "Н/Д",- "heading": "Синхронизация в процессе",- "successful": "Синхронизация настроена. Первоначальная синхронизация займёт некоторое время. После её завершения вы будете перенаправлены на страницу входа.",- "outstanding-items": "Оставшиеся элементы синхронизации:"- },"special_notes": {- "search_prefix": "Поиск:"+ "search_prefix": "Поиск:",+ "llm_chat_prefix": "Чат:"},"notes": {"duplicate-note-suffix": "(дубликат)",diff --cc apps/server/src/routes/routes.tsindex 43f748b70c,775a36e833..bcc86eb8e7--- a/apps/server/src/routes/routes.ts+++ b/apps/server/src/routes/routes.ts@@@ -18,19 -17,46 +18,20 @@@ import auth from "../services/auth.js"import openID from '../services/open_id.js';import { isElectron } from "../services/utils.js";import shareRoutes from "../share/routes.js";-import appInfoRoute from "./api/app_info.js";-import attachmentsApiRoute from "./api/attachments.js";-import attributesRoute from "./api/attributes.js";-import autocompleteApiRoute from "./api/autocomplete.js";import backendLogRoute from "./api/backend_log.js";-import branchesApiRoute from "./api/branches.js";-import bulkActionRoute from "./api/bulk_action.js";import clipperRoute from "./api/clipper.js";-import cloningApiRoute from "./api/cloning.js";import databaseRoute from "./api/database.js";import etapiTokensApiRoutes from "./api/etapi_tokens.js";-import exportRoute from "./api/export.js";import filesRoute from "./api/files.js";import fontsRoute from "./api/fonts.js";-import imageRoute from "./api/image.js";-import importRoute from "./api/import.js";-import keysRoute from "./api/keys.js";import llmChatRoute from "./api/llm_chat.js";+import llmSpecialNotesRoute from "./api/llm_special_notes.js";import loginApiRoute from "./api/login.js";import metricsRoute from "./api/metrics.js";-import noteMapRoute from "./api/note_map.js";-import notesApiRoute from "./api/notes.js";+ import ocrRoute from "./api/ocr.js";-import optionsApiRoute from "./api/options.js";-import otherRoute from "./api/other.js";import passwordApiRoute from "./api/password.js";-import recentChangesApiRoute from "./api/recent_changes.js";-import recentNotesRoute from "./api/recent_notes.js";import recoveryCodes from './api/recovery_codes.js';-import relationMapApiRoute from "./api/relation-map.js";-import revisionsApiRoute from "./api/revisions.js";-import scriptRoute from "./api/script.js";-import searchRoute from "./api/search.js";import senderRoute from "./api/sender.js";-import setupApiRoute from "./api/setup.js";-import similarNotesRoute from "./api/similar_notes.js";-import specialNotesRoute from "./api/special_notes.js";-import sqlRoute from "./api/sql.js";-import statsRoute from "./api/stats.js";-import syncApiRoute from "./api/sync.js";import systemInfoRoute from "./api/system_info.js";import totp from './api/totp.js';// API routesdiff --cc apps/server/src/services/handlers.tsindex 0562603fbe,cf96b0a6d1..16b829c47c--- a/apps/server/src/services/handlers.ts+++ b/apps/server/src/services/handlers.ts@@@ -1,2 -1,280 +1,42 @@@- import { handlers } from "@triliumnext/core";-import eventService from "./events.js";-import scriptService from "./script.js";-import treeService from "./tree.js";-import noteService from "./notes.js";-import becca from "../becca/becca.js";-import BAttribute from "../becca/entities/battribute.js";-import hiddenSubtreeService from "./hidden_subtree.js";-import oneTimeTimer from "./one_time_timer.js";-import ocrService from "./ocr/ocr_service.js";-import optionService from "./options.js";-import log from "./log.js";-import type BNote from "../becca/entities/bnote.js";-import type AbstractBeccaEntity from "../becca/entities/abstract_becca_entity.js";-import type { DefinitionObject } from "./promoted_attribute_definition_interface.js";--type Handler = (definition: DefinitionObject, note: BNote, targetNote: BNote) => void;--function runAttachedRelations(note: BNote, relationName: string, originEntity: AbstractBeccaEntity<any>) {- if (!note) {- return;- }-- // the same script note can get here with multiple ways, but execute only once- const notesToRun = new Set(- note- .getRelations(relationName)- .map((relation) => relation.getTargetNote())- .filter((note) => !!note) as BNote[]- );-- for (const noteToRun of notesToRun) {- scriptService.executeNoteNoException(noteToRun, { originEntity });- }-}--eventService.subscribe(eventService.NOTE_TITLE_CHANGED, (note) => {- runAttachedRelations(note, "runOnNoteTitleChange", note);-- if (!note.isRoot()) {- const noteFromCache = becca.notes[note.noteId];-- if (!noteFromCache) {- return;- }-- for (const parentNote of noteFromCache.parents) {- if (parentNote.hasLabel("sorted")) {- treeService.sortNotesIfNeeded(parentNote.noteId);- }- }- }-});--eventService.subscribe([eventService.ENTITY_CHANGED, eventService.ENTITY_DELETED], ({ entityName, entity }) => {- if (entityName === "attributes") {- runAttachedRelations(entity.getNote(), "runOnAttributeChange", entity);-- if (entity.type === "label" && ["sorted", "sortDirection", "sortFoldersFirst", "sortNatural", "sortLocale"].includes(entity.name)) {- handleSortedAttribute(entity);- } else if (entity.type === "label") {- handleMaybeSortingLabel(entity);- }- } else if (entityName === "notes") {- // ENTITY_DELETED won't trigger anything since all branches/attributes are already deleted at this point- runAttachedRelations(entity, "runOnNoteChange", entity);- }-});--eventService.subscribe(eventService.ENTITY_CHANGED, ({ entityName, entity }) => {- if (entityName === "branches") {- const parentNote = becca.getNote(entity.parentNoteId);-- if (parentNote?.hasLabel("sorted")) {- treeService.sortNotesIfNeeded(parentNote.noteId);- }-- const childNote = becca.getNote(entity.noteId);-- if (childNote) {- runAttachedRelations(childNote, "runOnBranchChange", entity);- }- }-});--eventService.subscribe(eventService.NOTE_CONTENT_CHANGE, ({ entity }) => {- runAttachedRelations(entity, "runOnNoteContentChange", entity);-});--eventService.subscribe(eventService.ENTITY_CREATED, ({ entityName, entity }) => {- if (entityName === "attributes") {- runAttachedRelations(entity.getNote(), "runOnAttributeCreation", entity);-- if (entity.type === "relation" && entity.name === "template") {- const note = becca.getNote(entity.noteId);- if (!note) {- return;- }-- const templateNote = becca.getNote(entity.value);-- if (!templateNote) {- return;- }-- const content = note.getContent();-- if (- ["text", "code", "mermaid", "canvas", "relationMap", "mindMap", "webView"].includes(note.type) &&- typeof content === "string" &&- // if the note has already content we're not going to overwrite it with template's one- (!content || content.trim().length === 0) &&- templateNote.hasStringContent()- ) {- const templateNoteContent = templateNote.getContent();-- if (templateNoteContent) {- note.setContent(templateNoteContent);++import { events, getLog, handlers, options as optionService } from "@triliumnext/core";++++import ocrService from "./ocr/ocr_service";+export default handlers;++++export function registerOcrHandlers() {++ events.subscribe(events.ENTITY_CREATED, ({ entityName, entity }) => {++ switch (entityName) {++ case "notes": {++ // Note: OCR processing for images is now handled in image.ts during image processing++ // OCR processing for files remains here since they don't go through image processing++ if (entity.type === 'file' && optionService.getOptionBool("ocrAutoProcessImages")) {++ autoProcessOCR(entity.mime, () => ocrService.processNoteOCR(entity.noteId), `file note ${entity.noteId}`);+ }-- note.type = templateNote.type;- note.mime = templateNote.mime;- note.save();++ break;+ }-- // we'll copy the children notes only if there's none so far- // this protects against e.g. multiple assignment of template relation resulting in having multiple copies of the subtree- if (note.getChildNotes().length === 0 && !note.isDescendantOfNote(templateNote.noteId)) {- noteService.duplicateSubtreeWithoutRoot(templateNote.noteId, note.noteId);++ case "attachments": {++ // Image attachments are handled in image.ts after async image processing sets the real MIME type.++ // Only handle non-image (file) attachments here.++ if (entity.role === "file" && optionService.getOptionBool("ocrAutoProcessImages")) {++ autoProcessOCR(entity.mime, () => ocrService.processAttachmentOCR(entity.attachmentId), `attachment ${entity.attachmentId}`);++ }++ break;+ }- } else if (entity.type === "label" && ["sorted", "sortDirection", "sortFoldersFirst", "sortNatural", "sortLocale"].includes(entity.name)) {- handleSortedAttribute(entity);- } else if (entity.type === "label") {- handleMaybeSortingLabel(entity);- }- } else if (entityName === "branches") {- runAttachedRelations(entity.getNote(), "runOnBranchCreation", entity);-- if (entity.parentNote?.hasLabel("sorted")) {- treeService.sortNotesIfNeeded(entity.parentNoteId);- }- } else if (entityName === "notes") {- runAttachedRelations(entity, "runOnNoteCreation", entity);-- // Note: OCR processing for images is now handled in image.ts during image processing- // OCR processing for files remains here since they don't go through image processing- if (entity.type === 'file' && optionService.getOptionBool("ocrAutoProcessImages")) {- autoProcessOCR(entity.mime, () => ocrService.processNoteOCR(entity.noteId), `file note ${entity.noteId}`);- }- } else if (entityName === "attachments") {- // Image attachments are handled in image.ts after async image processing sets the real MIME type.- // Only handle non-image (file) attachments here.- if (entity.role === "file" && optionService.getOptionBool("ocrAutoProcessImages")) {- autoProcessOCR(entity.mime, () => ocrService.processAttachmentOCR(entity.attachmentId), `attachment ${entity.attachmentId}`);+ }- }-});++ });++}++ function autoProcessOCR(mime: string, process: () => Promise<unknown>, entityDescription: string) {+ const supportedMimeTypes = ocrService.getAllSupportedMimeTypes();+++ const log = getLog();+ if (mime && supportedMimeTypes.includes(mime)) {+ process().then(result => {+ if (result) {+ log.info(`Automatically processed OCR for ${entityDescription} with MIME type ${mime}`);+ }+ }).catch(error => {+ log.error(`Failed to automatically process OCR for ${entityDescription}: ${error}`);+ });+ }+ }--eventService.subscribe(eventService.CHILD_NOTE_CREATED, ({ parentNote, childNote }) => {- runAttachedRelations(parentNote, "runOnChildNoteCreation", childNote);-});--function processInverseRelations(entityName: string, entity: BAttribute, handler: Handler) {- if (entityName === "attributes" && entity.type === "relation") {- const note = entity.getNote();- const relDefinitions = note.getLabels(`relation:${entity.name}`);-- for (const relDefinition of relDefinitions) {- const definition = relDefinition.getDefinition();-- if (definition.inverseRelation && definition.inverseRelation.trim()) {- const targetNote = entity.getTargetNote();-- if (targetNote) {- handler(definition, note, targetNote);- }- }- }- }-}--function handleSortedAttribute(entity: BAttribute) {- treeService.sortNotesIfNeeded(entity.noteId);-- if (entity.isInheritable) {- const note = becca.notes[entity.noteId];-- if (note) {- for (const noteId of note.getSubtreeNoteIds()) {- treeService.sortNotesIfNeeded(noteId);- }- }- }-}--function handleMaybeSortingLabel(entity: BAttribute) {- // check if this label is used for sorting, if yes force re-sort- const note = becca.notes[entity.noteId];-- // this will not work on deleted notes, but in that case we don't really need to re-sort- if (note) {- for (const parentNote of note.getParentNotes()) {- const sorted = parentNote.getLabelValue("sorted");- if (sorted === null) {- // checking specifically for null since that means the label doesn't exist- // empty valued "sorted" is still valid- continue;- }-- if (- sorted.includes(entity.name) || // hacky check if this label is used in the sort- entity.name === "top" ||- entity.name === "bottom"- ) {- treeService.sortNotesIfNeeded(parentNote.noteId);- }- }- }-}--eventService.subscribe(eventService.ENTITY_CHANGED, ({ entityName, entity }) => {- processInverseRelations(entityName, entity, (definition, note, targetNote) => {- // we need to make sure that also target's inverse attribute exists and if not, then create it- // inverse attribute has to target our note as well- const hasInverseAttribute = targetNote.getRelations(definition.inverseRelation).some((attr) => attr.value === note.noteId);-- if (!hasInverseAttribute) {- new BAttribute({- noteId: targetNote.noteId,- type: "relation",- name: definition.inverseRelation || "",- value: note.noteId,- isInheritable: entity.isInheritable- }).save();-- // becca will not be updated before we'll check from the other side which would create infinite relation creation (#2269)- targetNote.invalidateThisCache();- }- });-});--eventService.subscribe(eventService.ENTITY_DELETED, ({ entityName, entity }) => {- processInverseRelations(entityName, entity, (definition: DefinitionObject, note: BNote, targetNote: BNote) => {- // if one inverse attribute is deleted, then the other should be deleted as well- const relations = targetNote.getOwnedRelations(definition.inverseRelation);-- for (const relation of relations) {- if (relation.value === note.noteId) {- relation.markAsDeleted();- }- }- });-- if (entityName === "branches") {- runAttachedRelations(entity.getNote(), "runOnBranchDeletion", entity);- }-- if (entityName === "notes" && entity.noteId.startsWith("_")) {- // "named" note has been deleted, we will probably need to rebuild the hidden subtree- // scheduling so that bulk deletes won't trigger so many checks- oneTimeTimer.scheduleExecution("hidden-subtree-check", 1000, () => hiddenSubtreeService.checkHiddenSubtree());- }-});--export default {- runAttachedRelations-};diff --cc apps/server/src/services/image.tsindex e57811f748,243b5f9334..743d40acdc--- a/apps/server/src/services/image.ts+++ b/apps/server/src/services/image.ts@@@ -1,6 -1,3 +1,4 @@@--+import { sanitize } from "@triliumnext/core";import imageType from "image-type";import isAnimated from "is-animated";import isSvg from "is-svg";@@@ -8,8 -5,10 +6,9 @@@ import { Jimp } from "jimp"import sanitizeFilename from "sanitize-filename";import becca from "../becca/becca.js";-import htmlSanitizer from "./html_sanitizer.js";import log from "./log.js";import noteService from "./notes.js";+ import ocrService from "./ocr/ocr_service.js";import optionService from "./options.js";import protectedSessionService from "./protected_session.js";import sql from "./sql.js";diff --cc apps/server/src/www.tsindex 67ab16b9e4,130d3a380a..8581a06fcc--- a/apps/server/src/www.ts+++ b/apps/server/src/www.ts@@@ -4,15 -2,16 +4,16 @@@ import fs from "fs"import http from "http";import https from "https";import tmp from "tmp";++import buildApp from "./app.js";+import appInfo from "./services/app_info.js";import config from "./services/config.js";++import { registerOcrHandlers } from "./services/handlers.js";+import host from "./services/host.js";import log from "./services/log.js";-import appInfo from "./services/app_info.js";-import ws from "./services/ws.js";-import utils, { formatSize, formatUtcTime } from "./services/utils.js";import port from "./services/port.js";-import host from "./services/host.js";-import buildApp from "./app.js";-import type { Express } from "express";import { getDbSize } from "./services/sql_init.js";+import WebSocketMessagingProvider from "./services/ws_messaging_provider.js";const MINIMUM_NODE_VERSION = "20.0.0";@@@ -68,6 -64,6 +69,8 @@@ export default async function startTrilconst electronRouting = await import("./routes/electron.js");electronRouting.default(app);}++++ registerOcrHandlers();}async function displayStartupMessage() {diff --cc packages/commons/src/lib/rows.tsindex 92baf78a92,200b567023..15b7ed5ca5--- a/packages/commons/src/lib/rows.ts+++ b/packages/commons/src/lib/rows.ts@@@ -70,8 -70,9 +70,9 @@@ export interface EtapiTokenRowexport interface BlobRow {blobId: string;- content: string | Buffer;+ content: string | Uint8Array;contentLength: number;+ textRepresentation?: string | null;dateModified: string;utcDateModified: string;}diff --cc packages/trilium-core/src/becca/entities/bblob.tsindex a3ec261382,839eca153a..7bb05e774f--- a/packages/trilium-core/src/becca/entities/bblob.ts+++ b/packages/trilium-core/src/becca/entities/bblob.ts@@@ -13,8 -13,9 +13,9 @@@ class BBlob extends AbstractBeccaEntityreturn ["blobId", "content"];}- content!: string | Buffer;+ content!: string | Uint8Array;contentLength!: number;+ textRepresentation?: string | null;constructor(row: BlobRow) {super();diff --cc packages/trilium-core/src/services/app_info.tsindex 5a8b19e178,0000000000..891649a181mode 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";+- const APP_DB_VERSION = 235;++const APP_DB_VERSION = 236;+const SYNC_VERSION = 37;+const CLIPPER_PROTOCOL_VERSION = "1.0";++const appInfo: AppInfo = {+ appVersion: packageJson.version,+ dbVersion: APP_DB_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/blob.tsindex 09e72ee951,fa8bbd2b61..caa4952121--- a/packages/trilium-core/src/services/blob.ts+++ b/packages/trilium-core/src/services/blob.ts@@@ -38,21 -37,21 +38,21 @@@ function processContent(content: Uint8A}if (isStringContent) {- return content === null ? "" : content.toString("utf-8");- } else {- // see https://github.com/zadam/trilium/issues/3523- // IIRC a zero-sized buffer can be returned as null from the database- if (content === null) {- // this will force de/encryption- content = Buffer.alloc(0);- }-- return content;+ if (content === null) return "";+ return decodeUtf8(content);}+ // see https://github.com/zadam/trilium/issues/3523+ // IIRC a zero-sized buffer can be returned as null from the database+ if (content === null) {+ // this will force de/encryption+ content = new Uint8Array(0);+ }++ return content;}- function calculateContentHash({ blobId, content }: Pick<BlobRow, "blobId" | "content">) {- return hash(`${blobId}|${content.toString()}`);-function calculateContentHash({ blobId, content, textRepresentation }: Blob) {++function calculateContentHash({ blobId, content, textRepresentation }: Pick<BlobRow, "blobId" | "content" | "textRepresentation">) {+ return hash(`${blobId}|${content.toString()}|${textRepresentation ?? ""}`);}export default {diff --cc packages/trilium-core/src/services/entity_changes.tsindex c2f6ebb1f2,0000000000..7ad3c75f76mode 100644,000000..100644--- a/packages/trilium-core/src/services/entity_changes.ts+++ b/packages/trilium-core/src/services/entity_changes.ts@@@ -1,211 -1,0 +1,211 @@@+import type { BlobRow, EntityChange } from "@triliumnext/commons";++import becca from "../becca/becca.js";+import dateUtils from "./utils/date.js";+import { getLog } from "./log.js";+import { randomString } from "./utils/index.js";+import { getSql } from "./sql/index.js";+import * as cls from "./context.js";+import events from "./events.js";+import blobService from "./blob.js";+import getInstanceId from "./instance_id.js";++let maxEntityChangeId = 0;++function putEntityChangeWithInstanceId(origEntityChange: EntityChange, instanceId: string) {+ const ec = { ...origEntityChange, instanceId };++ putEntityChange(ec);+}++function putEntityChangeWithForcedChange(origEntityChange: EntityChange) {+ const ec = { ...origEntityChange, changeId: null };++ putEntityChange(ec);+}++function putEntityChange(origEntityChange: EntityChange) {+ const ec = { ...origEntityChange };++ delete ec.id;++ if (!ec.changeId) {+ ec.changeId = randomString(12);+ }++ ec.componentId = ec.componentId || cls.getComponentId() || "NA"; // NA = not available+ ec.instanceId = ec.instanceId || getInstanceId();+ ec.isSynced = ec.isSynced ? 1 : 0;+ ec.isErased = ec.isErased ? 1 : 0;+ ec.id = getSql().replace("entity_changes", ec);++ if (ec.id) {+ maxEntityChangeId = Math.max(maxEntityChangeId, ec.id);+ }++ cls.putEntityChange(ec);+}++function putNoteReorderingEntityChange(parentNoteId: string, componentId?: string) {+ putEntityChange({+ entityName: "note_reordering",+ entityId: parentNoteId,+ hash: "N/A",+ isErased: false,+ utcDateChanged: dateUtils.utcNowDateTime(),+ isSynced: true,+ componentId,+ instanceId: getInstanceId()+ });++ events.emit(events.ENTITY_CHANGED, {+ entityName: "note_reordering",+ entity: getSql().getMap(/*sql*/`SELECT branchId, notePosition FROM branches WHERE isDeleted = 0 AND parentNoteId = ?`, [parentNoteId])+ });+}++function putEntityChangeForOtherInstances(ec: EntityChange) {+ putEntityChange({+ ...ec,+ changeId: null,+ instanceId: null+ });+}++function addEntityChangesForSector(entityName: string, sector: string) {+ const sql = getSql();+ const entityChanges = sql.getRows<EntityChange>(/*sql*/`SELECT * FROM entity_changes WHERE entityName = ? AND SUBSTR(entityId, 1, 1) = ?`, [entityName, sector]);++ let entitiesInserted = entityChanges.length;++ sql.transactional(() => {+ if (entityName === "blobs") {+ entitiesInserted += addEntityChangesForDependingEntity(sector, "notes", "noteId");+ entitiesInserted += addEntityChangesForDependingEntity(sector, "attachments", "attachmentId");+ entitiesInserted += addEntityChangesForDependingEntity(sector, "revisions", "revisionId");+ }++ for (const ec of entityChanges) {+ putEntityChangeWithForcedChange(ec);+ }+ });++ getLog().info(`Added sector ${sector} of '${entityName}' (${entitiesInserted} entities) to the sync queue.`);+}++function addEntityChangesForDependingEntity(sector: string, tableName: string, primaryKeyColumn: string) {+ // problem in blobs might be caused by problem in entity referencing the blob+ const dependingEntityChanges = getSql().getRows<EntityChange>(+ `+ SELECT dep_change.*+ FROM entity_changes orig_sector+ JOIN ${tableName} ON ${tableName}.blobId = orig_sector.entityId+ JOIN entity_changes dep_change ON dep_change.entityName = '${tableName}' AND dep_change.entityId = ${tableName}.${primaryKeyColumn}+ WHERE orig_sector.entityName = 'blobs' AND SUBSTR(orig_sector.entityId, 1, 1) = ?`,+ [sector]+ );++ for (const ec of dependingEntityChanges) {+ putEntityChangeWithForcedChange(ec);+ }++ return dependingEntityChanges.length;+}++function cleanupEntityChangesForMissingEntities(entityName: string, entityPrimaryKey: string) {+ getSql().execute(`+ DELETE+ FROM entity_changes+ WHERE+ isErased = 0+ AND entityName = '${entityName}'+ AND entityId NOT IN (SELECT ${entityPrimaryKey} FROM ${entityName})`);+}++function fillEntityChanges(entityName: string, entityPrimaryKey: string, condition = "") {+ cleanupEntityChangesForMissingEntities(entityName, entityPrimaryKey);++ const sql = getSql();+ sql.transactional(() => {+ const entityIds = sql.getColumn<string>(/*sql*/`SELECT ${entityPrimaryKey} FROM ${entityName} ${condition}`);++ let createdCount = 0;++ for (const entityId of entityIds) {+ const existingRows = sql.getValue("SELECT COUNT(1) FROM entity_changes WHERE entityName = ? AND entityId = ?", [entityName, entityId]);++ if (existingRows !== 0) {+ // we don't want to replace existing entities (which would effectively cause full resync)+ continue;+ }++ createdCount++;++ const ec: Partial<EntityChange> = {+ entityName,+ entityId,+ isErased: false+ };++ if (entityName === "blobs") {- const blob = sql.getRow<Pick<BlobRow, "blobId" | "content" | "utcDateModified">>("SELECT blobId, content, utcDateModified FROM blobs WHERE blobId = ?", [entityId]);++ const blob = sql.getRow<Pick<BlobRow, "blobId" | "content" | "utcDateModified" | "textRepresentation">>("SELECT blobId, content, textRepresentation, utcDateModified FROM blobs WHERE blobId = ?", [entityId]);+ ec.hash = blobService.calculateContentHash(blob);+ ec.utcDateChanged = blob.utcDateModified;+ ec.isSynced = true; // blobs are always synced+ } else {+ const entity = becca.getEntity(entityName, entityId);++ if (entity) {+ ec.hash = entity.generateHash();+ ec.utcDateChanged = entity.getUtcDateChanged() || dateUtils.utcNowDateTime();+ ec.isSynced = entityName !== "options" || !!entity.isSynced;+ } else {+ // entity might be null (not present in becca) when it's deleted+ // this will produce different hash value than when entity is being deleted since then+ // all normal hashed attributes are being used. Sync should recover from that, though.+ ec.hash = "deleted";+ ec.utcDateChanged = dateUtils.utcNowDateTime();+ ec.isSynced = true; // deletable (the ones with isDeleted) entities are synced+ }+ }++ putEntityChange(ec as EntityChange);+ }++ if (createdCount > 0) {+ getLog().info(`Created ${createdCount} missing entity changes for entity '${entityName}'.`);+ }+ });+}++function fillAllEntityChanges() {+ const sql = getSql();+ sql.transactional(() => {+ sql.execute("DELETE FROM entity_changes WHERE isErased = 0");++ fillEntityChanges("notes", "noteId");+ fillEntityChanges("branches", "branchId");+ fillEntityChanges("revisions", "revisionId");+ fillEntityChanges("attachments", "attachmentId");+ fillEntityChanges("blobs", "blobId");+ fillEntityChanges("attributes", "attributeId");+ fillEntityChanges("etapi_tokens", "etapiTokenId");+ fillEntityChanges("options", "name", "WHERE isSynced = 1");+ });+}++function recalculateMaxEntityChangeId() {+ maxEntityChangeId = getSql().getValue<number>("SELECT COALESCE(MAX(id), 0) FROM entity_changes");+}++export default {+ putNoteReorderingEntityChange,+ putEntityChangeForOtherInstances,+ putEntityChangeWithForcedChange,+ putEntityChange,+ putEntityChangeWithInstanceId,+ fillAllEntityChanges,+ addEntityChangesForSector,+ getMaxEntityChangeId: () => maxEntityChangeId,+ recalculateMaxEntityChangeId+};diff --cc packages/trilium-core/src/services/handlers.tsindex ab2a345244,0000000000..f32bf6ddd0mode 100644,000000..100644--- a/packages/trilium-core/src/services/handlers.ts+++ b/packages/trilium-core/src/services/handlers.ts@@@ -1,252 -1,0 +1,251 @@@- import { DefinitionObject } from "@triliumnext/commons";-++import eventService from "./events.js";++import scriptService from "./script.js";++import treeService from "./tree.js";++import noteService from "./notes.js";+import becca from "../becca/becca.js";+import BAttribute from "../becca/entities/battribute.js";- import type BNote from "../becca/entities/bnote.js";+import hiddenSubtreeService from "./hidden_subtree.js";- import noteService from "./notes.js";+import oneTimeTimer from "./one_time_timer.js";- import scriptService from "./script.js";- import treeService from "./tree.js";- import eventService from "./events.js";- import AbstractBeccaEntity from "../becca/entities/abstract_becca_entity.js";++import type BNote from "../becca/entities/bnote.js";++import type AbstractBeccaEntity from "../becca/entities/abstract_becca_entity.js";++import type { DefinitionObject } from "./promoted_attribute_definition_interface.js";++type Handler = (definition: DefinitionObject, note: BNote, targetNote: BNote) => void;++function runAttachedRelations(note: BNote, relationName: string, originEntity: AbstractBeccaEntity<any>) {+ if (!note) {+ return;+ }++ // the same script note can get here with multiple ways, but execute only once+ const notesToRun = new Set(+ note+ .getRelations(relationName)+ .map((relation) => relation.getTargetNote())+ .filter((note) => !!note) as BNote[]+ );++ for (const noteToRun of notesToRun) {+ scriptService.executeNoteNoException(noteToRun, { originEntity });+ }+}++eventService.subscribe(eventService.NOTE_TITLE_CHANGED, (note) => {+ runAttachedRelations(note, "runOnNoteTitleChange", note);++ if (!note.isRoot()) {+ const noteFromCache = becca.notes[note.noteId];++ if (!noteFromCache) {+ return;+ }++ for (const parentNote of noteFromCache.parents) {+ if (parentNote.hasLabel("sorted")) {+ treeService.sortNotesIfNeeded(parentNote.noteId);+ }+ }+ }+});++eventService.subscribe([eventService.ENTITY_CHANGED, eventService.ENTITY_DELETED], ({ entityName, entity }) => {+ if (entityName === "attributes") {+ runAttachedRelations(entity.getNote(), "runOnAttributeChange", entity);++ if (entity.type === "label" && ["sorted", "sortDirection", "sortFoldersFirst", "sortNatural", "sortLocale"].includes(entity.name)) {+ handleSortedAttribute(entity);+ } else if (entity.type === "label") {+ handleMaybeSortingLabel(entity);+ }+ } else if (entityName === "notes") {+ // ENTITY_DELETED won't trigger anything since all branches/attributes are already deleted at this point+ runAttachedRelations(entity, "runOnNoteChange", entity);+ }+});++eventService.subscribe(eventService.ENTITY_CHANGED, ({ entityName, entity }) => {+ if (entityName === "branches") {+ const parentNote = becca.getNote(entity.parentNoteId);++ if (parentNote?.hasLabel("sorted")) {+ treeService.sortNotesIfNeeded(parentNote.noteId);+ }++ const childNote = becca.getNote(entity.noteId);++ if (childNote) {+ runAttachedRelations(childNote, "runOnBranchChange", entity);+ }+ }+});++eventService.subscribe(eventService.NOTE_CONTENT_CHANGE, ({ entity }) => {+ runAttachedRelations(entity, "runOnNoteContentChange", entity);+});++eventService.subscribe(eventService.ENTITY_CREATED, ({ entityName, entity }) => {+ if (entityName === "attributes") {+ runAttachedRelations(entity.getNote(), "runOnAttributeCreation", entity);++ if (entity.type === "relation" && entity.name === "template") {+ const note = becca.getNote(entity.noteId);+ if (!note) {+ return;+ }++ const templateNote = becca.getNote(entity.value);++ if (!templateNote) {+ return;+ }++ const content = note.getContent();++ if (+ ["text", "code", "mermaid", "canvas", "relationMap", "mindMap", "webView"].includes(note.type) &&+ typeof content === "string" &&+ // if the note has already content we're not going to overwrite it with template's one+ (!content || content.trim().length === 0) &&+ templateNote.hasStringContent()+ ) {+ const templateNoteContent = templateNote.getContent();++ if (templateNoteContent) {+ note.setContent(templateNoteContent);+ }++ note.type = templateNote.type;+ note.mime = templateNote.mime;+ note.save();+ }++ // we'll copy the children notes only if there's none so far+ // this protects against e.g. multiple assignment of template relation resulting in having multiple copies of the subtree+ if (note.getChildNotes().length === 0 && !note.isDescendantOfNote(templateNote.noteId)) {+ noteService.duplicateSubtreeWithoutRoot(templateNote.noteId, note.noteId);+ }+ } else if (entity.type === "label" && ["sorted", "sortDirection", "sortFoldersFirst", "sortNatural", "sortLocale"].includes(entity.name)) {+ handleSortedAttribute(entity);+ } else if (entity.type === "label") {+ handleMaybeSortingLabel(entity);+ }+ } else if (entityName === "branches") {+ runAttachedRelations(entity.getNote(), "runOnBranchCreation", entity);++ if (entity.parentNote?.hasLabel("sorted")) {+ treeService.sortNotesIfNeeded(entity.parentNoteId);+ }+ } else if (entityName === "notes") {+ runAttachedRelations(entity, "runOnNoteCreation", entity);+ }+});++eventService.subscribe(eventService.CHILD_NOTE_CREATED, ({ parentNote, childNote }) => {+ runAttachedRelations(parentNote, "runOnChildNoteCreation", childNote);+});++function processInverseRelations(entityName: string, entity: BAttribute, handler: Handler) {+ if (entityName === "attributes" && entity.type === "relation") {+ const note = entity.getNote();+ const relDefinitions = note.getLabels(`relation:${entity.name}`);++ for (const relDefinition of relDefinitions) {+ const definition = relDefinition.getDefinition();++ if (definition.inverseRelation && definition.inverseRelation.trim()) {+ const targetNote = entity.getTargetNote();++ if (targetNote) {+ handler(definition, note, targetNote);+ }+ }+ }+ }+}++function handleSortedAttribute(entity: BAttribute) {+ treeService.sortNotesIfNeeded(entity.noteId);++ if (entity.isInheritable) {+ const note = becca.notes[entity.noteId];++ if (note) {+ for (const noteId of note.getSubtreeNoteIds()) {+ treeService.sortNotesIfNeeded(noteId);+ }+ }+ }+}++function handleMaybeSortingLabel(entity: BAttribute) {+ // check if this label is used for sorting, if yes force re-sort+ const note = becca.notes[entity.noteId];++ // this will not work on deleted notes, but in that case we don't really need to re-sort+ if (note) {+ for (const parentNote of note.getParentNotes()) {+ const sorted = parentNote.getLabelValue("sorted");+ if (sorted === null) {+ // checking specifically for null since that means the label doesn't exist+ // empty valued "sorted" is still valid+ continue;+ }++ if (+ sorted.includes(entity.name) || // hacky check if this label is used in the sort+ entity.name === "top" ||+ entity.name === "bottom"+ ) {+ treeService.sortNotesIfNeeded(parentNote.noteId);+ }+ }+ }+}++eventService.subscribe(eventService.ENTITY_CHANGED, ({ entityName, entity }) => {+ processInverseRelations(entityName, entity, (definition, note, targetNote) => {+ // we need to make sure that also target's inverse attribute exists and if not, then create it+ // inverse attribute has to target our note as well+ const hasInverseAttribute = targetNote.getRelations(definition.inverseRelation).some((attr) => attr.value === note.noteId);++ if (!hasInverseAttribute) {+ new BAttribute({+ noteId: targetNote.noteId,+ type: "relation",+ name: definition.inverseRelation || "",+ value: note.noteId,+ isInheritable: entity.isInheritable+ }).save();++ // becca will not be updated before we'll check from the other side which would create infinite relation creation (#2269)+ targetNote.invalidateThisCache();+ }+ });+});++eventService.subscribe(eventService.ENTITY_DELETED, ({ entityName, entity }) => {+ processInverseRelations(entityName, entity, (definition: DefinitionObject, note: BNote, targetNote: BNote) => {+ // if one inverse attribute is deleted, then the other should be deleted as well+ const relations = targetNote.getOwnedRelations(definition.inverseRelation);++ for (const relation of relations) {+ if (relation.value === note.noteId) {+ relation.markAsDeleted();+ }+ }+ });++ if (entityName === "branches") {+ runAttachedRelations(entity.getNote(), "runOnBranchDeletion", entity);+ }++ if (entityName === "notes" && entity.noteId.startsWith("_")) {+ // "named" note has been deleted, we will probably need to rebuild the hidden subtree+ // scheduling so that bulk deletes won't trigger so many checks+ oneTimeTimer.scheduleExecution("hidden-subtree-check", 1000, () => hiddenSubtreeService.checkHiddenSubtree());+ }+});++export default {+ runAttachedRelations+};diff --cc packages/trilium-core/src/services/hidden_subtree.tsindex feaeb42a49,0000000000..90ca6135c8mode 100644,000000..100644--- a/packages/trilium-core/src/services/hidden_subtree.ts+++ b/packages/trilium-core/src/services/hidden_subtree.ts@@@ -1,517 -1,0 +1,519 @@@+import type { HiddenSubtreeItem } from "@triliumnext/commons";+import { t } from "i18next";++import becca from "../becca/becca.js";+import BAttribute from "../becca/entities/battribute.js";+import BBranch from "../becca/entities/bbranch.js";+import BNote from "../becca/entities/bnote.js";+import buildLaunchBarConfig from "./hidden_subtree_launcherbar.js";+import buildHiddenSubtreeTemplates from "./hidden_subtree_templates.js";+import { cleanUpHelp, getHelpHiddenSubtreeData } from "./in_app_help.js";+import migrationService from "./migration.js";+import noteService from "./notes.js";++import { getLog } from "./log.js";++export const LBTPL_ROOT = "_lbTplRoot";+export const LBTPL_BASE = "_lbTplBase";+export const LBTPL_HEADER = "_lbTplHeader";+export const LBTPL_NOTE_LAUNCHER = "_lbTplLauncherNote";+export const LBTPL_WIDGET = "_lbTplLauncherWidget";+export const LBTPL_COMMAND = "_lbTplLauncherCommand";+export const LBTPL_SCRIPT = "_lbTplLauncherScript";+export const LBTPL_SPACER = "_lbTplSpacer";+export const LBTPL_CUSTOM_WIDGET = "_lbTplCustomWidget";++/*+ * Hidden subtree is generated as a "predictable structure" which means that it avoids generating random IDs to always+ * produce the same structure. This is needed because it is run on multiple instances in the sync cluster which might produce+ * duplicate subtrees. This way, all instances will generate the same structure with the same IDs.+ */++let hiddenSubtreeDefinition: HiddenSubtreeItem;++function buildHiddenSubtreeDefinition(helpSubtree: HiddenSubtreeItem[]): HiddenSubtreeItem {+ const launchbarConfig = buildLaunchBarConfig();++ return {+ id: "_hidden",+ title: t("hidden-subtree.root-title"),+ type: "doc",+ icon: "bx bx-hide",+ // we want to keep the hidden subtree always last, otherwise there will be problems with e.g., keyboard navigation+ // over tree when it's in the middle+ notePosition: 999_999_999,+ enforceAttributes: true,+ attributes: [+ { type: "label", name: "docName", value: "hidden" }+ ],+ children: [+ {+ id: "_search",+ title: t("hidden-subtree.search-history-title"),+ type: "doc"+ },+ {+ id: "_globalNoteMap",+ title: t("hidden-subtree.note-map-title"),+ type: "noteMap",+ attributes: [+ { type: "label", name: "mapRootNoteId", value: "hoisted" },+ { type: "label", name: "keepCurrentHoisting" }+ ]+ },+ {+ id: "_sqlConsole",+ title: t("hidden-subtree.sql-console-history-title"),+ type: "doc",+ icon: "bx-data"+ },+ {+ id: "_llmChat",+ title: t("hidden-subtree.llm-chat-history-title"),+ type: "doc",+ icon: "bx-message-square-dots"+ },+ {+ id: "_share",+ title: t("hidden-subtree.shared-notes-title"),+ type: "doc",+ attributes: [{ type: "label", name: "docName", value: "share" }]+ },+ {+ id: "_bulkAction",+ title: t("hidden-subtree.bulk-action-title"),+ type: "doc"+ },+ {+ id: "_backendLog",+ title: t("hidden-subtree.backend-log-title"),+ type: "contentWidget",+ icon: "bx-terminal",+ attributes: [+ { type: "label", name: "keepCurrentHoisting" },+ { type: "label", name: "fullContentWidth" }+ ]+ },+ {+ // place for user scripts hidden stuff (scripts should not create notes directly under hidden root)+ id: "_userHidden",+ title: t("hidden-subtree.user-hidden-title"),+ type: "doc",+ attributes: [{ type: "label", name: "docName", value: "user_hidden" }]+ },+ {+ id: LBTPL_ROOT,+ title: t("hidden-subtree.launch-bar-templates-title"),+ type: "doc",+ children: [+ {+ id: LBTPL_BASE,+ title: t("hidden-subtree.base-abstract-launcher-title"),+ type: "doc"+ },+ {+ id: LBTPL_COMMAND,+ title: t("hidden-subtree.command-launcher-title"),+ type: "doc",+ attributes: [+ { type: "relation", name: "template", value: LBTPL_BASE },+ { type: "label", name: "launcherType", value: "command" },+ { type: "label", name: "docName", value: "launchbar_command_launcher" }+ ]+ },+ {+ id: LBTPL_NOTE_LAUNCHER,+ title: t("hidden-subtree.note-launcher-title"),+ type: "doc",+ attributes: [+ { type: "relation", name: "template", value: LBTPL_BASE },+ { type: "label", name: "launcherType", value: "note" },+ { type: "label", name: "relation:target", value: "promoted" },+ { type: "label", name: "relation:hoistedNote", value: "promoted" },+ { type: "label", name: "label:keyboardShortcut", value: "promoted,text" },+ { type: "label", name: "docName", value: "launchbar_note_launcher" }+ ]+ },+ {+ id: LBTPL_SCRIPT,+ title: t("hidden-subtree.script-launcher-title"),+ type: "doc",+ attributes: [+ { type: "relation", name: "template", value: LBTPL_BASE },+ { type: "label", name: "launcherType", value: "script" },+ { type: "label", name: "relation:script", value: "promoted" },+ { type: "label", name: "label:keyboardShortcut", value: "promoted,text" },+ { type: "label", name: "docName", value: "launchbar_script_launcher" }+ ]+ },+ {+ id: LBTPL_WIDGET,+ title: t("hidden-subtree.built-in-widget-title"),+ type: "doc",+ attributes: [+ { type: "relation", name: "template", value: LBTPL_BASE },+ { type: "label", name: "launcherType", value: "builtinWidget" }+ ]+ },+ {+ id: LBTPL_SPACER,+ title: t("hidden-subtree.spacer-title"),+ type: "doc",+ icon: "bx-move-vertical",+ attributes: [+ { type: "relation", name: "template", value: LBTPL_WIDGET },+ { type: "label", name: "builtinWidget", value: "spacer" },+ { type: "label", name: "label:baseSize", value: "promoted,number" },+ { type: "label", name: "label:growthFactor", value: "promoted,number" },+ { type: "label", name: "docName", value: "launchbar_spacer" }+ ]+ },+ {+ id: LBTPL_CUSTOM_WIDGET,+ title: t("hidden-subtree.custom-widget-title"),+ type: "doc",+ attributes: [+ { type: "relation", name: "template", value: LBTPL_BASE },+ { type: "label", name: "launcherType", value: "customWidget" },+ { type: "label", name: "relation:widget", value: "promoted" },+ { type: "label", name: "docName", value: "launchbar_widget_launcher" }+ ]+ }+ ]+ },+ {+ id: "_lbRoot",+ title: t("hidden-subtree.launch-bar-title"),+ type: "doc",+ icon: "bx-sidebar",+ isExpanded: true,+ attributes: [{ type: "label", name: "docName", value: "launchbar_intro" }],+ children: [+ {+ id: "_lbAvailableLaunchers",+ title: t("hidden-subtree.available-launchers-title"),+ type: "doc",+ icon: "bx-hide",+ isExpanded: true,+ attributes: [{ type: "label", name: "docName", value: "launchbar_intro" }],+ children: launchbarConfig.desktopAvailableLaunchers+ },+ {+ id: "_lbVisibleLaunchers",+ title: t("hidden-subtree.visible-launchers-title"),+ type: "doc",+ icon: "bx-show",+ isExpanded: true,+ attributes: [{ type: "label", name: "docName", value: "launchbar_intro" }],+ children: launchbarConfig.desktopVisibleLaunchers+ }+ ]+ },+ {+ id: "_lbMobileRoot",+ title: "Mobile Launch Bar",+ type: "doc",+ icon: "bx-mobile",+ isExpanded: true,+ attributes: [{ type: "label", name: "docName", value: "launchbar_intro" }],+ children: [+ {+ id: "_lbMobileAvailableLaunchers",+ title: t("hidden-subtree.available-launchers-title"),+ type: "doc",+ icon: "bx-hide",+ isExpanded: true,+ attributes: [{ type: "label", name: "docName", value: "launchbar_intro" }],+ children: launchbarConfig.mobileAvailableLaunchers+ },+ {+ id: "_lbMobileVisibleLaunchers",+ title: t("hidden-subtree.visible-launchers-title"),+ type: "doc",+ icon: "bx-show",+ isExpanded: true,+ attributes: [{ type: "label", name: "docName", value: "launchbar_intro" }],+ children: launchbarConfig.mobileVisibleLaunchers+ }+ ]+ },+ {+ id: "_options",+ title: t("hidden-subtree.options-title"),+ type: "book",+ icon: "bx-cog",+ children: [+ { id: "_optionsAppearance", title: t("hidden-subtree.appearance-title"), type: "contentWidget", icon: "bx-layout" },+ { id: "_optionsShortcuts", title: t("hidden-subtree.shortcuts-title"), type: "contentWidget", icon: "bxs-keyboard" },+ { id: "_optionsTextNotes", title: t("hidden-subtree.text-notes"), type: "contentWidget", icon: "bx-text" },+ { id: "_optionsCodeNotes", title: t("hidden-subtree.code-notes-title"), type: "contentWidget", icon: "bx-code" },- { id: "_optionsImages", title: t("hidden-subtree.images-title"), type: "contentWidget", icon: "bx-image" },++ { id: "_optionsImages", title: "Images", type: "contentWidget", enforceDeleted: true },++ { id: "_optionsMedia", title: t("hidden-subtree.images-title"), type: "contentWidget", icon: "bx-image" },+ { id: "_optionsSpellcheck", title: t("hidden-subtree.spellcheck-title"), type: "contentWidget", icon: "bx-check-double" },+ { id: "_optionsPassword", title: t("hidden-subtree.password-title"), type: "contentWidget", icon: "bx-lock" },+ { id: '_optionsMFA', title: t('hidden-subtree.multi-factor-authentication-title'), type: 'contentWidget', icon: 'bx-lock ' },+ { id: "_optionsEtapi", title: t("hidden-subtree.etapi-title"), type: "contentWidget", icon: "bx-extension" },+ { id: "_optionsBackup", title: t("hidden-subtree.backup-title"), type: "contentWidget", icon: "bx-data" },+ { id: "_optionsSync", title: t("hidden-subtree.sync-title"), type: "contentWidget", icon: "bx-wifi" },+ { id: "_optionsLlm", title: t("hidden-subtree.llm-title"), type: "contentWidget", icon: "bx-bot" },+ { id: "_optionsAi", title: "AI Chat", type: "contentWidget", enforceDeleted: true },+ { id: "_optionsOther", title: t("hidden-subtree.other"), type: "contentWidget", icon: "bx-dots-horizontal" },+ { id: "_optionsLocalization", title: t("hidden-subtree.localization"), type: "contentWidget", icon: "bx-world" },+ { id: "_optionsAdvanced", title: t("hidden-subtree.advanced-title"), type: "contentWidget" }+ ]+ },+ {+ id: "_help",+ title: t("hidden-subtree.user-guide"),+ type: "book",+ icon: "bx-help-circle",+ children: helpSubtree,+ isExpanded: true+ },+ buildHiddenSubtreeTemplates()+ ]+ };+}++interface CheckHiddenExtraOpts {+ restoreNames?: boolean;+}++function checkHiddenSubtree(force = false, extraOpts: CheckHiddenExtraOpts = {}) {+ if (!force && !migrationService.isDbUpToDate()) {+ // on-delete hook might get triggered during some future migration and cause havoc+ getLog().info("Will not check hidden subtree until migration is finished.");+ return;+ }++ const helpSubtree = getHelpHiddenSubtreeData();+ if (!hiddenSubtreeDefinition || force) {+ hiddenSubtreeDefinition = buildHiddenSubtreeDefinition(helpSubtree);+ }++ getSql().transactional(() => {+ checkHiddenSubtreeRecursively("root", hiddenSubtreeDefinition, extraOpts);+ });++ try {+ cleanUpHelp(helpSubtree);+ } catch (e) {+ // Non-critical operation should something go wrong.+ console.error(e);+ }+}++/**+ * Get all expected parent IDs for a given note ID from the hidden subtree definition+ */+function getExpectedParentIds(noteId: string, subtree: HiddenSubtreeItem): string[] {+ const expectedParents: string[] = [];++ function traverse(item: HiddenSubtreeItem, parentId: string) {+ if (item.id === noteId) {+ expectedParents.push(parentId);+ }++ if (item.children) {+ for (const child of item.children) {+ traverse(child, item.id);+ }+ }+ }++ // Start traversal from root+ if (subtree.id === noteId) {+ expectedParents.push("root");+ }++ if (subtree.children) {+ for (const child of subtree.children) {+ traverse(child, subtree.id);+ }+ }++ return expectedParents;+}++/**+ * Check if a note ID is within the hidden subtree structure+ */+function isWithinHiddenSubtree(noteId: string): boolean {+ // Consider a note to be within hidden subtree if it starts with underscore+ // This is the convention used for hidden subtree notes+ return noteId.startsWith("_") || noteId === "root";+}++function checkHiddenSubtreeRecursively(parentNoteId: string, item: HiddenSubtreeItem, extraOpts: CheckHiddenExtraOpts = {}) {+ if (!item.id || !item.type || !item.title) {+ throw new Error(`Item does not contain mandatory properties: ${JSON.stringify(item)}`);+ }++ if (item.id.charAt(0) !== "_") {+ throw new Error(`ID has to start with underscore, given '${item.id}'`);+ }++ let note = becca.notes[item.id] as BNote | undefined;+ let branch: BBranch | undefined;+ const log = getLog();++ if (item.enforceDeleted) {+ note?.deleteNote();+ return;+ }++ if (!note) {+ // Missing item, add it.+ ({ note, branch } = noteService.createNewNote({+ noteId: item.id,+ title: item.title,+ type: item.type,+ parentNoteId,+ content: item.content ?? "",+ ignoreForbiddenParents: true+ }));+ } else {+ // Existing item, check if it's in the right state.+ branch = note.getParentBranches().find((branch) => branch.parentNoteId === parentNoteId);++ if (item.content && note.getContent() !== item.content) {+ log.info(`Updating content of ${item.id}.`);+ note.setContent(item.content);+ }++ if (item.enforceBranches || item.id.startsWith("_help")) {+ // Clean up any branches that shouldn't exist according to the meta definition+ // For hidden subtree notes, we want to ensure they only exist in their designated locations++ // If the note exists but doesn't have a branch in the expected parent,+ // create the missing branch to ensure it's in the correct location+ if (!branch) {+ log.info(`Creating missing branch for note ${item.id} under parent ${parentNoteId}.`);+ branch = new BBranch({+ noteId: item.id,+ parentNoteId,+ notePosition: item.notePosition !== undefined ? item.notePosition : undefined,+ isExpanded: item.isExpanded !== undefined ? item.isExpanded : false+ }).save();+ }++ // Remove any branches that are not in the expected parent.+ const expectedParents = getExpectedParentIds(item.id, hiddenSubtreeDefinition);+ const currentBranches = note.getParentBranches();++ for (const currentBranch of currentBranches) {+ // Only delete branches that are not in the expected locations+ // and are within the hidden subtree structure (avoid touching user-created clones)+ if (!expectedParents.includes(currentBranch.parentNoteId) &&+ isWithinHiddenSubtree(currentBranch.parentNoteId)) {+ log.info(`Removing unexpected branch for note '${item.id}' from parent '${currentBranch.parentNoteId}'`);+ currentBranch.markAsDeleted();+ }+ }+ }+ }++ const attrs = [...(item.attributes || [])];++ if (item.icon) {+ attrs.push({ type: "label", name: "iconClass", value: `bx ${item.icon}` });+ }++ if (item.type === "launcher") {+ if (item.command) {+ attrs.push({ type: "relation", name: "template", value: LBTPL_COMMAND });+ attrs.push({ type: "label", name: "command", value: item.command });+ } else if (item.builtinWidget) {+ if (item.builtinWidget === "spacer") {+ attrs.push({ type: "relation", name: "template", value: LBTPL_SPACER });+ attrs.push({ type: "label", name: "baseSize", value: item.baseSize });+ attrs.push({ type: "label", name: "growthFactor", value: item.growthFactor });+ } else {+ attrs.push({ type: "relation", name: "template", value: LBTPL_WIDGET });+ }++ attrs.push({ type: "label", name: "builtinWidget", value: item.builtinWidget });+ } else if (item.targetNoteId) {+ attrs.push({ type: "relation", name: "template", value: LBTPL_NOTE_LAUNCHER });+ attrs.push({ type: "relation", name: "target", value: item.targetNoteId });+ } else if (!item.enforceDeleted) {+ throw new Error(`No action defined for launcher ${JSON.stringify(item)}`);+ }+ }++ const shouldRestoreNames = extraOpts.restoreNames || note.noteId.startsWith("_help") || item.id.startsWith("_lb") || item.id.startsWith("_template");+ if (shouldRestoreNames && note.title !== item.title) {+ note.title = item.title;+ note.save();+ }++ if (note.type !== item.type) {+ // enforce a correct note type+ note.type = item.type;+ note.save();+ }++ if (branch) {+ // in case of launchers the branch ID is not preserved and should not be relied upon - launchers which move between+ // visible and available will change branch since the branch's parent-child relationship is immutable+ if (item.notePosition !== undefined && branch.notePosition !== item.notePosition) {+ branch.notePosition = item.notePosition;+ branch.save();+ }++ if (item.isExpanded !== undefined && branch.isExpanded !== item.isExpanded) {+ branch.isExpanded = item.isExpanded;+ branch.save();+ }+ }++ // Enforce attribute structure if needed.+ if (item.enforceAttributes) {+ for (const attribute of note.getAttributes()) {+ // Remove unwanted attributes.+ const attrDef = attrs.find(a => a.name === attribute.name);+ if (!attrDef) {+ console.log(`Removing unwanted attribute ${attribute.name} where expected attrs are ${attrs.map(a => a.name).join(", ")}`);+ attribute.markAsDeleted();+ continue;+ }++ // Ensure value is consistent.+ if (attribute.value !== attrDef.value || attribute.type !== attrDef.type) {+ attribute.type = attrDef.type;+ attribute.value = attrDef.value ?? "";+ attribute.save();+ }+ }+ }++ for (const attr of attrs) {+ const attrId = `${note.noteId}_${attr.type.charAt(0)}${attr.name}`;++ const existingAttribute = note.getAttributes().find((attr) => attr.attributeId === attrId);++ if (!existingAttribute) {+ new BAttribute({+ attributeId: attrId,+ noteId: note.noteId,+ type: attr.type,+ name: attr.name,+ value: attr.value,+ isInheritable: attr.isInheritable+ }).save();+ } else if (attr.name === "docName" || (existingAttribute.noteId.startsWith("_help") && attr.name === "iconClass")) {+ if (existingAttribute.value !== attr.value) {+ log.info(`Updating attribute ${attrId} from "${existingAttribute.value}" to "${attr.value}"`);+ existingAttribute.value = attr.value ?? "";+ existingAttribute.save();+ }+ }+ }++ for (const child of item.children || []) {+ checkHiddenSubtreeRecursively(item.id, child, extraOpts);+ }+}++export default {+ checkHiddenSubtree+};diff --cc packages/trilium-core/src/services/import/markdown.tsindex 35bc7cf8d4,a812567887..4b20bf271d--- a/packages/trilium-core/src/services/import/markdown.ts+++ b/packages/trilium-core/src/services/import/markdown.ts@@@ -1,15 -1,14 +1,12 @@@- import { getMimeTypeFromMarkdownName, MIME_TYPE_AUTO } from "@triliumnext/commons";- import { normalizeMimeTypeForCKEditor } from "@triliumnext/commons";- import { parse, Renderer, type Tokens,use } from "marked";--+ import { getMimeTypeFromMarkdownName, MIME_TYPE_AUTO, normalizeMimeTypeForCKEditor, transclusionExtension, wikiLinkExtension } from "@triliumnext/commons";+ import { parse, Renderer, type Tokens, use } from "marked";import { ADMONITION_TYPE_MAPPINGS } from "../export/markdown.js";- import wikiLinkInternalLink from "./markdown/wikilink_internal_link.js";- import wikiLinkTransclusion from "./markdown/wikilink_transclusion.js";-import htmlSanitizer from "../html_sanitizer.js";-import utils from "../utils.js";import importUtils from "./utils.js";+import { escapeHtml } from "../utils/index.js";+import { sanitizeHtml } from "../sanitizer.js";-const escape = utils.escapeHtml;+const escape = escapeHtml;/*** Keep renderer code up to date with https://github.com/markedjs/marked/blob/master/src/Renderer.ts.diff --cc packages/trilium-core/src/services/options_init.tsindex 0219a4d33b,0000000000..9b5001a4fbmode 100644,000000..100644--- a/packages/trilium-core/src/services/options_init.ts+++ b/packages/trilium-core/src/services/options_init.ts@@@ -1,264 -1,0 +1,269 @@@+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", "120000", false);+ optionService.createOption("syncProxy", opts.syncProxy || "", false);+}++/**+ * 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: "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: "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 },+ { 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 },++ // 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 },++ // 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: false }++ { 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/search/expressions/ocr_content.tsindex 0000000000,2b3472b1bb..2b3472b1bbmode 000000,100644..100644--- a/packages/trilium-core/src/services/search/expressions/ocr_content.ts+++ b/packages/trilium-core/src/services/search/expressions/ocr_content.tsdiff --cc packages/trilium-core/src/services/search/search_result.tsindex ef99daba65,10e4b33ca6..03fb79ed3d--- a/packages/trilium-core/src/services/search/search_result.ts+++ b/packages/trilium-core/src/services/search/search_result.ts@@@ -1,6 -1,5 +1,5 @@@- import becca_service from "../../becca/becca_service";-import becca from "../../becca/becca.js";-import beccaService from "../../becca/becca_service.js";++import becca_service from "../../becca/becca_service.js";import {calculateOptimizedEditDistance,FUZZY_SEARCH_CONFIG,diff --cc packages/trilium-core/src/services/search/services/parse.tsindex 00e918cdcf,a117bf9928..c0a08d89d0--- a/packages/trilium-core/src/services/search/services/parse.ts+++ b/packages/trilium-core/src/services/search/services/parse.ts@@@ -1,28 -1,30 +1,28 @@@- "use strict";---import { dayjs } from "@triliumnext/commons";+-import { removeDiacritic } from "../../utils.js";+ import AncestorExp from "../expressions/ancestor.js";import AndExp from "../expressions/and.js";- import OrExp from "../expressions/or.js";- import NotExp from "../expressions/not.js";+ import AttributeExistsExp from "../expressions/attribute_exists.js";import ChildOfExp from "../expressions/child_of.js";import DescendantOfExp from "../expressions/descendant_of.js";-import type Expression from "../expressions/expression.js";-import IsHiddenExp from "../expressions/is_hidden.js";+import ParentOfExp from "../expressions/parent_of.js";+import RelationWhereExp from "../expressions/relation_where.js";+import PropertyComparisonExp from "../expressions/property_comparison.js";- import AttributeExistsExp from "../expressions/attribute_exists.js";import LabelComparisonExp from "../expressions/label_comparison.js";-import NotExp from "../expressions/not.js";-import NoteContentFulltextExp from "../expressions/note_content_fulltext.js";import NoteFlatTextExp from "../expressions/note_flat_text.js";-import OCRContentExpression from "../expressions/ocr_content.js";-import OrExp from "../expressions/or.js";+import NoteContentFulltextExp from "../expressions/note_content_fulltext.js";import OrderByAndLimitExp from "../expressions/order_by_and_limit.js";- import AncestorExp from "../expressions/ancestor.js";-import ParentOfExp from "../expressions/parent_of.js";-import PropertyComparisonExp from "../expressions/property_comparison.js";-import RelationWhereExp from "../expressions/relation_where.js";+import buildComparator from "./build_comparator.js";+import ValueExtractor from "../value_extractor.js";- import { removeDiacritic } from "../../utils/index.js";import TrueExp from "../expressions/true.js";- import IsHiddenExp from "../expressions/is_hidden.js";import type SearchContext from "../search_context.js";-import ValueExtractor from "../value_extractor.js";-import buildComparator from "./build_comparator.js";import type { TokenData, TokenStructure } from "./types.js";+import type Expression from "../expressions/expression.js";++import IsHiddenExp from "../expressions/is_hidden.js";++import NotExp from "../expressions/not.js";++import OCRContentExpression from "../expressions/ocr_content.js";++import OrExp from "../expressions/or.js";++import { removeDiacritic } from "../../utils/index.js";function getFulltext(_tokens: TokenData[], searchContext: SearchContext, leadingOperator?: string) {const tokens: string[] = _tokens.map((t) => removeDiacritic(t.token));diff --cc packages/trilium-core/src/services/search/services/search.tsindex 72f8ef051d,0000000000..de61756ef8mode 100644,000000..100644--- a/packages/trilium-core/src/services/search/services/search.ts+++ b/packages/trilium-core/src/services/search/services/search.ts@@@ -1,796 -1,0 +1,821 @@@+import normalizeString from "normalize-strings";+import striptags from "striptags";++import becca from "../../../becca/becca.js";+import becca_service from "../../../becca/becca_service.js";+import type BNote from "../../../becca/entities/bnote.js";+import hoistedNoteService from "../../hoisted_note.js";+import { getLog } from "../../log.js";+import protectedSessionService from "../../protected_session.js";+import scriptService from "../../script.js";+import { escapeHtml, escapeRegExp } from "../../utils/index.js";+import type Expression from "../expressions/expression.js";+import SearchContext from "../search_context.js";+import SearchResult from "../search_result.js";+import handleParens from "./handle_parens.js";+import lex from "./lex.js";+import parse from "./parse.js";+import type { SearchParams, TokenStructure } from "./types.js";+import { getSql } from "../../sql/index.js";++export interface SearchNoteResult {+ searchResultNoteIds: string[];+ highlightedTokens: string[];+ error: string | null;+}++export const EMPTY_RESULT: SearchNoteResult = {+ searchResultNoteIds: [],+ highlightedTokens: [],+ error: null+};++function searchFromNote(note: BNote): SearchNoteResult {+ let searchResultNoteIds;+ let highlightedTokens: string[];++ const searchScript = note.getRelationValue("searchScript");+ const searchString = note.getLabelValue("searchString") || "";+ let error: string | null = null;++ if (searchScript) {+ searchResultNoteIds = searchFromRelation(note, "searchScript");+ highlightedTokens = [];+ } else {+ const searchContext = new SearchContext({+ fastSearch: note.hasLabel("fastSearch"),+ ancestorNoteId: note.getRelationValue("ancestor") || undefined,+ ancestorDepth: note.getLabelValue("ancestorDepth") || undefined,+ includeArchivedNotes: note.hasLabel("includeArchivedNotes"),+ orderBy: note.getLabelValue("orderBy") || undefined,+ orderDirection: note.getLabelValue("orderDirection") || undefined,+ limit: parseInt(note.getLabelValue("limit") || "0", 10),+ debug: note.hasLabel("debug"),+ fuzzyAttributeSearch: false+ });++ searchResultNoteIds = findResultsWithQuery(searchString, searchContext).map((sr) => sr.noteId);++ highlightedTokens = searchContext.highlightedTokens;+ error = searchContext.getError();+ }++ // we won't return search note's own noteId+ // also don't allow root since that would force infinite cycle+ return {+ searchResultNoteIds: searchResultNoteIds.filter((resultNoteId) => !["root", note.noteId].includes(resultNoteId)),+ highlightedTokens,+ error+ };+}++function searchFromRelation(note: BNote, relationName: string) {+ const scriptNote = note.getRelationTarget(relationName);++ const log = getLog();+ if (!scriptNote) {+ log.info(`Search note's relation ${relationName} has not been found.`);++ return [];+ }++ if (!scriptNote.isJavaScript() || scriptNote.getScriptEnv() !== "backend") {+ log.info(`Note ${scriptNote.noteId} is not executable.`);++ return [];+ }++ if (!note.isContentAvailable()) {+ log.info(`Note ${scriptNote.noteId} is not available outside of protected session.`);++ return [];+ }++ const result = scriptService.executeNote(scriptNote, { originEntity: note });++ if (!Array.isArray(result)) {+ log.info(`Result from ${scriptNote.noteId} is not an array.`);++ return [];+ }++ if (result.length === 0) {+ return [];+ }++ // we expect either array of noteIds (strings) or notes, in that case we extract noteIds ourselves+ return typeof result[0] === "string" ? result : result.map((item) => item.noteId);+}++function loadNeededInfoFromDatabase() {+ /**+ * This complex structure is needed to calculate total occupied space by a note. Several object instances+ * (note, revisions, attachments) can point to a single blobId, and thus the blob size should count towards the total+ * only once.+ *+ * noteId => { blobId => blobSize }+ */+ const noteBlobs: Record<string, Record<string, number>> = {};++ type NoteContentLengthsRow = {+ noteId: string;+ blobId: string;+ length: number;+ };+ const log = getLog();+ const noteContentLengths = getSql().getRows<NoteContentLengthsRow>(`+ SELECT+ noteId,+ blobId,+ LENGTH(content) AS length+ FROM notes+ JOIN blobs USING(blobId)+ WHERE notes.isDeleted = 0`);++ for (const { noteId, blobId, length } of noteContentLengths) {+ if (!(noteId in becca.notes)) {+ log.error(`Note '${noteId}' not found in becca.`);+ continue;+ }++ becca.notes[noteId].contentSize = length;+ becca.notes[noteId].revisionCount = 0;++ noteBlobs[noteId] = { [blobId]: length };+ }++ type AttachmentContentLengthsRow = {+ noteId: string;+ blobId: string;+ length: number;+ };+ const attachmentContentLengths = getSql().getRows<AttachmentContentLengthsRow>(`+ SELECT+ ownerId AS noteId,+ attachments.blobId,+ LENGTH(content) AS length+ FROM attachments+ JOIN notes ON attachments.ownerId = notes.noteId+ JOIN blobs ON attachments.blobId = blobs.blobId+ WHERE attachments.isDeleted = 0+ AND notes.isDeleted = 0`);++ for (const { noteId, blobId, length } of attachmentContentLengths) {+ if (!(noteId in becca.notes)) {+ log.error(`Note '${noteId}' not found in becca.`);+ continue;+ }++ if (!(noteId in noteBlobs)) {+ log.error(`Did not find a '${noteId}' in the noteBlobs.`);+ continue;+ }++ noteBlobs[noteId][blobId] = length;+ }++ for (const noteId in noteBlobs) {+ becca.notes[noteId].contentAndAttachmentsSize = Object.values(noteBlobs[noteId]).reduce((acc, size) => acc + size, 0);+ }++ type RevisionRow = {+ noteId: string;+ blobId: string;+ length: number;+ isNoteRevision: true;+ };+ const revisionContentLengths = getSql().getRows<RevisionRow>(`+ SELECT+ noteId,+ revisions.blobId,+ LENGTH(content) AS length,+ 1 AS isNoteRevision+ FROM notes+ JOIN revisions USING(noteId)+ JOIN blobs ON revisions.blobId = blobs.blobId+ WHERE notes.isDeleted = 0+ UNION ALL+ SELECT+ noteId,+ revisions.blobId,+ LENGTH(content) AS length,+ 0 AS isNoteRevision -- it's attachment not counting towards revision count+ FROM notes+ JOIN revisions USING(noteId)+ JOIN attachments ON attachments.ownerId = revisions.revisionId+ JOIN blobs ON attachments.blobId = blobs.blobId+ WHERE notes.isDeleted = 0`);++ for (const { noteId, blobId, length, isNoteRevision } of revisionContentLengths) {+ if (!(noteId in becca.notes)) {+ log.error(`Note '${noteId}' not found in becca.`);+ continue;+ }++ if (!(noteId in noteBlobs)) {+ log.error(`Did not find a '${noteId}' in the noteBlobs.`);+ continue;+ }++ noteBlobs[noteId][blobId] = length;++ if (isNoteRevision) {+ const noteRevision = becca.notes[noteId];+ if (noteRevision && noteRevision.revisionCount) {+ noteRevision.revisionCount++;+ }+ }+ }++ for (const noteId in noteBlobs) {+ becca.notes[noteId].contentAndAttachmentsAndRevisionsSize = Object.values(noteBlobs[noteId]).reduce((acc, size) => acc + size, 0);+ }+}++function findResultsWithExpression(expression: Expression, searchContext: SearchContext): SearchResult[] {+ if (searchContext.dbLoadNeeded) {+ loadNeededInfoFromDatabase();+ }++ // If there's an explicit orderBy clause, skip progressive search+ // as it would interfere with the ordering+ if (searchContext.orderBy) {+ // For ordered queries, don't use progressive search but respect+ // the original fuzzy matching setting+ return performSearch(expression, searchContext, searchContext.enableFuzzyMatching);+ }++ // If fuzzy matching is explicitly disabled, skip progressive search+ if (!searchContext.enableFuzzyMatching) {+ return performSearch(expression, searchContext, false);+ }++ // Phase 1: Try exact matches first (without fuzzy matching)+ const exactResults = performSearch(expression, searchContext, false);++ // Check if we have sufficient high-quality results+ const minResultThreshold = 5;+ const minScoreForQuality = 10; // Minimum score to consider a result "high quality"++ const highQualityResults = exactResults.filter(result => result.score >= minScoreForQuality);++ // If we have enough high-quality exact matches, return them+ if (highQualityResults.length >= minResultThreshold) {+ return exactResults;+ }++ // Phase 2: Add fuzzy matching as fallback when exact matches are insufficient+ const fuzzyResults = performSearch(expression, searchContext, true);++ // Merge results, ensuring exact matches always rank higher than fuzzy matches+ return mergeExactAndFuzzyResults(exactResults, fuzzyResults);+}++function performSearch(expression: Expression, searchContext: SearchContext, enableFuzzyMatching: boolean): SearchResult[] {+ const allNoteSet = becca.getAllNoteSet();++ const noteIdToNotePath: Record<string, string[]> = {};+ const executionContext = {+ noteIdToNotePath+ };++ // Store original fuzzy setting and temporarily override it+ const originalFuzzyMatching = searchContext.enableFuzzyMatching;+ searchContext.enableFuzzyMatching = enableFuzzyMatching;++ const noteSet = expression.execute(allNoteSet, executionContext, searchContext);++ const searchResults = noteSet.notes.map((note) => {+ const notePathArray = executionContext.noteIdToNotePath[note.noteId] || note.getBestNotePath();++ if (!notePathArray) {+ throw new Error(`Can't find note path for note ${JSON.stringify(note.getPojo())}`);+ }++ return new SearchResult(notePathArray);+ });++ for (const res of searchResults) {+ res.computeScore(searchContext.fulltextQuery, searchContext.highlightedTokens, enableFuzzyMatching);+ }++ // Restore original fuzzy setting+ searchContext.enableFuzzyMatching = originalFuzzyMatching;++ if (!noteSet.sorted) {+ searchResults.sort((a, b) => {+ if (a.score > b.score) {+ return -1;+ } else if (a.score < b.score) {+ return 1;+ }++ // if score does not decide then sort results by depth of the note.+ // This is based on the assumption that more important results are closer to the note root.+ if (a.notePathArray.length === b.notePathArray.length) {+ return a.notePathTitle < b.notePathTitle ? -1 : 1;+ }++ return a.notePathArray.length < b.notePathArray.length ? -1 : 1;+ });+ }++ return searchResults;+}++function mergeExactAndFuzzyResults(exactResults: SearchResult[], fuzzyResults: SearchResult[]): SearchResult[] {+ // Create a map of exact result note IDs for deduplication+ const exactNoteIds = new Set(exactResults.map(result => result.noteId));++ // Add fuzzy results that aren't already in exact results+ const additionalFuzzyResults = fuzzyResults.filter(result => !exactNoteIds.has(result.noteId));++ // Sort exact results by score (best exact matches first)+ exactResults.sort((a, b) => {+ if (a.score > b.score) {+ return -1;+ } else if (a.score < b.score) {+ return 1;+ }++ // if score does not decide then sort results by depth of the note.+ if (a.notePathArray.length === b.notePathArray.length) {+ return a.notePathTitle < b.notePathTitle ? -1 : 1;+ }++ return a.notePathArray.length < b.notePathArray.length ? -1 : 1;+ });++ // Sort fuzzy results by score (best fuzzy matches first)+ additionalFuzzyResults.sort((a, b) => {+ if (a.score > b.score) {+ return -1;+ } else if (a.score < b.score) {+ return 1;+ }++ // if score does not decide then sort results by depth of the note.+ if (a.notePathArray.length === b.notePathArray.length) {+ return a.notePathTitle < b.notePathTitle ? -1 : 1;+ }++ return a.notePathArray.length < b.notePathArray.length ? -1 : 1;+ });++ // CRITICAL: Always put exact matches before fuzzy matches, regardless of scores+ return [...exactResults, ...additionalFuzzyResults];+}++function parseQueryToExpression(query: string, searchContext: SearchContext) {+ const { fulltextQuery, fulltextTokens, expressionTokens, leadingOperator } = lex(query);+ searchContext.fulltextQuery = fulltextQuery;++ let structuredExpressionTokens: TokenStructure;++ try {+ structuredExpressionTokens = handleParens(expressionTokens);+ } catch (e: any) {+ structuredExpressionTokens = [];+ searchContext.addError(e.message);+ }++ const expression = parse({+ fulltextTokens,+ expressionTokens: structuredExpressionTokens,+ searchContext,+ originalQuery: query,+ leadingOperator+ });++ if (searchContext.debug) {+ searchContext.debugInfo = {+ fulltextTokens,+ structuredExpressionTokens,+ expression+ };++ getLog().info(`Search debug: ${JSON.stringify(searchContext.debugInfo, null, 4)}`);+ }++ return expression;+}++function searchNotes(query: string, params: SearchParams = {}): BNote[] {+ const searchResults = findResultsWithQuery(query, new SearchContext(params));++ return searchResults.map((sr) => becca.notes[sr.noteId]);+}++function findResultsWithQuery(query: string, searchContext: SearchContext): SearchResult[] {+ query = query || "";+ searchContext.originalQuery = query;++ const expression = parseQueryToExpression(query, searchContext);++ if (!expression) {+ return [];+ }++ // If the query starts with '#', it's a pure expression query.+ // Don't use progressive search for these as they may have complex+ // ordering or other logic that shouldn't be interfered with.+ const isPureExpressionQuery = query.trim().startsWith('#');++ if (isPureExpressionQuery) {+ // For pure expression queries, use standard search without progressive phases+ return performSearch(expression, searchContext, searchContext.enableFuzzyMatching);+ }++ return findResultsWithExpression(expression, searchContext);+}++function findFirstNoteWithQuery(query: string, searchContext: SearchContext): BNote | null {+ const searchResults = findResultsWithQuery(query, searchContext);++ return searchResults.length > 0 ? becca.notes[searchResults[0].noteId] : null;+}+++/**++ * Returns the first non-empty textRepresentation for a note's own blob++ * or any of its attachment blobs.++ */++function getTextRepresentationForNote(note: BNote): string | null {++ // Query only textRepresentation to avoid loading large binary content into memory.++ const row = getSql().getRow<{ textRepresentation: string | null }>(`++ SELECT b.textRepresentation FROM blobs b++ WHERE b.textRepresentation IS NOT NULL++ AND b.textRepresentation != ''++ AND (++ b.blobId = ?++ OR b.blobId IN (SELECT blobId FROM attachments WHERE ownerId = ? AND isDeleted = 0)++ )++ LIMIT 1++ `, [note.blobId, note.noteId]);++++ return row?.textRepresentation ?? null;++}+++function extractContentSnippet(noteId: string, searchTokens: string[], maxLength: number = 200): string {+ const note = becca.notes[noteId];+ if (!note) {+ return "";+ }+- // Only extract content for text-based notes- if (!["text", "code", "mermaid", "canvas", "mindMap"].includes(note.type)) {- return "";- }-+ try {- let content = note.getContent();++ let content: string | undefined;+- if (!content || typeof content !== "string") {++ if (["text", "code", "mermaid", "canvas", "mindMap"].includes(note.type)) {++ const raw = note.getContent();++ if (raw && typeof raw === "string") {++ content = raw;++ }++ } else {++ // For non-text notes (image, file), use OCR text representation++ content = getTextRepresentationForNote(note) || undefined;++ }++++ if (!content) {+ return "";+ }++ // Handle protected notes+ if (note.isProtected && protectedSessionService.isProtectedSessionAvailable()) {+ try {+ content = protectedSessionService.decryptString(content) || "";+ } catch (e) {+ return ""; // Can't decrypt, don't show content+ }+ } else if (note.isProtected) {+ return ""; // Protected but no session available+ }++ // Strip HTML tags for text notes+ if (note.type === "text") {+ content = striptags(content);+ }++ // Normalize whitespace while preserving paragraph breaks+ // First, normalize multiple newlines to double newlines (paragraph breaks)+ content = content.replace(/\n\s*\n/g, "\n\n");+ // Then normalize spaces within lines+ content = content.split('\n').map(line => line.replace(/\s+/g, " ").trim()).join('\n');+ // Finally trim the whole content+ content = content.trim();++ if (!content) {+ return "";+ }++ // Try to find a snippet around the first matching token+ const normalizedContent = normalizeString(content.toLowerCase());+ let snippetStart = 0;+ let matchFound = false;++ for (const token of searchTokens) {+ const normalizedToken = normalizeString(token.toLowerCase());+ const matchIndex = normalizedContent.indexOf(normalizedToken);++ if (matchIndex !== -1) {+ // Center the snippet around the match+ snippetStart = Math.max(0, matchIndex - maxLength / 2);+ matchFound = true;+ break;+ }+ }++ // Extract snippet+ let snippet = content.substring(snippetStart, snippetStart + maxLength);++ // If snippet contains linebreaks, limit to max 4 lines and override character limit+ const lines = snippet.split('\n');+ if (lines.length > 4) {+ // Find which lines contain the search tokens to ensure they're included+ const normalizedLines = lines.map(line => normalizeString(line.toLowerCase()));+ const normalizedTokens = searchTokens.map(token => normalizeString(token.toLowerCase()));++ // Find the first line that contains a search token+ let firstMatchLine = -1;+ for (let i = 0; i < normalizedLines.length; i++) {+ if (normalizedTokens.some(token => normalizedLines[i].includes(token))) {+ firstMatchLine = i;+ break;+ }+ }++ if (firstMatchLine !== -1) {+ // Center the 4-line window around the first match+ // Try to show 1 line before and 2 lines after the match+ const startLine = Math.max(0, firstMatchLine - 1);+ const endLine = Math.min(lines.length, startLine + 4);+ snippet = lines.slice(startLine, endLine).join('\n');+ } else {+ // No match found in lines (shouldn't happen), just take first 4+ snippet = lines.slice(0, 4).join('\n');+ }+ // Add ellipsis if we truncated lines- snippet = `${snippet }...`;++ snippet = `${snippet}...`;+ } else if (lines.length > 1) {+ // For multi-line snippets that are 4 or fewer lines, keep them as-is+ // No need to truncate+ } else {+ // Single line content - apply original word boundary logic+ // Try to start/end at word boundaries+ if (snippetStart > 0) {+ const firstSpace = snippet.search(/\s/);+ if (firstSpace > 0 && firstSpace < 20) {+ snippet = snippet.substring(firstSpace + 1);+ }+ snippet = `...${snippet}`;+ }++ if (snippetStart + maxLength < content.length) {+ const lastSpace = snippet.search(/\s[^\s]*$/);+ if (lastSpace > snippet.length - 20 && lastSpace > 0) {+ snippet = snippet.substring(0, lastSpace);+ }- snippet = `${snippet }...`;++ snippet = `${snippet}...`;+ }+ }++ return snippet;+ } catch (e) {+ getLog().error(`Error extracting content snippet for note ${noteId}: ${e}`);+ return "";+ }+}++function extractAttributeSnippet(noteId: string, searchTokens: string[], maxLength: number = 200): string {+ const note = becca.notes[noteId];+ if (!note) {+ return "";+ }++ try {+ // Get all attributes for this note+ const attributes = note.getAttributes();+ if (!attributes || attributes.length === 0) {+ return "";+ }++ const matchingAttributes: Array<{name: string, value: string, type: string}> = [];++ // Look for attributes that match the search tokens+ for (const attr of attributes) {+ const attrName = attr.name?.toLowerCase() || "";+ const attrValue = attr.value?.toLowerCase() || "";+ const attrType = attr.type || "";++ // Check if any search token matches the attribute name or value+ const hasMatch = searchTokens.some(token => {+ const normalizedToken = normalizeString(token.toLowerCase());+ return attrName.includes(normalizedToken) || attrValue.includes(normalizedToken);+ });++ if (hasMatch) {+ matchingAttributes.push({+ name: attr.name || "",+ value: attr.value || "",+ type: attrType+ });+ }+ }++ if (matchingAttributes.length === 0) {+ return "";+ }++ // Limit to 4 lines maximum, similar to content snippet logic+ const lines: string[] = [];+ for (const attr of matchingAttributes.slice(0, 4)) {+ let line = "";+ if (attr.type === "label") {+ line = attr.value ? `#${attr.name}="${attr.value}"` : `#${attr.name}`;+ } else if (attr.type === "relation") {+ // For relations, show the target note title if possible+ const targetNote = attr.value ? becca.notes[attr.value] : null;+ const targetTitle = targetNote ? targetNote.title : attr.value;+ line = `~${attr.name}="${targetTitle}"`;+ }++ if (line) {+ lines.push(line);+ }+ }++ let snippet = lines.join('\n');++ // Apply length limit while preserving line structure+ if (snippet.length > maxLength) {+ // Try to truncate at word boundaries but keep lines intact+ const truncated = snippet.substring(0, maxLength);+ const lastNewline = truncated.lastIndexOf('\n');++ if (lastNewline > maxLength / 2) {+ // If we can keep most content by truncating to last complete line+ snippet = truncated.substring(0, lastNewline);+ } else {+ // Otherwise just truncate and add ellipsis+ const lastSpace = truncated.lastIndexOf(' ');+ snippet = truncated.substring(0, lastSpace > maxLength / 2 ? lastSpace : maxLength - 3);+ snippet = `${snippet}...`;+ }+ }++ return snippet;+ } catch (e) {+ getLog().error(`Error extracting attribute snippet for note ${noteId}: ${e}`);+ return "";+ }+}++function searchNotesForAutocomplete(query: string, fastSearch: boolean = true) {+ const searchContext = new SearchContext({+ fastSearch,+ includeArchivedNotes: false,+ includeHiddenNotes: true,+ fuzzyAttributeSearch: true,+ ignoreInternalAttributes: true,+ ancestorNoteId: hoistedNoteService.isHoistedInHiddenSubtree() ? "root" : hoistedNoteService.getHoistedNoteId()+ });++ const allSearchResults = findResultsWithQuery(query, searchContext);++ const trimmed = allSearchResults.slice(0, 200);++ // Extract content and attribute snippets+ for (const result of trimmed) {+ result.contentSnippet = extractContentSnippet(result.noteId, searchContext.highlightedTokens);+ result.attributeSnippet = extractAttributeSnippet(result.noteId, searchContext.highlightedTokens);+ }++ highlightSearchResults(trimmed, searchContext.highlightedTokens, searchContext.ignoreInternalAttributes);++ return trimmed.map((result) => {+ const { title, icon } = becca_service.getNoteTitleAndIcon(result.noteId);+ return {+ notePath: result.notePath,+ noteTitle: title,+ notePathTitle: result.notePathTitle,+ highlightedNotePathTitle: result.highlightedNotePathTitle,+ contentSnippet: result.contentSnippet,+ highlightedContentSnippet: result.highlightedContentSnippet,+ attributeSnippet: result.attributeSnippet,+ highlightedAttributeSnippet: result.highlightedAttributeSnippet,+ icon: icon ?? "bx bx-note"+ };+ });+}++/**+ * @param ignoreInternalAttributes whether to ignore certain attributes from the search such as ~internalLink.+ */+function highlightSearchResults(searchResults: SearchResult[], highlightedTokens: string[], ignoreInternalAttributes = false) {+ highlightedTokens = Array.from(new Set(highlightedTokens));++ // we remove < signs because they can cause trouble in matching and overwriting existing highlighted chunks+ // which would make the resulting HTML string invalid.+ // { and } are used for marking <b> and </b> tag (to avoid matches on single 'b' character)+ // < and > are used for marking <small> and </small>+ highlightedTokens = highlightedTokens.map((token) => token.replace(/[<>{}]/g, "")).filter((token) => !!token?.trim());++ // sort by the longest, so we first highlight the longest matches+ highlightedTokens.sort((a, b) => (a.length > b.length ? -1 : 1));++ for (const result of searchResults) {+ result.highlightedNotePathTitle = result.notePathTitle.replace(/[<{}]/g, "");++ // Initialize highlighted content snippet+ if (result.contentSnippet) {+ // Escape HTML but preserve newlines for later conversion to <br>+ result.highlightedContentSnippet = escapeHtml(result.contentSnippet);+ // Remove any stray < { } that might interfere with our highlighting markers+ result.highlightedContentSnippet = result.highlightedContentSnippet.replace(/[<{}]/g, "");+ }++ // Initialize highlighted attribute snippet+ if (result.attributeSnippet) {+ // Escape HTML but preserve newlines for later conversion to <br>+ result.highlightedAttributeSnippet = escapeHtml(result.attributeSnippet);+ // Remove any stray < { } that might interfere with our highlighting markers+ result.highlightedAttributeSnippet = result.highlightedAttributeSnippet.replace(/[<{}]/g, "");+ }+ }++ function wrapText(text: string, start: number, length: number, prefix: string, suffix: string) {+ return text.substring(0, start) + prefix + text.substr(start, length) + suffix + text.substring(start + length);+ }++ for (const token of highlightedTokens) {+ if (!token) {+ // Avoid empty tokens, which might cause an infinite loop.+ continue;+ }++ for (const result of searchResults) {+ // Reset token+ const tokenRegex = new RegExp(escapeRegExp(token), "gi");+ let match;++ // Highlight in note path title+ if (result.highlightedNotePathTitle) {+ const titleRegex = new RegExp(escapeRegExp(token), "gi");+ while ((match = titleRegex.exec(normalizeString(result.highlightedNotePathTitle))) !== null) {+ result.highlightedNotePathTitle = wrapText(result.highlightedNotePathTitle, match.index, token.length, "{", "}");+ // 2 characters are added, so we need to adjust the index+ titleRegex.lastIndex += 2;+ }+ }++ // Highlight in content snippet+ if (result.highlightedContentSnippet) {+ const contentRegex = new RegExp(escapeRegExp(token), "gi");+ while ((match = contentRegex.exec(normalizeString(result.highlightedContentSnippet))) !== null) {+ result.highlightedContentSnippet = wrapText(result.highlightedContentSnippet, match.index, token.length, "{", "}");+ // 2 characters are added, so we need to adjust the index+ contentRegex.lastIndex += 2;+ }+ }++ // Highlight in attribute snippet+ if (result.highlightedAttributeSnippet) {+ const attributeRegex = new RegExp(escapeRegExp(token), "gi");+ while ((match = attributeRegex.exec(normalizeString(result.highlightedAttributeSnippet))) !== null) {+ result.highlightedAttributeSnippet = wrapText(result.highlightedAttributeSnippet, match.index, token.length, "{", "}");+ // 2 characters are added, so we need to adjust the index+ attributeRegex.lastIndex += 2;+ }+ }+ }+ }++ for (const result of searchResults) {+ if (result.highlightedNotePathTitle) {+ result.highlightedNotePathTitle = result.highlightedNotePathTitle.replace(/{/g, "<b>").replace(/}/g, "</b>");+ }++ if (result.highlightedContentSnippet) {+ // Replace highlighting markers with HTML tags+ result.highlightedContentSnippet = result.highlightedContentSnippet.replace(/{/g, "<b>").replace(/}/g, "</b>");+ // Convert newlines to <br> tags for HTML display+ result.highlightedContentSnippet = result.highlightedContentSnippet.replace(/\n/g, "<br>");+ }++ if (result.highlightedAttributeSnippet) {+ // Replace highlighting markers with HTML tags+ result.highlightedAttributeSnippet = result.highlightedAttributeSnippet.replace(/{/g, "<b>").replace(/}/g, "</b>");+ // Convert newlines to <br> tags for HTML display+ result.highlightedAttributeSnippet = result.highlightedAttributeSnippet.replace(/\n/g, "<br>");+ }+ }+}++export default {+ searchFromNote,+ searchNotesForAutocomplete,+ findResultsWithQuery,+ findFirstNoteWithQuery,+ searchNotes,+ extractContentSnippet,+ extractAttributeSnippet,+ highlightSearchResults+};diff --cc pnpm-lock.yamlindex 5bbc8df6b1,abd7ec647e..8cde2fde17--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@@ -149,22 -171,15 +171,22 @@@ importersversion: 2.0.1vite:specifier: 8.0.3- version: 8.0.3(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 8.0.3(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vite-plugin-dts:specifier: 4.5.4- version: 4.5.4(@types/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 4.5.4(@types/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))vitest:specifier: 4.1.2- version: 4.1.2(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected]([email protected])([email protected]))([email protected]([email protected])([email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 4.1.2(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected]([email protected])([email protected]))([email protected]([email protected])([email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))apps/build-docs:+ dependencies:+ '@triliumnext/core':+ specifier: workspace:*+ version: link:../../packages/trilium-core+ '@triliumnext/server':+ specifier: workspace:*+ version: link:../serverdevDependencies:'@redocly/cli':specifier: 2.25.3@@@ -411,226 -426,9 +433,226 @@@specifier: 0.7.2version: 0.7.2vite-plugin-static-copy:- specifier: 3.4.0- version: 3.4.0([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ specifier: 4.0.0+ version: 4.0.0([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ apps/client-standalone:+ dependencies:+ '@excalidraw/excalidraw':+ specifier: 0.18.0+ version: 0.18.0(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])+ '@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.6.0+ version: 2.6.0+ 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: 25.10.10- version: 25.10.10([email protected])++ version: 25.10.10([email protected])+ i18next-http-backend:+ specifier: 3.0.2+ version: 3.0.2([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.44+ version: 0.16.44+ 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: 17.0.5+ version: 17.0.5+ mermaid:+ specifier: 11.13.0+ version: 11.13.0+ mind-elixir:+ specifier: 5.9.3+ version: 5.9.3+ normalize.css:+ specifier: 8.0.1+ version: 8.0.1+ panzoom:+ specifier: 9.4.4+ version: 9.4.4+ preact:+ specifier: 10.29.0+ version: 10.29.0+ react-i18next:+ specifier: 17.0.0- version: 17.0.0([email protected]([email protected]))([email protected]([email protected]))([email protected])([email protected])++ version: 17.0.0([email protected]([email protected]))([email protected]([email protected]))([email protected])([email protected])+ react-window:+ specifier: 2.2.7+ reveal.js:+ specifier: 6.0.0+ version: 6.0.0+ 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- version: 2.10.2(@babel/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))++ version: 2.10.2(@babel/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ '@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- version: 14.0.0([email protected]([email protected]))++ version: 14.0.0([email protected]([email protected]))+ cross-env:+ specifier: 7.0.3+ version: 7.0.3+ happy-dom:+ specifier: 20.8.9+ version: 20.8.9([email protected])([email protected])+ script-loader:+ specifier: 0.7.2+ version: 0.7.2+ vite-plugin-static-copy:+ specifier: 3.4.0- version: 3.4.0([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))++ version: 3.4.0([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+apps/db-compare:dependencies:colors:@@@ -804,6 -599,18 +829,12 @@@html-to-text:specifier: 9.0.5version: 9.0.5+ 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])devDependencies:'@braintree/sanitize-url':specifier: 7.1.2@@@ -859,6 -669,12 +890,9 @@@'@types/ini':specifier: 4.1.1version: 4.1.1+ '@types/js-yaml':+ specifier: 4.0.9+ version: 4.0.9- '@types/mime-types':- specifier: 3.0.1- version: 3.0.1'@types/multer':specifier: 2.1.0version: 2.1.0@@@ -1039,9 -888,15 +1079,9 @@@turnish:specifier: 1.8.0version: 1.8.0- unescape:- specifier: 1.0.1- version: 1.0.1vite:specifier: 8.0.3- version: 8.0.3(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 8.0.3(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])- ws:- specifier: 8.20.0- version: 8.20.0([email protected])([email protected])xml2js:specifier: 0.6.2version: 0.6.2@@@ -1696,77 -1494,19 +1679,74 @@@devDependencies:'@rollup/plugin-buble':specifier: 1.0.3- version: 1.0.3([email protected])- karma:- specifier: 6.4.4- version: 6.4.4([email protected])([email protected])- karma-chrome-launcher:- specifier: 3.2.0- version: 3.2.0- karma-firefox-launcher:- specifier: 2.1.3- version: 2.1.3- karma-jasmine:- specifier: 5.1.0+ version: 1.0.3([email protected])+ happy-dom:+ specifier: 20.8.9+ version: 20.8.9([email protected])([email protected])+ vitest:+ specifier: 4.1.2+ version: 4.1.2(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected]([email protected])([email protected]))([email protected]([email protected])([email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ 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: 25.10.10- version: 25.10.10([email protected])++ version: 25.10.10([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/turndown-plugin-gfm:devDependencies:+ happy-dom:+ specifier: 20.8.9+ version: 20.8.9([email protected])([email protected])turndown:specifier: 7.2.2version: 7.2.2@@@ -6551,12 -5649,6 +5902,9 @@@ packages'@types/[email protected]':resolution: {integrity: sha512-H/+L+UkTV33uf49PH5pCAUBVPNj2nDBXTN+qS1dOwyyg24l3CcicicCA7ca+HMvJBZcFgl5r8e+RR6elsb4Lyw==}- '@types/[email protected]':- resolution: {integrity: sha512-XISRgDJ2Tc5q4TRqvgJtzsRkFYNJzZrhTdtMoGVBttwzzQJkPnS3WWTFc7kuDRoPtPakl+T+OfdEUjYJj7Jbow==}-+ '@types/[email protected]':+ resolution: {integrity: sha512-U6wdIeFZPR77zjaZCrFNPzKjjfdFr4Dj0WUAZ+UYgXGjwqYCnjpCngeS0hb+28FLL0QzE9jXBikvB7xxAQi5sg==}+'@types/[email protected]':resolution: {integrity: sha512-kK/IM1+pvwCMom+Kezt/UlP8LMEwm8rP6UgGbRc6zUnhU/csoBQ5rWgmD2CJuHxiMiX+H1VqPGpo0kDluJGXYA==}@@@ -8724,9 -7713,9 +7969,12 @@@engines: {node: '>=10.14', npm: '>=6', yarn: '>=1'}hasBin: true+ resolution: {integrity: sha512-e4a5N8lVvuLgAWgnCrLr2PP0YyDOTHa9H/Rj54dirp61qXnNq46m82bRhNqIA5VccJtWBvPTFRV3TtvHUKPB1g==}++ resolution: {integrity: sha512-uKm5PU+MHTootlWEY+mZ4vvXoCn4fLQxT9dSc1sXVMSFkINTJVN8cAQROpwcKm8bJ/c7rgZVIBWzH5T78sNZZw==}+resolution: {integrity: sha512-VqCUuhcd1iB+dsv8gxPttb5iZh/D0iubSP21g36KXdEuf6I5JiioesUVjpCdHV9MZRUfVFlvwtIUyPfxo5trtw==}engines: {node: '>=4.8'}@@@ -10691,28 -9499,20 +9758,31 @@@resolution: {integrity: sha512-Fl70vYtsAFb/C06PTS9dZBo7ihau+Tu/DNCk/OyHhea07S+aeMWpFFkUaXRa8fI+ScZbEI8dfSxwY7gxZ9SAVQ==}- resolution: {integrity: sha512-Y93lCzHYgGWdrJ66yIktxiaGULYc6oGiABxhcO5AufBeOyoIdZF7bIfLaOrbM0iGIOXQQgxxRrFEnb+Y6w1n4A==}- engines: {node: '>=10.18'}-- resolution: {integrity: sha512-eYWTX7QT7kJ0sZyCPK6x1q+R63zvNKv2D6UdbMf15A8vNb2ZLyw4NNNZxPFwXlIv/U+oUtg8SakW6ZgJZcoqHQ==}+ resolution: {integrity: sha512-/5aW996nbolGh/qVU9urjAJ2QiXpiyGuhG8x/ZvvZQ3bMlrK+ouUdD6whS4e+sU9CCdUIzl7x/heEjsBh/3xtw==}+ resolution: {integrity: sha512-PdlvPnvIp4E1sYi46Ik4tBYh/v/NbYfFFgTjkwFl0is8A18s7/bx9aXqsrOax9WUbeNS6mD2oix7Z0yGGf6m5g==}++ resolution: {integrity: sha512-udwrBIE6cNpqn1gRAqRULq3+7MzIIuaiKRWrz++dVz5SqWW2VwXmPJtAgkI0JtMLFaADC9qNmnZAxWAhsxXx2g==}++ resolution: {integrity: sha512-cqUW2Z3EkRx7NqSyywjkgCLK7KLCL6IFVFcONG7nVYIJ3ekZ1/N5jUsihHV6Bq37NfhgtczxJcxduELtjTwkuQ==}+ peerDependencies:+ typescript: ^5 || ^6+ peerDependenciesMeta:+ typescript:+ optional: true++ resolution: {integrity: sha512-1571kXINxHKY7LksWp8wP+zP0YqHSSpl/OW0Y0owFEf2H3s8gCAffWaZivcz14rMkOvn3R/psiQxVsR9t2Nafg==}+ peerDependencies:+ typescript: ^5 || ^6+ peerDependenciesMeta:+ typescript:+ optional: true+resolution: {integrity: sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==}engines: {node: '>=0.10.0'}@@@ -11458,13 -10169,6 +10451,9 @@@resolution: {integrity: sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w==}engines: {node: '>=6'}- resolution: {integrity: sha512-dhG34DXATL5hSxJbIexCft8FChFXtmskoZYnoPWjXQuebWYCNkVeV3KkGegCK9CP1oswI/vQibS2GY7Em/sJJA==}- engines: {node: '>= 8'}-+ resolution: {integrity: sha512-wRJ9I4az0QcsH7A4v4l0enUpkS++MBx0BnL/68KaLzJg7x1qmbjSlwEoCNol7KTYZ+pmtI7Eh2J0Nu6/2Z5J/Q==}+resolution: {integrity: sha512-Y+60/zizpJ3HRH8DCss+q95yr6145JXZo46OTpFvDZWLfRCE4qChOyk1b26nMaNpfHHgxagk9dXT5OP0Tfe+dQ==}@@@ -12138,18 -10804,6 +11089,9 @@@resolution: {integrity: sha512-AY/tDXz8stMbx0MIutdn63Dz0uwY1VVMKIxCqOOA2hg5WGdCGm2qqEZF498deLDxoZbL+hDf1SwBWzvWADBoPA==}+ resolution: {integrity: sha512-OTTO6ofvDuzN4fxuBngqhQLJmIqModr2NgQb4OY+5DGRt54B+YNAvNnlspYwUXXGq2Rbht1DhXgeU4dr4CUy6Q==}+- resolution: {integrity: sha512-ZWYT7ln73Hptxqxk2DxPU9MmapXRhxkJD6tkSR04dnQxm8BGu2hzgKLugK5yySD97u/8yy7Ma7E76k9ZdvtjkQ==}- engines: {node: '>= 12.13.0'}- peerDependencies:- webpack: ^5.0.0-- resolution: {integrity: sha512-UtJcAD4yEaGtjPezWuO9wC4nwUnVH/8/Im3yEHQP4b67cXlD/Qr9hdITCU1xDbSEXg2XKNaP8jsReV7vQd00/A==}-resolution: {integrity: sha512-oRjTw/97aTBN0RHbYCdtF1MQfvusSIBQM0IZEgzl6426+8jSC0nF1a/GmnVLpfB9yyr6g6FTqWqiZVbxrtaCIg==}engines: {node: 18 || 20 || >=22}@@@ -13641,24 -12091,8 +12374,24 @@@peerDependencies:react: ^19.2.4+ resolution: {integrity: sha512-L7aqwOePCExt6nlF7000lN2YKWnR7IpSpQId9sj01798Xn3LAncBdTHKl9lA/nr+YrG78BTqWPJxq9mlrrmH7Q==}+ peerDependencies:+ i18next: '>= 25.10.10'+ 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-iG65FGnFHcYyHNuT01ukffYWCOBFTWSdVD8EZd/dCVWgtjFPObcSsvYYNwcsokO/rDcTb5d6D8Acv8MrOdm6Hw==}+ resolution: {integrity: sha512-shBftH2vaTWK2Bsp7FiL+cevx3xFJlvFxmsDFQSrJc+6twHkP0tv/bGa01VVWzpreUVVwU+3Hev5iFqRg65RwA==}peerDependencies:i18next: '>= 26.0.1'react: '>= 16.8.0'@@@ -15694,12 -13958,12 +14257,18 @@@vite:optional: true+ resolution: {integrity: sha512-ekryzCw0ouAOE8tw4RvVL/dfqguXzumsV3FBKoKso4MQ1MUUrUXtl5RI4KpJQUNGqFEsg9kxl4EvDl02YtA9VQ==}+ engines: {node: ^18.0.0 || >=20.0.0}+ peerDependencies:+ vite: ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0++ resolution: {integrity: sha512-TTf6cVTV4M2pH2Wfr3zhevdRsIQezfm2ltDkSfkjqvvdryJHYQyNoPISvuytX3r9jFZV0yVeMYyGTsAvAH2XLw==}+ engines: {node: ^22.0.0 || >=24.0.0}+ peerDependencies:+ vite: ^6.0.0 || ^7.0.0 || ^8.0.0+resolution: {integrity: sha512-WaiOUlmt1fKw1w/WWJnx9gVk42D1BASKZmGCPpy6iTLE5iIemN2lim3MwI7Rffyt3aQnPrLfLSLnI8ZUJ9s49g==}peerDependencies:@@@ -20329,12 -17679,30 +17986,34 @@@ snapshotsdependencies:mind-elixir: 5.10.0+ '@mind-elixir/[email protected]([email protected])':+ dependencies:+ mind-elixir: 5.9.3+'@mixmark-io/[email protected]': {}+ '@modelcontextprotocol/[email protected]([email protected])':+ dependencies:+ '@hono/node-server': 1.19.12([email protected])+ ajv: 8.18.0+ ajv-formats: 3.0.1([email protected])+ content-type: 1.0.5+ cors: 2.8.5+ cross-spawn: 7.0.6+ eventsource: 3.0.7+ eventsource-parser: 3.0.6+ express: 5.2.1+ express-rate-limit: 8.3.2([email protected])+ hono: 4.12.9+ jose: 6.2.2+ json-schema-typed: 8.0.2+ pkce-challenge: 5.0.1+ raw-body: 3.0.2+ zod: 4.3.6+ zod-to-json-schema: 3.25.2([email protected])+ transitivePeerDependencies:+ - supports-color+'@mswjs/[email protected]':dependencies:'@open-draft/deferred-promise': 2.2.0@@@ -20695,23 -18002,7 +18313,23 @@@'@popperjs/[email protected]': {}- '@preact/[email protected](@babel/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))':++ '@preact/[email protected](@babel/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([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])- '@prefresh/vite': 2.4.12([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))++ '@prefresh/vite': 2.4.12([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ '@rollup/pluginutils': 4.2.1+ babel-plugin-transform-hook-names: 1.0.2(@babel/[email protected])- debug: 4.4.3([email protected])++ debug: 4.4.3+ picocolors: 1.1.1- vite: 8.0.3(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])- vite-prerender-plugin: 0.5.11([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))++ vite: 8.0.3(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])++ vite-prerender-plugin: 0.5.11([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ transitivePeerDependencies:+ - preact+ - supports-color+- '@preact/[email protected](@babel/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))':+ '@preact/[email protected](@babel/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))':dependencies:'@babel/core': 7.29.0'@babel/plugin-transform-react-jsx': 7.27.1(@babel/[email protected])@@@ -22816,10 -19780,6 +20109,8 @@@dependencies:'@types/node': 24.12.0- '@types/[email protected]': {}-+ '@types/[email protected]': {}+'@types/[email protected]': {}'@types/[email protected]':@@@ -24853,12 -21850,8 +22177,10 @@@'@zip.js/[email protected]': {}+ '@zumer/[email protected]': {}+'@zumer/[email protected]': {}- [email protected]: {}-@@@ -26258,12 -23109,12 +23438,18 @@@dependencies:cross-spawn: 7.0.6+ dependencies:+ node-fetch: 2.7.0([email protected])+ transitivePeerDependencies:+ - encoding++ dependencies:+ node-fetch: 2.7.0([email protected])+ transitivePeerDependencies:+ - encoding+dependencies:nice-try: 1.0.5@@@ -28900,22 -25460,20 +25795,32 @@@dependencies:ms: 2.1.3- [email protected]: {}-- [email protected]: {}+ [email protected]: {}+ dependencies:+ cross-fetch: 4.0.0([email protected])+ transitivePeerDependencies:+ - encoding++ dependencies:+ cross-fetch: 4.1.0([email protected])+ transitivePeerDependencies:+ - encoding++ dependencies:+ '@babel/runtime': 7.29.2+ optionalDependencies:+ typescript: 6.0.2++ dependencies:+ '@babel/runtime': 7.29.2+ optionalDependencies:+ typescript: 6.0.2+dependencies:safer-buffer: 2.1.2@@@ -29631,10 -26066,6 +26421,8 @@@- [email protected]: {}-+ [email protected]: {}+@@@ -30583,27 -26929,9 +27286,11 @@@+ [email protected]: {}+- [email protected]([email protected](@swc/[email protected](@swc/[email protected]))([email protected])):- dependencies:- schema-utils: 4.3.2- tapable: 2.2.3-- [email protected]: {}-dependencies:- brace-expansion: 5.0.2-- dependencies:- brace-expansion: 1.1.12-- dependencies:- brace-expansion: 1.1.12+ brace-expansion: 5.0.5dependencies:@@@ -32208,18 -28288,7 +28645,18 @@@react: 19.2.4scheduler: 0.27.0- [email protected]([email protected]([email protected]))([email protected]([email protected]))([email protected])([email protected]):++ [email protected]([email protected]([email protected]))([email protected]([email protected]))([email protected])([email protected]):+ dependencies:+ '@babel/runtime': 7.29.2+ html-parse-stringify: 3.0.1- i18next: 25.10.10([email protected])++ i18next: 25.10.10([email protected])+ react: 19.2.4+ use-sync-external-store: 1.6.0([email protected])+ optionalDependencies:+ react-dom: 19.2.4([email protected])- typescript: 5.9.3++ typescript: 6.0.2+- [email protected]([email protected]([email protected]))([email protected]([email protected]))([email protected])([email protected]):+ [email protected]([email protected]([email protected]))([email protected]([email protected]))([email protected])([email protected]):dependencies:'@babel/runtime': 7.29.2html-parse-stringify: 3.0.1@@@ -34694,7 -30475,7 +30843,15 @@@- rollup- supports-color- [email protected]([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):++ [email protected]([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):++ dependencies:++ chokidar: 3.6.0++ p-map: 7.0.4++ picocolors: 1.1.1++ tinyglobby: 0.2.15++ vite: 8.0.3(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+++ [email protected]([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):dependencies:chokidar: 3.6.0p-map: 7.0.4