docs(dev): integrate some of the architecture notes

This commit is contained in:
Elian Doran
2025-11-04 15:51:54 +02:00
parent 579b2ce76e
commit 58ac325634
67 changed files with 1428 additions and 1353 deletions

View File

@@ -36,7 +36,7 @@ class="image image_resized" style="width:74.04%;">
<p>To see what embedding models Ollama has available, you can check out
<a
href="https://ollama.com/search?c=embedding">this search</a>on their website, and then <code>pull</code> whichever one
you want to try out. As of 4/15/25, my personal favorite is <code>mxbai-embed-large</code>.</p>
you want to try out. A popular choice is <code>mxbai-embed-large</code>.</p>
<p>First, we'll need to select the Ollama provider from the tabs of providers,
then we will enter in the Base URL for our Ollama. Since our Ollama is
running on our local machine, our Base URL is <code>http://localhost:11434</code>.

View File

@@ -8,7 +8,7 @@
<li>
<p><a class="reference-link" href="#root/_help_HI6GBBIduIgv">Labels</a>&nbsp;can
be used for a variety of purposes, such as storing metadata or configuring
the behaviour of notes. Labels are also searchable, enhancing note retrieval.</p>
the behavior of notes. Labels are also searchable, enhancing note retrieval.</p>
<p>For more information, including predefined labels, see&nbsp;<a class="reference-link"
href="#root/_help_HI6GBBIduIgv">Labels</a>.</p>
</li>
@@ -21,7 +21,7 @@
class="reference-link" href="#root/_help_Cq5X6iKQop6R">Relations</a>.</p>
</li>
</ol>
<p>These attributes play a crucial role in organizing, categorising, and
<p>These attributes play a crucial role in organizing, categorizing, and
enhancing the functionality of notes.</p>
<h2>Viewing the list of attributes</h2>
<p>Both the labels and relations for the current note are displayed in the <em>Owned Attributes</em> section

View File

@@ -11,7 +11,7 @@ const {secret, title, content} = req.body;
if (req.method == 'POST' &amp;&amp; secret === 'secret-password') {
// notes must be saved somewhere in the tree hierarchy specified by a parent note.
// This is defined by a relation from this code note to the "target" parent note
// alternetively you can just use constant noteId for simplicity (get that from "Note Info" dialog of the desired parent note)
// alternatively you can just use constant noteId for simplicity (get that from "Note Info" dialog of the desired parent note)
const targetParentNoteId = api.currentNote.getRelationValue('targetNote');
const {note} = api.createTextNote(targetParentNoteId, title, content);
@@ -30,7 +30,7 @@ else {
be saved</li>
</ul>
<h3>Explanation</h3>
<p>Let's test this by using an HTTP client to send a request:</p><pre><code class="language-text-x-trilium-auto">POST http://my.trilium.org/custom/create-note
<p>Let's test this by using an HTTP client to send a request:</p><pre><code class="language-text-x-trilium-auto">POST http://your-trilium-server/custom/create-note
Content-Type: application/json
{
@@ -64,12 +64,12 @@ Content-Type: application/json
can always look into its <a href="https://expressjs.com/en/api.html">documentation</a> for
details.</p>
<h3>Parameters</h3>
<p>REST request paths often contain parameters in the URL, e.g.:</p><pre><code class="language-text-x-trilium-auto">http://my.trilium.org/custom/notes/123</code></pre>
<p>REST request paths often contain parameters in the URL, e.g.:</p><pre><code class="language-text-x-trilium-auto">http://your-trilium-server/custom/notes/123</code></pre>
<p>The last part is dynamic so the matching of the URL must also be dynamic
- for this reason the matching is done with regular expressions. Following <code>customRequestHandler</code> value
would match it:</p><pre><code class="language-text-x-trilium-auto">notes/([0-9]+)</code></pre>
<p>Additionally, this also defines a matching group with the use of parenthesis
which then makes it easier to extract the value. The matched groups are
available in <code>api.pathParams</code>:</p><pre><code class="language-text-x-trilium-auto">const noteId = api.pathParams[0];</code></pre>
<p>Often you also need query params (as in e.g. <code>http://my.trilium.org/custom/notes?noteId=123</code>),
<p>Often you also need query params (as in e.g. <code>http://your-trilium-server/custom/notes?noteId=123</code>),
you can get those with standard express <code>req.query.noteId</code>.</p>

View File

@@ -21,7 +21,7 @@
<ol>
<li>Set the text to search for in the <em>Search string</em> field.
<ol>
<li>Apart from searching for words ad-literam, there is also the possibility
<li>Apart from searching for words literally, there is also the possibility
to search for attributes or properties of notes.</li>
<li>See the examples below for more information.</li>
</ol>

View File

@@ -31,7 +31,7 @@
and you will see a list of all modified notes including the deleted ones.
Notes available for undeletion have a link to do so. This is kind of "trash
can" functionality known from e.g. Windows.</p>
<p>Clicking an undelete will recover the note, it's content and attributes
<p>Clicking an undelete will recover the note, its content and attributes
- note should be just as before being deleted. This action will also undelete
note's children which have been deleted in the same action.</p>
<p>To be able to undelete a note, it is necessary that deleted note's parent

View File

@@ -29,7 +29,7 @@
<li><em><strong>Editable</strong></em> changes whether the current note:
<ul>
<li>Enters <a href="#root/_help_CoFPLs3dRlXc">read-only mode</a> automatically if
the note is too big (default behaviour).</li>
the note is too big (default behavior).</li>
<li>Is always in read-only mode (however it can still be edited temporarily).</li>
<li>Is always editable, regardless of its size.</li>
</ul>

View File

@@ -1,5 +1,5 @@
<p>Collections are a unique type of notes that don't have a content, but
instead display its child notes in various presentation methods.</p>
<p>Collections are a unique type of note that don't have content, but instead
display their child notes in various presentation methods.</p>
<h2>Main collections</h2>
<table>
<thead>
@@ -94,7 +94,7 @@
in the&nbsp;<a class="reference-link" href="#root/_help_BlN9DFI679QC">Ribbon</a>.</p>
<h2>Archived notes</h2>
<p>By default, <a href="#root/_help_MKmLg5x6xkor">archived notes</a> will not be
shown in collections. This behaviour can be changed by going to <em>Collection Properties</em> in
shown in collections. This behavior can be changed by going to <em>Collection Properties</em> in
the&nbsp;<a class="reference-link" href="#root/_help_BlN9DFI679QC">Ribbon</a>&nbsp;and
checking <em>Show archived notes</em>.</p>
<p>Archived notes will be generally indicated by being greyed out as opposed

View File

@@ -27,6 +27,6 @@
any startup scripts that might cause the application to crash.</li>
</ul>
<h2>Synchronization</h2>
<p>For Trilium desktp users who wish to synchronize their data with a server
<p>For Trilium desktop users who wish to synchronize their data with a server
instance, refer to the&nbsp;<a class="reference-link" href="#root/_help_cbkrhQjrkKrh">Synchronization</a>&nbsp;guide
for detailed instructions.</p>

View File

@@ -40,7 +40,7 @@
<h3>Disabling / Modifying the Upload Limit</h3>
<p>If you're running into the 250MB limit imposed on the server by default,
and you'd like to increase the upload limit, you can set the <code>TRILIUM_NO_UPLOAD_LIMIT</code> environment
variable to <code>true</code> disable it completely:</p><pre><code class="language-text-x-trilium-auto">export TRILIUM_NO_UPLOAD_LIMIT=true </code></pre>
variable to <code>true</code> to disable it completely:</p><pre><code class="language-text-x-trilium-auto">export TRILIUM_NO_UPLOAD_LIMIT=true </code></pre>
<p>Or, if you'd simply like to <em>increase</em> the upload limit size to something
beyond 250MB, you can set the <code>MAX_ALLOWED_FILE_SIZE_MB</code> environment
variable to something larger than the integer <code>250</code> (e.g. <code>450</code> in

View File

@@ -1,5 +1,5 @@
<p>One core features of Trilium is that it supports multiple types of notes,
depending on the need.</p>
<p>One of the core features of Trilium is that it supports multiple types
of notes, depending on the need.</p>
<h2>Creating a new note with a different type via the note tree</h2>
<p>The default note type in Trilium (e.g. when creating a new note) is&nbsp;
<a

View File

@@ -3,7 +3,7 @@
it. Special case is JavaScript code notes which can also be executed inside
Trilium which can in conjunction with&nbsp;<a class="reference-link" href="#root/_help_GLks18SNjxmC">Script API</a>&nbsp;provide
extra functionality.</p>
<h2>Scripting</h2>
<h2>Architecture Overview</h2>
<p>To go further I must explain basic architecture of Trilium - in its essence
it is a classic web application - it has these two main components:</p>
<ul>
@@ -14,8 +14,8 @@
</ul>
<p>So we have frontend and backend, each with their own set of responsibilities,
but their common feature is that they both run JavaScript code. Add to
this the fact, that we're able to create JavaScript [[code notes]] and
we're onto something.</p>
this the fact, that we're able to create JavaScript <a class="reference-link"
href="#root/_help_6f9hih2hXXZk">code notes</a> and we're onto something.</p>
<h2>Use cases</h2>
<ul>
<li><a class="reference-link" href="#root/_help_TjLYAo3JMO8X">"New Task" launcher button</a>

View File

@@ -16,11 +16,11 @@
module.exports = new MyWidget();</code></pre>
<p>To implement this widget:</p>
<ol>
<li data-list-item-id="ee416db068caeb5aebc3edf8d313cdbbf">Create a new <code>JS Frontend</code> note in Trilium and paste in the code
<li>Create a new <code>JS Frontend</code> note in Trilium and paste in the code
above.</li>
<li data-list-item-id="ec82d101a82bd1bdbbc180294534aecaa">Assign the <code>#widget</code> <a href="#root/_help_zEY4DaJG4YT5">attribute</a> to
<li>Assign the <code>#widget</code> <a href="#root/_help_zEY4DaJG4YT5">attribute</a> to
the <a href="#root/_help_BFs8mudNFgCS">note</a>.</li>
<li data-list-item-id="ee1c3b9d316a04a986cc0be3b57d4c569">Restart Trilium or reload the window.</li>
<li>Restart Trilium or reload the window.</li>
</ol>
<p>To verify that the widget is working, open the developer tools (<code>Cmd</code> + <code>Shift</code> + <code>I</code>)
and run <code>document.querySelector("#my-widget")</code>. If the element
@@ -89,16 +89,15 @@ module.exports = new MyWidget();</code></pre>
module.exports = new MyWidget();</code></pre>
<p><code>parentWidget()</code> can be given the following values:</p>
<ul>
<li data-list-item-id="ebf9bc7b43e420c012d4c72b3b95a8cf0"><code>left-pane</code> - This renders the widget on the left side of the
<li><code>left-pane</code> - This renders the widget on the left side of the
screen where the note tree lives.</li>
<li data-list-item-id="ec6ca6cd1ed1b9157edc99a61e4b9f336"><code>center-pane</code> - This renders the widget in the center of the
<li><code>center-pane</code> - This renders the widget in the center of the
layout in the same location that notes and splits appear.</li>
<li data-list-item-id="e8575696a825b1dce0a62a3ffb6b59ae8"><code>note-detail-pane</code> - This renders the widget <em>with</em> the
<li><code>note-detail-pane</code> - This renders the widget <em>with</em> the
note in the center pane. This means it can appear multiple times with splits.</li>
<li
data-list-item-id="e064dfaa93f31a16d42c10c4c45d903be"><code>right-pane</code> - This renders the widget to the right of any opened
<li><code>right-pane</code> - This renders the widget to the right of any opened
notes.</li>
</ul>
<p><a href="#root/pOsGYCXsbNQG/BgmBlOIl72jZ/_help_s8alTXmpFR61">Reload</a> the application
one last time. When you click the button, a "Hello World!" message should
appear, confirming that your widget is fully functional.</p>
<p><a href="#root/_help_s8alTXmpFR61">Reload</a> the application one last time.
When you click the button, a "Hello World!" message should appear, confirming
that your widget is fully functional.</p>

View File

@@ -1,4 +1,5 @@
<p>As Trilium is currently in beta, encountering bugs is to be expected.</p>
<p>While Trilium is actively maintained and stable, encountering bugs is
possible.</p>
<h2>General Quick Fix</h2>
<p>The first step in troubleshooting is often a restart.</p>
<p>If you experience an UI issue, the frontend may have entered an inconsistent
@@ -15,7 +16,7 @@
variable to reset the open tabs to a single specified note ID (e.g., <code>root</code>).
In Linux, you can set it as follows:</p><pre><code class="language-text-x-trilium-auto">TRILIUM_START_NOTE_ID=root ./trilium</code></pre>
<h2>Broken Script Prevents Application Startup</h2>
<p>If a custom script causes Triliumto crash, and it is set as a startup
<p>If a custom script causes Trilium to crash, and it is set as a startup
script or in an active <a href="#root/_help_MgibgPcfeuGz">custom widget</a>, start
Triliumin "safe mode" to prevent any custom scripts from executing:</p><pre><code class="language-text-x-trilium-auto">TRILIUM_SAFE_MODE=true ./trilium</code></pre>
<p>Depending on your Trilium distribution, you may have pre-made scripts

742
docs/ARCHITECTURE.md vendored
View File

@@ -1,741 +1,5 @@
# Trilium Notes - Technical Architecture Documentation
> **Version:** 0.99.3
> **Last Updated:** November 2025
> **Maintainer:** TriliumNext Team
## Table of Contents
1. [Introduction](#introduction)
2. [High-Level Architecture](#high-level-architecture)
3. [Monorepo Structure](#monorepo-structure)
4. [Core Architecture Patterns](#core-architecture-patterns)
5. [Data Layer](#data-layer)
6. [Caching System](#caching-system)
7. [Frontend Architecture](#frontend-architecture)
8. [Backend Architecture](#backend-architecture)
9. [API Architecture](#api-architecture)
10. [Build System](#build-system)
11. [Testing Strategy](#testing-strategy)
12. [Security Architecture](#security-architecture)
13. [Related Documentation](#related-documentation)
---
## Introduction
Trilium Notes is a hierarchical note-taking application built as a TypeScript monorepo. It supports multiple deployment modes (desktop, server, mobile web) and features advanced capabilities including synchronization, scripting, encryption, and rich content editing.
### Key Characteristics
- **Monorepo Architecture**: Uses pnpm workspaces for dependency management
- **Multi-Platform**: Desktop (Electron), Server (Node.js/Express), and Mobile Web
- **TypeScript-First**: Strong typing throughout the codebase
- **Plugin-Based**: Extensible architecture for note types and UI components
- **Offline-First**: Full functionality without network connectivity
- **Synchronization-Ready**: Built-in sync protocol for multi-device usage
### Technology Stack
- **Runtime**: Node.js (backend), Browser/Electron (frontend)
- **Language**: TypeScript, JavaScript
- **Database**: SQLite (better-sqlite3)
- **Build Tools**: Vite, ESBuild, pnpm
- **UI Framework**: Custom widget-based system
- **Rich Text**: CKEditor 5 (customized)
- **Code Editing**: CodeMirror 6
- **Desktop**: Electron
- **Server**: Express.js
---
## High-Level Architecture
Trilium follows a **client-server architecture** even in desktop mode, where Electron runs both the backend server and frontend client within the same process.
```mermaid
graph TB
subgraph Frontend
Widgets[Widgets<br/>System]
Froca[Froca<br/>Cache]
UIServices[UI<br/>Services]
end
subgraph Backend["Backend Server"]
Express[Express<br/>Routes]
Becca[Becca<br/>Cache]
ScriptEngine[Script<br/>Engine]
Database[(SQLite<br/>Database)]
end
Widgets -.-> API[WebSocket / REST API]
Froca -.-> API
UIServices -.-> API
API -.-> Express
API -.-> Becca
API -.-> ScriptEngine
Becca --> Database
Express --> Database
ScriptEngine --> Database
```
### Deployment Modes
1. **Desktop Application**
- Electron wrapper running both frontend and backend
- Local SQLite database
- Full offline functionality
- Cross-platform (Windows, macOS, Linux)
2. **Server Installation**
- Node.js server exposing web interface
- Multi-user capable
- Can sync with desktop clients
- Docker deployment supported
3. **Mobile Web**
- Optimized responsive interface
- Accessed via browser
- Requires server installation
---
## Monorepo Structure
Trilium uses **pnpm workspaces** to manage its monorepo structure, with apps and packages clearly separated.
```
trilium/
├── apps/ # Runnable applications
│ ├── client/ # Frontend application (shared by server & desktop)
│ ├── server/ # Node.js server with web interface
│ ├── desktop/ # Electron desktop application
│ ├── web-clipper/ # Browser extension for web content capture
│ ├── db-compare/ # Database comparison tool
│ ├── dump-db/ # Database export tool
│ ├── edit-docs/ # Documentation editing tool
│ ├── build-docs/ # Documentation build tool
│ └── website/ # Marketing website
├── packages/ # Shared libraries
│ ├── commons/ # Shared interfaces and utilities
│ ├── ckeditor5/ # Custom rich text editor
│ ├── codemirror/ # Code editor customizations
│ ├── highlightjs/ # Syntax highlighting
│ ├── ckeditor5-admonition/ # CKEditor plugin: admonitions
│ ├── ckeditor5-footnotes/ # CKEditor plugin: footnotes
│ ├── ckeditor5-keyboard-marker/# CKEditor plugin: keyboard shortcuts
│ ├── ckeditor5-math/ # CKEditor plugin: math equations
│ ├── ckeditor5-mermaid/ # CKEditor plugin: diagrams
│ ├── express-partial-content/ # HTTP partial content middleware
│ ├── share-theme/ # Shared note theme
│ ├── splitjs/ # Split pane library
│ └── turndown-plugin-gfm/ # Markdown conversion
├── docs/ # Documentation
├── scripts/ # Build and utility scripts
└── patches/ # Package patches (via pnpm)
```
### Package Dependencies
The monorepo uses workspace protocol (`workspace:*`) for internal dependencies:
```
desktop → client → commons
server → client → commons
client → ckeditor5, codemirror, highlightjs
ckeditor5 → ckeditor5-* plugins
```
---
## Core Architecture Patterns
### Three-Layer Cache System
Trilium implements a sophisticated **three-tier caching system** to optimize performance and enable offline functionality:
#### 1. Becca (Backend Cache)
Located at: `apps/server/src/becca/`
```typescript
// Becca caches all entities in memory
class Becca {
notes: Record<string, BNote>
branches: Record<string, BBranch>
attributes: Record<string, BAttribute>
attachments: Record<string, BAttachment>
// ... other entity collections
}
```
**Responsibilities:**
- Server-side entity cache
- Maintains complete note tree in memory
- Handles entity relationships and integrity
- Provides fast lookups without database queries
- Manages entity lifecycle (create, update, delete)
**Key Files:**
- `becca.ts` - Main cache instance
- `becca_loader.ts` - Loads entities from database
- `becca_service.ts` - Cache management operations
- `entities/` - Entity classes (BNote, BBranch, etc.)
#### 2. Froca (Frontend Cache)
Located at: `apps/client/src/services/froca.ts`
```typescript
// Froca is a read-only mirror of backend data
class Froca {
notes: Record<string, FNote>
branches: Record<string, FBranch>
attributes: Record<string, FAttribute>
// ... other entity collections
}
```
**Responsibilities:**
- Frontend read-only cache
- Lazy loading of note tree
- Minimizes API calls
- Enables fast UI rendering
- Synchronizes with backend via WebSocket
**Loading Strategy:**
- Initial load: root notes and immediate children
- Lazy load: notes loaded when accessed
- When note is loaded, all parent and child branches load
- Deleted entities tracked via missing branches
#### 3. Shaca (Share Cache)
Located at: `apps/server/src/share/`
**Responsibilities:**
- Optimized cache for shared/published notes
- Handles public note access without authentication
- Performance-optimized for high-traffic scenarios
- Separate from main Becca to isolate concerns
### Entity System
Trilium's data model is based on five core entities:
```mermaid
graph TD
Note[Note<br/>BNote]
Branch[Branch<br/>BBranch]
Attribute[Attribute<br/>BAttribute]
Revision[Revision<br/>BRevision]
Attachment[Attachment<br/>BAttachment]
Note -->|linked by| Branch
Note -.->|metadata| Attribute
Branch -->|creates| Revision
Note -->|has| Attachment
style Note fill:#e1f5ff
style Branch fill:#fff4e1
style Attribute fill:#ffe1f5
style Revision fill:#f5ffe1
style Attachment fill:#ffe1e1
```
#### Entity Definitions
**1. BNote** (`apps/server/src/becca/entities/bnote.ts`)
- Represents a note with title, content, and metadata
- Type can be: text, code, file, image, canvas, mermaid, etc.
- Contains content via blob reference
- Can be protected (encrypted)
- Has creation and modification timestamps
**2. BBranch** (`apps/server/src/becca/entities/bbranch.ts`)
- Represents parent-child relationship between notes
- Enables note cloning (multiple parents)
- Contains positioning information
- Has optional prefix for customization
- Tracks expansion state in tree
**3. BAttribute** (`apps/server/src/becca/entities/battribute.ts`)
- Key-value metadata attached to notes
- Two types: labels (tags) and relations (links)
- Can be inheritable to child notes
- Used for search, organization, and scripting
- Supports promoted attributes (displayed prominently)
**4. BRevision** (`apps/server/src/becca/entities/brevision.ts`)
- Stores historical versions of note content
- Automatic versioning on edits
- Retains title, type, and content
- Enables note history browsing and restoration
**5. BAttachment** (`apps/server/src/becca/entities/battachment.ts`)
- File attachments linked to notes
- Has owner (note), role, and mime type
- Content stored in blobs
- Can be protected (encrypted)
**6. BBlob** (`apps/server/src/becca/entities/bblob.ts`)
- Binary large object storage
- Stores actual note content and attachments
- Referenced by notes, revisions, and attachments
- Supports encryption for protected content
### Widget-Based UI
The frontend uses a **widget system** for modular, reusable UI components.
Located at: `apps/client/src/widgets/`
```typescript
// Widget Hierarchy
BasicWidget
NoteContextAwareWidget (responds to note changes)
RightPanelWidget (displayed in right sidebar)
Type-specific widgets
Container widgets (tabs, ribbons, etc.)
Specialized widgets (search, calendar, etc.)
```
**Base Classes:**
1. **BasicWidget** (`basic_widget.ts`)
- Base class for all UI components
- Lifecycle: construction → rendering → events → destruction
- Handles DOM manipulation
- Event subscription management
- Child widget management
2. **NoteContextAwareWidget** (`note_context_aware_widget.ts`)
- Extends BasicWidget
- Automatically updates when active note changes
- Accesses current note context
- Used for note-dependent UI
3. **RightPanelWidget**
- Widgets displayed in right sidebar
- Collapsible sections
- Context-specific tools and information
**Type-Specific Widgets:**
Located at: `apps/client/src/widgets/type_widgets/`
Each note type has a dedicated widget:
- `text_type_widget.ts` - CKEditor integration
- `code_type_widget.ts` - CodeMirror integration
- `file_type_widget.ts` - File preview and download
- `image_type_widget.ts` - Image display and editing
- `canvas_type_widget.ts` - Excalidraw integration
- `mermaid_type_widget.ts` - Diagram rendering
- And more...
---
## Data Layer
### Database Schema
Trilium uses **SQLite** as its database engine, managed via `better-sqlite3`.
Schema location: `apps/server/src/assets/db/schema.sql`
**Core Tables:**
```sql
-- Notes: Core content storage
notes (
noteId, title, isProtected, type, mime,
blobId, isDeleted, dateCreated, dateModified
)
-- Branches: Tree relationships
branches (
branchId, noteId, parentNoteId, notePosition,
prefix, isExpanded, isDeleted
)
-- Attributes: Metadata
attributes (
attributeId, noteId, type, name, value,
position, isInheritable, isDeleted
)
-- Revisions: Version history
revisions (
revisionId, noteId, type, mime, title,
blobId, utcDateLastEdited
)
-- Attachments: File attachments
attachments (
attachmentId, ownerId, role, mime, title,
blobId, isProtected, isDeleted
)
-- Blobs: Binary content
blobs (
blobId, content, dateModified
)
-- Options: Application settings
options (
name, value, isSynced
)
-- Entity Changes: Sync tracking
entity_changes (
entityName, entityId, hash, changeId,
isSynced, utcDateChanged
)
```
### Data Access Patterns
**Direct SQL:**
```typescript
// apps/server/src/services/sql.ts
sql.getRows("SELECT * FROM notes WHERE type = ?", ['text'])
sql.execute("UPDATE notes SET title = ? WHERE noteId = ?", [title, noteId])
```
**Through Becca:**
```typescript
// Recommended approach - uses cache
const note = becca.getNote('noteId')
note.title = 'New Title'
note.save()
```
**Through Froca (Frontend):**
```typescript
// Read-only access
const note = froca.getNote('noteId')
console.log(note.title)
```
### Database Migrations
Migration system: `apps/server/src/migrations/`
- Sequential numbered files (e.g., `XXXX_migration_name.sql`)
- Automatic execution on version upgrade
- Schema version tracked in options table
- Both SQL and JavaScript migrations supported
---
## Caching System
### Cache Initialization
**Backend (Becca):**
```typescript
// On server startup
await becca_loader.load() // Loads all entities into memory
becca.loaded = true
```
**Frontend (Froca):**
```typescript
// On app initialization
await froca.loadInitialTree() // Loads root and visible notes
// Lazy load on demand
const note = await froca.getNote(noteId) // Triggers load if not cached
```
### Cache Invalidation
**Server-Side:**
- Entities automatically update cache on save
- WebSocket broadcasts changes to all clients
- Synchronization updates trigger cache refresh
**Client-Side:**
- WebSocket listeners update Froca
- Manual reload via `froca.loadSubTree(noteId)`
- Full reload on protected session changes
### Cache Consistency
**Entity Change Tracking:**
```typescript
// Every entity modification tracked
entity_changes (
entityName: 'notes',
entityId: 'note123',
hash: 'abc...',
changeId: 'change456',
utcDateChanged: '2025-11-02...'
)
```
**Sync Protocol:**
1. Client requests changes since last sync
2. Server returns entity_changes records
3. Client applies changes to Froca
4. Client sends local changes to server
5. Server updates Becca and database
---
## Frontend Architecture
### Application Entry Point
**Desktop:** `apps/client/src/desktop.ts`
**Web:** `apps/client/src/index.ts`
### Service Layer
Located at: `apps/client/src/services/`
Key services:
- `froca.ts` - Frontend cache
- `server.ts` - API communication
- `ws.ts` - WebSocket connection
- `tree_service.ts` - Note tree management
- `note_context.ts` - Active note tracking
- `protected_session.ts` - Encryption key management
- `link.ts` - Note linking and navigation
- `export.ts` - Note export functionality
### UI Components
**Main Layout:**
```mermaid
graph TD
subgraph TriliumUI[" "]
TitleBar[Title Bar]
subgraph MainArea[" "]
NoteTree[Note Tree]
NoteDetail[Note Detail<br/>Editor]
RightPanel[Right Panel<br/>Info, Links]
end
StatusBar[Status Bar]
end
TitleBar -.-> MainArea
MainArea -.-> StatusBar
style TitleBar fill:#e1f5ff
style NoteTree fill:#fff4e1
style NoteDetail fill:#f5ffe1
style RightPanel fill:#ffe1f5
style StatusBar fill:#e1f5ff
```
**Component Locations:**
- `widgets/containers/` - Layout containers
- `widgets/buttons/` - Toolbar buttons
- `widgets/dialogs/` - Modal dialogs
- `widgets/ribbon_widgets/` - Tab widgets
- `widgets/type_widgets/` - Note type editors
### Event System
**Application Events:**
```typescript
// Subscribe to events
appContext.addBeforeUnloadListener(() => {
// Cleanup before page unload
})
// Trigger events
appContext.trigger('noteTreeLoaded')
```
**Note Context Events:**
```typescript
// NoteContextAwareWidget automatically receives:
- noteSwitched()
- noteChanged()
- refresh()
```
### State Management
Trilium uses **custom state management** rather than Redux/MobX:
- `note_context.ts` - Active note and context
- `froca.ts` - Entity cache
- Component local state
- URL parameters for shareable state
---
## Backend Architecture
### Application Entry Point
Location: `apps/server/src/main.ts`
**Startup Sequence:**
1. Load configuration
2. Initialize database
3. Run migrations
4. Load Becca cache
5. Start Express server
6. Initialize WebSocket
7. Start scheduled tasks
### Service Layer
Located at: `apps/server/src/services/`
**Core Services:**
- **Notes Management**
- `notes.ts` - CRUD operations
- `note_contents.ts` - Content handling
- `note_types.ts` - Type-specific logic
- `cloning.ts` - Note cloning/multi-parent
- **Tree Operations**
- `tree.ts` - Tree structure management
- `branches.ts` - Branch operations
- `consistency_checks.ts` - Tree integrity
- **Search**
- `search/search.ts` - Main search engine
- `search/expressions/` - Search expression parsing
- `search/services/` - Search utilities
- **Sync**
- `sync.ts` - Synchronization protocol
- `sync_update.ts` - Update handling
- `sync_mutex.ts` - Concurrency control
- **Scripting**
- `backend_script_api.ts` - Backend script API
- `script_context.ts` - Script execution context
- **Import/Export**
- `import/` - Various import formats
- `export/` - Export to different formats
- `zip.ts` - Archive handling
- **Security**
- `encryption.ts` - Note encryption
- `protected_session.ts` - Session management
- `password.ts` - Password handling
### Route Structure
Located at: `apps/server/src/routes/`
```
routes/
├── index.ts # Route registration
├── api/ # REST API endpoints
│ ├── notes.ts
│ ├── branches.ts
│ ├── attributes.ts
│ ├── search.ts
│ ├── login.ts
│ └── ...
└── custom/ # Special endpoints
├── setup.ts
├── share.ts
└── ...
```
**API Endpoint Pattern:**
```typescript
router.get('/api/notes/:noteId', (req, res) => {
const noteId = req.params.noteId
const note = becca.getNote(noteId)
res.json(note.getPojoWithContent())
})
```
### Middleware
Key middleware components:
- `auth.ts` - Authentication
- `csrf.ts` - CSRF protection
- `request_context.ts` - Request-scoped data
- `error_handling.ts` - Error responses
---
## API Architecture
### Internal API
**REST Endpoints** (`/api/*`)
Used by the frontend for all operations:
**Note Operations:**
- `GET /api/notes/:noteId` - Get note
- `POST /api/notes/:noteId/content` - Update content
- `PUT /api/notes/:noteId` - Update metadata
- `DELETE /api/notes/:noteId` - Delete note
**Tree Operations:**
- `GET /api/tree` - Get note tree
- `POST /api/branches` - Create branch
- `PUT /api/branches/:branchId` - Update branch
- `DELETE /api/branches/:branchId` - Delete branch
**Search:**
- `GET /api/search?query=...` - Search notes
- `GET /api/search-note/:noteId` - Execute search note
### ETAPI (External API)
Located at: `apps/server/src/etapi/`
**Purpose:** Third-party integrations and automation
**Authentication:** Token-based (ETAPI tokens)
**OpenAPI Spec:** Auto-generated
**Key Endpoints:**
- `/etapi/notes` - Note CRUD
- `/etapi/branches` - Branch management
- `/etapi/attributes` - Attribute operations
- `/etapi/attachments` - Attachment handling
**Example:**
```bash
curl -H "Authorization: YOUR_TOKEN" \
https://trilium.example.com/etapi/notes/noteId
```
### WebSocket API
Located at: `apps/server/src/services/ws.ts`
**Purpose:** Real-time updates and synchronization
**Protocol:** WebSocket (Socket.IO-like custom protocol)
**Message Types:**
- `sync` - Synchronization request
- `entity-change` - Entity update notification
- `refresh-tree` - Tree structure changed
- `open-note` - Open note in UI
**Client Subscribe:**
```typescript
ws.subscribe('entity-change', (data) => {
froca.processEntityChange(data)
})
```
---
## Build System
### Package Manager: pnpm
@@ -1013,9 +277,3 @@ For historical context on major architectural decisions, see:
- Adoption of pnpm workspaces
- CKEditor 5 upgrade
- Entity change tracking system
---
**Document Maintainer:** TriliumNext Team
**Last Review:** November 2025
**Next Review:** When major architectural changes occur

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,118 @@
# Architecture
Trilium Notes is a hierarchical note-taking application built as a TypeScript monorepo. It supports multiple deployment modes (desktop, server, mobile web) and features advanced capabilities including synchronization, scripting, encryption, and rich content editing.
### Key Characteristics
* **Monorepo Architecture**: Uses pnpm workspaces for dependency management
* **Multi-Platform**: Desktop (Electron), Server (Node.js/Express), and Mobile Web
* **TypeScript-First**: Strong typing throughout the codebase
* **Plugin-Based**: Extensible architecture for note types and UI components
* **Offline-First**: Full functionality without network connectivity
* **Synchronization-Ready**: Built-in sync protocol for multi-device usage
### Technology Stack
* **Runtime**: Node.js (backend), Browser/Electron (frontend)
* **Language**: TypeScript, JavaScript
* **Database**: SQLite (better-sqlite3)
* **Build Tools**: Vite, ESBuild, pnpm
* **UI Framework**: Custom widget-based system (vanilla HTML, CSS & JavaScript + jQuery), in the process of converting to React/Preact.
* **Rich Text**: CKEditor 5 (customized)
* **Code Editing**: CodeMirror 6
* **Desktop**: Electron
* **Server**: Express.js
## Main architecture
Trilium follows a **client-server architecture** even in desktop mode, where Electron runs both the backend server and frontend client within the same process.
```mermaid
graph TB
subgraph Frontend
Widgets[Widgets<br/>System]
Froca[Froca<br/>Cache]
UIServices[UI<br/>Services]
end
subgraph Backend["Backend Server"]
Express[Express<br/>Routes]
Becca[Becca<br/>Cache]
ScriptEngine[Script<br/>Engine]
Database[(SQLite<br/>Database)]
end
Widgets -.-> API[WebSocket & REST API]
Froca -.-> API
UIServices -.-> API
API -.-> Express
API -.-> Becca
API -.-> ScriptEngine
Becca --> Database
Express --> Database
ScriptEngine --> Database
```
### Deployment Modes
1. **Desktop Application**
* Electron wrapper running both frontend and backend
* Local SQLite database
* Full offline functionality
* Cross-platform (Windows, macOS, Linux)
2. **Server Installation**
* Node.js server exposing web interface
* Multi-user capable
* Can sync with desktop clients
* Docker deployment supported
3. **Mobile Web**
* Optimized responsive interface
* Accessed via browser
* Requires server installation
## Monorepo Structure
Trilium uses **pnpm workspaces** to manage its monorepo structure, with apps and packages clearly separated.
```
trilium/
├── apps/ # Runnable applications
│ ├── client/ # Frontend application (shared by server & desktop)
│ ├── server/ # Node.js server with web interface
│ ├── desktop/ # Electron desktop application
│ ├── web-clipper/ # Browser extension for web content capture
│ ├── db-compare/ # Database comparison tool
│ ├── dump-db/ # Database export tool
│ ├── edit-docs/ # Documentation editing tool
│ ├── build-docs/ # Documentation build tool
│ └── website/ # Marketing website
├── packages/ # Shared libraries
│ ├── commons/ # Shared interfaces and utilities
│ ├── ckeditor5/ # Custom rich text editor
│ ├── codemirror/ # Code editor customizations
│ ├── highlightjs/ # Syntax highlighting
│ ├── ckeditor5-admonition/ # CKEditor plugin: admonitions
│ ├── ckeditor5-footnotes/ # CKEditor plugin: footnotes
│ ├── ckeditor5-keyboard-marker/# CKEditor plugin: keyboard shortcuts
│ ├── ckeditor5-math/ # CKEditor plugin: math equations
│ ├── ckeditor5-mermaid/ # CKEditor plugin: diagrams
│ ├── express-partial-content/ # HTTP partial content middleware
│ ├── share-theme/ # Shared note theme
│ ├── splitjs/ # Split pane library
│ └── turndown-plugin-gfm/ # Markdown conversion
├── docs/ # Documentation
├── scripts/ # Build and utility scripts
└── patches/ # Package patches (via pnpm)
```
### Package Dependencies
The monorepo uses workspace protocol (`workspace:*`) for internal dependencies:
```
desktop → client → commons
server → client → commons
client → ckeditor5, codemirror, highlightjs
ckeditor5 → ckeditor5-* plugins
```

View File

@@ -0,0 +1,72 @@
# API
### Internal API
**REST Endpoints** (`/api/*`)
Used by the frontend for all operations:
**Note Operations:**
* `GET /api/notes/:noteId` - Get note
* `POST /api/notes/:noteId/content` - Update content
* `PUT /api/notes/:noteId` - Update metadata
* `DELETE /api/notes/:noteId` - Delete note
**Tree Operations:**
* `GET /api/tree` - Get note tree
* `POST /api/branches` - Create branch
* `PUT /api/branches/:branchId` - Update branch
* `DELETE /api/branches/:branchId` - Delete branch
**Search:**
* `GET /api/search?query=...` - Search notes
* `GET /api/search-note/:noteId` - Execute search note
### ETAPI (External API)
Located at: `apps/server/src/etapi/`
**Purpose:** Third-party integrations and automation
**Authentication:** Token-based (ETAPI tokens)
**OpenAPI Spec:** Auto-generated
**Key Endpoints:**
* `/etapi/notes` - Note CRUD
* `/etapi/branches` - Branch management
* `/etapi/attributes` - Attribute operations
* `/etapi/attachments` - Attachment handling
**Example:**
```sh
curl -H "Authorization: YOUR_TOKEN" \
https://trilium.example.com/etapi/notes/noteId
```
### WebSocket API
Located at: `apps/server/src/services/ws.ts`
**Purpose:** Real-time updates and synchronization
**Protocol:** WebSocket (Socket.IO-like custom protocol)
**Message Types:**
* `sync` - Synchronization request
* `entity-change` - Entity update notification
* `refresh-tree` - Tree structure changed
* `open-note` - Open note in UI
**Client Subscribe:**
```typescript
ws.subscribe('entity-change', (data) => {
froca.processEntityChange(data)
})
```

View File

@@ -0,0 +1,88 @@
# Backend
### Application Entry Point
Location: `apps/server/src/main.ts`
**Startup Sequence:**
1. Load configuration
2. Initialize database
3. Run migrations
4. Load Becca cache
5. Start Express server
6. Initialize WebSocket
7. Start scheduled tasks
### Service Layer
Located at: `apps/server/src/services/`
**Core Services:**
* **Notes Management**
* `notes.ts` - CRUD operations
* `note_contents.ts` - Content handling
* `note_types.ts` - Type-specific logic
* `cloning.ts` - Note cloning/multi-parent
* **Tree Operations**
* `tree.ts` - Tree structure management
* `branches.ts` - Branch operations
* `consistency_checks.ts` - Tree integrity
* **Search**
* `search/search.ts` - Main search engine
* `search/expressions/` - Search expression parsing
* `search/services/` - Search utilities
* **Sync**
* `sync.ts` - Synchronization protocol
* `sync_update.ts` - Update handling
* `sync_mutex.ts` - Concurrency control
* **Scripting**
* `backend_script_api.ts` - Backend script API
* `script_context.ts` - Script execution context
* **Import/Export**
* `import/` - Various import formats
* `export/` - Export to different formats
* `zip.ts` - Archive handling
* **Security**
* `encryption.ts` - Note encryption
* `protected_session.ts` - Session management
* `password.ts` - Password handling
### Route Structure
Located at: `apps/server/src/routes/`
```
routes/
├── index.ts # Route registration
├── api/ # REST API endpoints
│ ├── notes.ts
│ ├── branches.ts
│ ├── attributes.ts
│ ├── search.ts
│ ├── login.ts
│ └── ...
└── custom/ # Special endpoints
├── setup.ts
├── share.ts
└── ...
```
**API Endpoint Pattern:**
```typescript
router.get('/api/notes/:noteId', (req, res) => {
const noteId = req.params.noteId
const note = becca.getNote(noteId)
res.json(note.getPojoWithContent())
})
```
### Middleware
Key middleware components:
* `auth.ts` - Authentication
* `csrf.ts` - CSRF protection
* `request_context.ts` - Request-scoped data
* `error_handling.ts` - Error responses

View File

@@ -0,0 +1,61 @@
# Frontend
### Application Entry Point
**Desktop:** `apps/client/src/desktop.ts` **Web:** `apps/client/src/index.ts`
### Service Layer
Located at: `apps/client/src/services/`
Key services:
* `froca.ts` - Frontend cache
* `server.ts` - API communication
* `ws.ts` - WebSocket connection
* `tree_service.ts` - Note tree management
* `note_context.ts` - Active note tracking
* `protected_session.ts` - Encryption key management
* `link.ts` - Note linking and navigation
* `export.ts` - Note export functionality
### UI Components
**Component Locations:**
* `widgets/containers/` - Layout containers
* `widgets/buttons/` - Toolbar buttons
* `widgets/dialogs/` - Modal dialogs
* `widgets/ribbon_widgets/` - Tab widgets
* `widgets/type_widgets/` - Note type editors
### Event System
**Application Events:**
```typescript
// Subscribe to events
appContext.addBeforeUnloadListener(() => {
// Cleanup before page unload
})
// Trigger events
appContext.trigger('noteTreeLoaded')
```
**Note Context Events:**
```typescript
// NoteContextAwareWidget automatically receives:
- noteSwitched()
- noteChanged()
- refresh()
```
### State Management
Trilium uses **custom state management** rather than Redux/MobX:
* `note_context.ts` - Active note and context
* `froca.ts` - Entity cache
* Component local state
* URL parameters for shareable state

View File

@@ -0,0 +1,40 @@
# Database
Trilium uses **SQLite** as its database engine, managed via `better-sqlite3`.
Schema location: `apps/server/src/assets/db/schema.sql`
### Data Access Patterns
**Direct SQL:**
```typescript
// apps/server/src/services/sql.ts
sql.getRows("SELECT * FROM notes WHERE type = ?", ['text'])
sql.execute("UPDATE notes SET title = ? WHERE noteId = ?", [title, noteId])
```
**Through Becca:**
```typescript
// Recommended approach - uses cache
const note = becca.getNote('noteId')
note.title = 'New Title'
note.save()
```
**Through Froca (Frontend):**
```typescript
// Read-only access
const note = froca.getNote('noteId')
console.log(note.title)
```
### Database Migrations
* The migration system is in `server/src/migrations/migrations.ts` (actual definitions) and `src/services/migration.ts`.
* Both SQLite and TypeScript migrations are supported.
* Small migrations are contained directly in `src/migrations/migrations.ts`.
* Bigger TypeScript migrations are sequentially numbered (e.g., `XXXX_migration_name.ts`) and dynamically imported by `migrations.ts`.
* Automatic execution on version upgrade.
* Schema version tracked in options table.

View File

@@ -6,11 +6,11 @@
| `role` | Text | Non-null | | The role of the attachment: `image` for images that are attached to a note, `file` for uploaded files. |
| `mime` | Text | Non-null | | The MIME type of the attachment (e.g. `image/png`) |
| `title` | Text | Non-null | | The title of the attachment. |
| `isProtected` | Integer | Non-null | 0 | `1` if the entity is [protected](../Protected%20entities.md), `0` otherwise. |
| `isProtected` | Integer | Non-null | 0 | `1` if the entity is [protected](../../../Concepts/Protected%20entities.md), `0` otherwise. |
| `position` | Integer | Non-null | 0 | Not sure where the position is relevant for attachments (saw it with values of 10 and 0). |
| `blobId` | Text | Nullable | `null` | The corresponding `blobId` from the <a class="reference-link" href="blobs.md">blobs</a> table. |
| `dateModified` | Text | Non-null | | Localized modification date (e.g. `2023-11-08 18:43:44.204+0200`) |
| `utcDateModified` | Text | Non-null | | Modification date in UTC format (e.g. `2023-11-08 16:43:44.204Z`) |
| `utcDateScheduledForErasure` | Text | Nullable | `null` | |
| `isDeleted` | Integer | Non-null | | `1` if the entity is [deleted](../Deleted%20notes.md), `0` otherwise. |
| `isDeleted` | Integer | Non-null | | `1` if the entity is [deleted](../../../Concepts/Deleted%20notes.md), `0` otherwise. |
| `deleteId` | Text | Nullable | `null` | |

View File

@@ -1,2 +1,2 @@
# attributes
<table><thead><tr><th>Column Name</th><th>Data Type</th><th>Nullity</th><th>Default value</th><th>Description</th></tr></thead><tbody><tr><th><code>attributeId</code></th><td>Text</td><td>Non-null</td><td>&nbsp;</td><td>Unique Id of the attribute (e.g. <code>qhC1vzU4nwSE</code>), can also have a special unique ID for&nbsp;<a class="reference-link" href="#root/r11Bh3uxFGRj">Special notes</a>&nbsp;(e.g. <code>_lbToday_liconClass</code>).</td></tr><tr><th><code>noteId</code></th><td>Text</td><td>Non-null</td><td>&nbsp;</td><td>The ID of the <a href="notes.md">note</a> this atttribute belongs to</td></tr><tr><th><code>type</code></th><td>Text</td><td>Non-null</td><td>&nbsp;</td><td>The type of attribute (<code>label</code> or <code>relation</code>).</td></tr><tr><th><code>name</code></th><td>Text</td><td>Non-null</td><td>&nbsp;</td><td>The name/key of the attribute.</td></tr><tr><th><code>value</code></th><td>Text</td><td>Non-null</td><td><code>""</code></td><td><ul><li>For <code>label</code> attributes, a free-form value of the attribute.</li><li>For <code>relation</code> attributes, the ID of the <a href="notes.md">note</a> the relation is pointing to.</li></ul></td></tr><tr><th><code>position</code></th><td>Integer</td><td>Non-null</td><td>0</td><td>The position of the attribute compared to the other attributes. Some predefined attributes such as <code>originalFileName</code> have a value of 1000.</td></tr><tr><th><code>utcDateModified</code></th><td>Text</td><td>Non-null</td><td>&nbsp;</td><td>Modification date in UTC format (e.g. <code>2023-11-08 16:43:44.204Z</code>)</td></tr><tr><th><code>isDeleted</code></th><td>Integer</td><td>Non-null</td><td>&nbsp;</td><td><code>1</code> if the entity is <a href="../Deleted%20notes.md">deleted</a>, <code>0</code> otherwise.</td></tr><tr><th><code>deleteId</code></th><td>Text</td><td>Nullable</td><td><code>null</code></td><td>&nbsp;</td></tr><tr><th><code>isInheritable</code></th><td>Integer</td><td>Nullable</td><td>0</td><td>&nbsp;</td></tr></tbody></table>
<table><thead><tr><th>Column Name</th><th>Data Type</th><th>Nullity</th><th>Default value</th><th>Description</th></tr></thead><tbody><tr><th><code>attributeId</code></th><td>Text</td><td>Non-null</td><td>&nbsp;</td><td>Unique Id of the attribute (e.g. <code>qhC1vzU4nwSE</code>), can also have a special unique ID for&nbsp;<a class="reference-link" href="#root/r11Bh3uxFGRj">Special notes</a>&nbsp;(e.g. <code>_lbToday_liconClass</code>).</td></tr><tr><th><code>noteId</code></th><td>Text</td><td>Non-null</td><td>&nbsp;</td><td>The ID of the <a href="notes.md">note</a> this atttribute belongs to</td></tr><tr><th><code>type</code></th><td>Text</td><td>Non-null</td><td>&nbsp;</td><td>The type of attribute (<code>label</code> or <code>relation</code>).</td></tr><tr><th><code>name</code></th><td>Text</td><td>Non-null</td><td>&nbsp;</td><td>The name/key of the attribute.</td></tr><tr><th><code>value</code></th><td>Text</td><td>Non-null</td><td><code>""</code></td><td><ul><li>For <code>label</code> attributes, a free-form value of the attribute.</li><li>For <code>relation</code> attributes, the ID of the <a href="notes.md">note</a> the relation is pointing to.</li></ul></td></tr><tr><th><code>position</code></th><td>Integer</td><td>Non-null</td><td>0</td><td>The position of the attribute compared to the other attributes. Some predefined attributes such as <code>originalFileName</code> have a value of 1000.</td></tr><tr><th><code>utcDateModified</code></th><td>Text</td><td>Non-null</td><td>&nbsp;</td><td>Modification date in UTC format (e.g. <code>2023-11-08 16:43:44.204Z</code>)</td></tr><tr><th><code>isDeleted</code></th><td>Integer</td><td>Non-null</td><td>&nbsp;</td><td><code>1</code> if the entity is <a href="../../../Concepts/Deleted%20notes.md">deleted</a>, <code>0</code> otherwise.</td></tr><tr><th><code>deleteId</code></th><td>Text</td><td>Nullable</td><td><code>null</code></td><td>&nbsp;</td></tr><tr><th><code>isInheritable</code></th><td>Integer</td><td>Nullable</td><td>0</td><td>&nbsp;</td></tr></tbody></table>

View File

@@ -5,8 +5,8 @@
| `noteId` | Text | Non-null | | The ID of the [note](notes.md). |
| `parentNoteId` | Text | Non-null | | The ID of the parent [note](notes.md) the note belongs to. |
| `notePosition` | Integer | Non-null | | The position of the branch within the same level of hierarchy, the value is usually a multiple of 10. |
| `prefix` | Text | Nullable | | The [branch prefix](../Branch%20prefixes.md) if any, or `NULL` otherwise. |
| `prefix` | Text | Nullable | | The [branch prefix](../../../Concepts/Branch%20prefixes.md) if any, or `NULL` otherwise. |
| `isExpanded` | Integer | Non-null | 0 | Whether the branch should appear expanded (its children shown) to the user. |
| `isDeleted` | Integer | Non-null | 0 | `1` if the entity is [deleted](../Deleted%20notes.md), `0` otherwise. |
| `isDeleted` | Integer | Non-null | 0 | `1` if the entity is [deleted](../../../Concepts/Deleted%20notes.md), `0` otherwise. |
| `deleteId` | Text | Nullable | `null` | |
| `utcDateModified` | Text | Non-null | | Modification date in UTC format (e.g. `2023-11-08 16:43:44.204Z`) |

View File

@@ -6,4 +6,4 @@
| `tokenHash` | Text | Non-null | | The token itself. |
| `utcDateCreated` | Text | Non-null | | Creation date in UTC format (e.g. `2023-11-08 16:43:44.204Z`) |
| `utcDateModified` | Text | Non-null | | Modification date in UTC format (e.g. `2023-11-08 16:43:44.204Z`) |
| `isDeleted` | Integer | Non-null | 0 | `1` if the entity is [deleted](../Deleted%20notes.md), `0` otherwise. |
| `isDeleted` | Integer | Non-null | 0 | `1` if the entity is [deleted](../../../Concepts/Deleted%20notes.md), `0` otherwise. |

View File

@@ -3,10 +3,10 @@
| --- | --- | --- | --- | --- |
| `noteId` | Text | Non-null | | The unique ID of the note (e.g. `2LJrKqIhr0Pe`). |
| `title` | Text | Non-null | `"note"` | The title of the note, as defined by the user. |
| `isProtected` | Integer | Non-null | 0 | `1` if the entity is [protected](../Protected%20entities.md), `0` otherwise. |
| `isProtected` | Integer | Non-null | 0 | `1` if the entity is [protected](../../../Concepts/Protected%20entities.md), `0` otherwise. |
| `type` | Text | Non-null | `"text"` | The type of note (i.e. `text`, `file`, `code`, `relationMap`, `mermaid`, `canvas`). |
| `mime` | Text | Non-null | `"text/html"` | The MIME type of the note (e.g. `text/html`).. Note that it can be an empty string in some circumstances, but not null. |
| `isDeleted` | Integer | Nullable | 0 | `1` if the entity is [deleted](../Deleted%20notes.md), `0` otherwise. |
| `isDeleted` | Integer | Nullable | 0 | `1` if the entity is [deleted](../../../Concepts/Deleted%20notes.md), `0` otherwise. |
| `deleteId` | Text | Non-null | `null` | |
| `dateCreated` | Text | Non-null | | Localized creation date (e.g. `2023-11-08 18:43:44.204+0200`) |
| `dateModified` | Text | Non-null | | Localized modification date (e.g. `2023-11-08 18:43:44.204+0200`) |

View File

@@ -6,7 +6,7 @@
| `type` | Text | Non-null | `""` | The type of note (i.e. `text`, `file`, `code`, `relationMap`, `mermaid`, `canvas`). |
| `mime` | Text | Non-null | `""` | The MIME type of the note (e.g. `text/html`). |
| `title` | Text | Non-null | | The title of the note, as defined by the user. |
| `isProtected` | Integer | Non-null | 0 | `1` if the entity is [protected](../Protected%20entities.md), `0` otherwise. |
| `isProtected` | Integer | Non-null | 0 | `1` if the entity is [protected](../../../Concepts/Protected%20entities.md), `0` otherwise. |
| `blobId` | Text | Nullable | `null` | The corresponding ID from <a class="reference-link" href="blobs.md">blobs</a>. Although it can theoretically be `NULL`, haven't found any such note yet. |
| `utcDateLastEdited` | Text | Non-null | | **Not sure how it differs from modification date.** |
| `utcDateCreated` | Text | Non-null | | Creation date in UTC format (e.g. `2023-11-08 16:43:44.204Z`) |

View File

@@ -1,6 +0,0 @@
# Protected entities
The following entities can be made protected, via their `isProtected` flag:
* <a class="reference-link" href="Database%20structure/attachments.md">attachments</a>
* <a class="reference-link" href="Database%20structure/notes.md">notes</a>
* <a class="reference-link" href="Database%20structure/revisions.md">revisions</a>

View File

Before

Width:  |  Height:  |  Size: 61 KiB

After

Width:  |  Height:  |  Size: 61 KiB

View File

Before

Width:  |  Height:  |  Size: 8.4 KiB

After

Width:  |  Height:  |  Size: 8.4 KiB

View File

@@ -0,0 +1,111 @@
# Cache
### Three-Layer Cache System
Trilium implements a sophisticated **three-tier caching system** to optimize performance and enable offline functionality:
#### 1\. Becca (Backend Cache)
Located at: `apps/server/src/becca/`
```typescript
// Becca caches all entities in memory
class Becca {
notes: Record<string, BNote>
branches: Record<string, BBranch>
attributes: Record<string, BAttribute>
attachments: Record<string, BAttachment>
// ... other entity collections
}
```
**Responsibilities:**
* Server-side entity cache
* Maintains complete note tree in memory
* Handles entity relationships and integrity
* Provides fast lookups without database queries
* Manages entity lifecycle (create, update, delete)
**Key Files:**
* `becca.ts` - Main cache instance
* `becca_loader.ts` - Loads entities from database
* `becca_service.ts` - Cache management operations
* `entities/` - Entity classes (BNote, BBranch, etc.)
#### 2\. Froca (Frontend Cache)
Located at: `apps/client/src/services/froca.ts`
```typescript
// Froca is a read-only mirror of backend data
class Froca {
notes: Record<string, FNote>
branches: Record<string, FBranch>
attributes: Record<string, FAttribute>
// ... other entity collections
}
```
**Responsibilities:**
* Frontend read-only cache
* Lazy loading of note tree
* Minimizes API calls
* Enables fast UI rendering
* Synchronizes with backend via WebSocket
**Loading Strategy:**
* Initial load: root notes and immediate children
* Lazy load: notes loaded when accessed
* When note is loaded, all parent and child branches load
* Deleted entities tracked via missing branches
#### 3\. Shaca (Share Cache)
Located at: `apps/server/src/share/`
**Responsibilities:**
* Optimized cache for shared/published notes
* Handles public note access without authentication
* Performance-optimized for high-traffic scenarios
* Separate from main Becca to isolate concerns
### Cache Invalidation
**Server-Side:**
* Entities automatically update cache on save
* WebSocket broadcasts changes to all clients
* Synchronization updates trigger cache refresh
**Client-Side:**
* WebSocket listeners update Froca
* Manual reload via `froca.loadSubTree(noteId)`
* Full reload on protected session changes
### Cache Consistency
**Entity Change Tracking:**
```typescript
// Every entity modification tracked
entity_changes (
entityName: 'notes',
entityId: 'note123',
hash: 'abc...',
changeId: 'change456',
utcDateChanged: '2025-11-02...'
)
```
**Sync Protocol:**
1. Client requests changes since last sync
2. Server returns entity\_changes records
3. Client applies changes to Froca
4. Client sends local changes to server
5. Server updates Becca and database

View File

@@ -0,0 +1,109 @@
# Entities
### Entity System
Trilium's data model is based on five core entities:
```mermaid
graph TD
Note[Note<br/>BNote]
Branch[Branch<br/>BBranch]
Attribute[Attribute<br/>BAttribute]
Revision[Revision<br/>BRevision]
Attachment[Attachment<br/>BAttachment]
Note -->|linked by| Branch
Note -.->|metadata| Attribute
Branch -->|creates| Revision
Note -->|has| Attachment
style Note fill:#e1f5ff
style Branch fill:#fff4e1
style Attribute fill:#ffe1f5
style Revision fill:#f5ffe1
style Attachment fill:#ffe1e1
```
#### Entity Definitions
**1\. BNote** (`apps/server/src/becca/entities/bnote.ts`)
* Represents a note with title, content, and metadata
* Type can be: text, code, file, image, canvas, mermaid, etc.
* Contains content via blob reference
* Can be protected (encrypted)
* Has creation and modification timestamps
**2\. BBranch** (`apps/server/src/becca/entities/bbranch.ts`)
* Represents parent-child relationship between notes
* Enables note cloning (multiple parents)
* Contains positioning information
* Has optional prefix for customization
* Tracks expansion state in tree
**3\. BAttribute** (`apps/server/src/becca/entities/battribute.ts`)
* Key-value metadata attached to notes
* Two types: labels (tags) and relations (links)
* Can be inheritable to child notes
* Used for search, organization, and scripting
* Supports promoted attributes (displayed prominently)
**4\. BRevision** (`apps/server/src/becca/entities/brevision.ts`)
* Stores historical versions of note content
* Automatic versioning on edits
* Retains title, type, and content
* Enables note history browsing and restoration
**5\. BAttachment** (`apps/server/src/becca/entities/battachment.ts`)
* File attachments linked to notes
* Has owner (note), role, and mime type
* Content stored in blobs
* Can be protected (encrypted)
**6\. BBlob** (`apps/server/src/becca/entities/bblob.ts`)
* Binary large object storage
* Stores actual note content and attachments
* Referenced by notes, revisions, and attachments
* Supports encryption for protected content
### Widget-Based UI
The frontend uses a **widget system** for modular, reusable UI components.
Located at: `apps/client/src/widgets/`
```typescript
// Widget Hierarchy
BasicWidget
NoteContextAwareWidget (responds to note changes)
RightPanelWidget (displayed in right sidebar)
Type-specific widgets
Container widgets (tabs, ribbons, etc.)
Specialized widgets (search, calendar, etc.)
```
**Base Classes:**
1. **BasicWidget** (`basic_widget.ts`)
* Base class for all UI components
* Lifecycle: construction → rendering → events → destruction
* Handles DOM manipulation
* Event subscription management
* Child widget management
2. **NoteContextAwareWidget** (`note_context_aware_widget.ts`)
* Extends BasicWidget
* Automatically updates when active note changes
* Accesses current note context
* Used for note-dependent UI
3. **RightPanelWidget**
* Widgets displayed in right sidebar
* Collapsible sections
* Context-specific tools and information
**Type-Specific Widgets:**
Each note type has a dedicated widget, which are located in `apps/client/src/widgets/type_widgets`.

View File

@@ -0,0 +1,6 @@
# Protected entities
The following entities can be made protected, via their `isProtected` flag:
* <a class="reference-link" href="../Architecture/Database/Database%20structure/attachments.md">attachments</a>
* <a class="reference-link" href="../Architecture/Database/Database%20structure/notes.md">notes</a>
* <a class="reference-link" href="../Architecture/Database/Database%20structure/revisions.md">revisions</a>

View File

@@ -1,5 +1,5 @@
# Documentation
There are multiple types of documentation for Trilium:<img class="image-style-align-right" src="api/attachments/2bUrJyt2yfsd/image/Documentation_image.png" width="205" height="162">
There are multiple types of documentation for Trilium:<img class="image-style-align-right" src="api/images/GUwY9NTWQZlI/Documentation_image.png" width="205" height="162">
* The _User Guide_ represents the user-facing documentation. This documentation can be browsed by users directly from within Trilium, by pressing <kbd>F1</kbd>.
* The _Developer's Guide_ represents a set of Markdown documents that present the internals of Trilium, for developers.

View File

@@ -33,4 +33,4 @@ Run `pnpm i` at the top of the `Notes` repository to install the dependencies.
Our recommended IDE for working on Trilium is Visual Studio Code (or VSCodium if you are looking for a fully open-source alternative).
By default we include a number of suggested extensions which should appear when opening the repository in VS Code. Most of the extensions are for integrating various technologies we are using such as Playwright and Vitest for testing or for <a class="reference-link" href="Architecture/Internationalisation%20%20Translat.md">Internationalisation / Translations</a>.
By default we include a number of suggested extensions which should appear when opening the repository in VS Code. Most of the extensions are for integrating various technologies we are using such as Playwright and Vitest for testing or for <a class="reference-link" href="Concepts/Internationalisation%20%20Translat.md">Internationalisation / Translations</a>.

View File

@@ -14616,21 +14616,21 @@
{
"type": "relation",
"name": "internalLink",
"value": "zEY4DaJG4YT5",
"value": "GLks18SNjxmC",
"isInheritable": false,
"position": 10
},
{
"type": "relation",
"name": "internalLink",
"value": "SynTBQiBsdYJ",
"value": "zEY4DaJG4YT5",
"isInheritable": false,
"position": 20
},
{
"type": "relation",
"name": "internalLink",
"value": "GLks18SNjxmC",
"value": "SynTBQiBsdYJ",
"isInheritable": false,
"position": 30
},
@@ -14787,19 +14787,19 @@
"isInheritable": false,
"position": 30
},
{
"type": "label",
"name": "shareAlias",
"value": "widget-basics",
"isInheritable": false,
"position": 20
},
{
"type": "relation",
"name": "internalLink",
"value": "s8alTXmpFR61",
"isInheritable": false,
"position": 40
},
{
"type": "label",
"name": "shareAlias",
"value": "widget-basics",
"isInheritable": false,
"position": 20
}
],
"format": "markdown",
@@ -14949,21 +14949,21 @@
{
"type": "relation",
"name": "internalLink",
"value": "m1lbrzyKDaRB",
"value": "yIhgI5H7A2Sm",
"isInheritable": false,
"position": 50
},
{
"type": "relation",
"name": "internalLink",
"value": "s8alTXmpFR61",
"value": "m1lbrzyKDaRB",
"isInheritable": false,
"position": 60
},
{
"type": "relation",
"name": "internalLink",
"value": "yIhgI5H7A2Sm",
"value": "s8alTXmpFR61",
"isInheritable": false,
"position": 70
},