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 Doran8494e0c08ad2
diff --cc CLAUDE.mdindex 4fb8a3fe1d,1b90b02881..ebed3e69a6--- a/CLAUDE.md+++ b/CLAUDE.md@@@ -2,156 -2,132 +2,175 @@@This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.+ > **Note**: When updating this file, also update `.github/copilot-instructions.md` to keep both AI coding assistants in sync.+## Overview-Trilium Notes is a hierarchical note-taking application with advanced features like synchronization, scripting, and rich text editing. It's built as a TypeScript monorepo using pnpm, with multiple applications and shared packages.+Trilium Notes is a hierarchical note-taking application with synchronization, scripting, and rich text editing. TypeScript monorepo using pnpm with multiple apps and shared packages.## Development Commands-### Setup-- `pnpm install` - Install all dependencies-- `corepack enable` - Enable pnpm if not available--### Running Applications-- `pnpm run server:start` - Start development server (http://localhost:8080)-- `pnpm run server:start-prod` - Run server in production mode--### Building-- `pnpm run client:build` - Build client application-- `pnpm run server:build` - Build server application-- `pnpm run electron:build` - Build desktop application--### Testing-- `pnpm test:all` - Run all tests (parallel + sequential)-- `pnpm test:parallel` - Run tests that can run in parallel-- `pnpm test:sequential` - Run tests that must run sequentially (server, ckeditor5-mermaid, ckeditor5-math)-- `pnpm coverage` - Generate coverage reports--## Architecture Overview--### Monorepo Structure-- **apps/**: Runnable applications- - `client/` - Frontend application (shared by server and desktop)- - `server/` - Node.js server with web interface- - `desktop/` - Electron desktop application- - `web-clipper/` - Browser extension for saving web content- - Additional tools: `db-compare`, `dump-db`, `edit-docs`--- **packages/**: Shared libraries- - `commons/` - Shared interfaces and utilities- - `ckeditor5/` - Custom rich text editor with Trilium-specific plugins- - `codemirror/` - Code editor customizations- - `highlightjs/` - Syntax highlighting- - Custom CKEditor plugins: `ckeditor5-admonition`, `ckeditor5-footnotes`, `ckeditor5-math`, `ckeditor5-mermaid`--### Core Architecture Patterns--#### Three-Layer Cache System-- **Becca** (Backend Cache): Server-side entity cache (`apps/server/src/becca/`)-- **Froca** (Frontend Cache): Client-side mirror of backend data (`apps/client/src/services/froca.ts`)-- **Shaca** (Share Cache): Optimized cache for shared/published notes (`apps/server/src/share/`)--#### Entity System-Core entities are defined in `apps/server/src/becca/entities/`:-- `BNote` - Notes with content and metadata-- `BBranch` - Hierarchical relationships between notes (allows multiple parents)-- `BAttribute` - Key-value metadata attached to notes-- `BRevision` - Note version history-- `BOption` - Application configuration--#### Widget-Based UI-Frontend uses a widget system (`apps/client/src/widgets/`):-- `BasicWidget` - Base class for all UI components-- `NoteContextAwareWidget` - Widgets that respond to note changes-- `RightPanelWidget` - Widgets displayed in the right panel+```bash+# Setup+corepack enable && pnpm install++# Run+pnpm server:start # Dev server at http://localhost:8080+pnpm desktop:start # Electron dev app+pnpm standalone:start # Standalone client dev++# Build+pnpm client:build # Frontend+pnpm server:build # Backend+pnpm desktop:build # Electron++# Test+pnpm test:all # All tests (parallel + sequential)+pnpm test:parallel # Client + most package tests+pnpm test:sequential # Server, ckeditor5-mermaid, ckeditor5-math (shared DB)+pnpm --filter server test # Single package tests+pnpm coverage # Coverage reports++# Lint & Format+pnpm dev:linter-check # ESLint check+pnpm dev:linter-fix # ESLint fix+pnpm dev:format-check # Format check (stricter stylistic rules)+pnpm dev:format-fix # Format fix+pnpm typecheck # TypeScript type check across all projects+```++**Running a single test file**: `pnpm --filter server test spec/etapi/search.spec.ts`++## Main Applications++The four main apps share `packages/trilium-core/` for business logic but differ in runtime:++- **client** (`apps/client/`): Preact frontend with jQuery widget system. Shared UI layer used by both server and desktop.+- **server** (`apps/server/`): Node.js backend (Express, better-sqlite3). Serves the client and provides REST/WebSocket APIs.+- **desktop** (`apps/desktop/`): Electron wrapper around server + client, running both in a single process.+- **standalone** (`apps/client-standalone/` + `apps/standalone-desktop/`): Runs the entire stack in the browser — server logic compiled to WASM via sql.js, executed in a service worker. No Node.js dependency at runtime.++## Monorepo Structure++```+apps/+ client/ # Preact frontend (shared by server, desktop, standalone)+ server/ # Node.js backend (Express, better-sqlite3)+ desktop/ # Electron (bundles server + client)+ client-standalone/ # Standalone client (WASM + service workers, no Node.js)+ standalone-desktop/ # Standalone desktop variant+ server-e2e/ # Playwright E2E tests for server+ web-clipper/ # Browser extension+ website/ # Project website+ db-compare/, dump-db/, edit-docs/, build-docs/, icon-pack-builder/++packages/+ trilium-core/ # Core business logic: entities, services, SQL, sync+ commons/ # Shared interfaces and utilities+ ckeditor5/ # Custom rich text editor bundle+ codemirror/ # Code editor integration+ highlightjs/ # Syntax highlighting+ share-theme/ # Theme for shared/published notes+ ckeditor5-admonition/, ckeditor5-footnotes/, ckeditor5-math/, ckeditor5-mermaid/+ ckeditor5-keyboard-marker/, express-partial-content/, pdfjs-viewer/, splitjs/+ turndown-plugin-gfm/+```++Use `pnpm --filter <package-name> <command>` to run commands in specific packages.++## Core Architecture++### Three-Layer Cache System++All data access goes through cache layers — never bypass with direct DB queries:++- **Becca** (`packages/trilium-core/src/becca/`): Server-side entity cache. Access via `becca.notes[noteId]`.+- **Froca** (`apps/client/src/services/froca.ts`): Client-side mirror synced via WebSocket. Access via `froca.getNote()`.+- **Shaca** (`apps/server/src/share/`): Optimized cache for shared/published notes.++**Critical**: Always use cache methods, not direct DB writes. Cache methods create `EntityChange` records needed for synchronization.++### Entity System++Core entities live in `packages/trilium-core/src/becca/entities/` (not `apps/server/`):++- `BNote` — Notes with content and metadata+- `BBranch` — Multi-parent tree relationships (cloning supported)+- `BAttribute` — Key-value metadata (labels and relations)+- `BRevision` — Version history+- `BOption` — Application configuration+- `BBlob` — Binary content storage++Entities extend `AbstractBeccaEntity<T>` with built-in change tracking, hash generation, and date management.++### Entity Change & Sync Protocol++Every entity modification creates an `EntityChange` record driving sync:+1. Login with HMAC authentication (document secret + timestamp)+2. Push changes → Pull changes → Push again (conflict resolution)+3. Content hash verification with retry loop++Sync services: `packages/trilium-core/src/services/sync.ts`, `syncMutexService`, `syncUpdateService`.++### Widget-Based UI++Frontend widgets in `apps/client/src/widgets/`:+- `BasicWidget` / `TypedBasicWidget` — Base classes (jQuery `this.$widget` for DOM)+- `NoteContextAwareWidget` — Responds to note changes+- `RightPanelWidget` — Sidebar widgets with position ordering- Type-specific widgets in `type_widgets/` directory+**Widget lifecycle**: `doRenderBody()` for initial render, `refreshWithNote()` for note changes, `entitiesReloadedEvent({loadResults})` for entity updates. Uses jQuery — don't mix React patterns.++ #### Reusable Preact Components+ Common UI components are available in `apps/client/src/widgets/react/` — prefer reusing these over creating custom implementations:+ - `NoItems` - Empty state placeholder with icon and message (use for "no results", "too many items", error states)+ - `ActionButton` - Consistent button styling with icon support+ - `FormTextBox` - Text input with validation and controlled input handling+ - `Slider` - Range slider with label+ - `Checkbox`, `RadioButton` - Form controls+ - `CollapsibleSection` - Expandable content sections+-#### API Architecture-- **Internal API**: REST endpoints in `apps/server/src/routes/api/`-- **ETAPI**: External API for third-party integrations (`apps/server/src/etapi/`)-- **WebSocket**: Real-time synchronization (`apps/server/src/services/ws.ts`)+Fluent builder pattern: `.child()`, `.class()`, `.css()` chaining with position-based ordering.-### Key Files for Understanding Architecture+### API Architecture-1. **Application Entry Points**:- - `apps/server/src/main.ts` - Server startup- - `apps/client/src/desktop.ts` - Client initialization+- **Internal API** (`apps/server/src/routes/api/`): REST endpoints, trusts frontend+- **ETAPI** (`apps/server/src/etapi/`): External API with basic auth tokens — maintain backwards compatibility+- **WebSocket** (`apps/server/src/services/ws.ts`): Real-time sync-2. **Core Services**:- - `apps/server/src/becca/becca.ts` - Backend data management- - `apps/client/src/services/froca.ts` - Frontend data synchronization- - `apps/server/src/services/backend_script_api.ts` - Scripting API+### Platform Abstraction-3. **Database Schema**:- - `apps/server/src/assets/db/schema.sql` - Core database structure+`packages/trilium-core/src/services/platform.ts` defines `PlatformProvider` interface with implementations in `apps/desktop/`, `apps/server/`, and `apps/client-standalone/`. Singleton via `initPlatform()`/`getPlatform()`.-4. **Configuration**:- - `package.json` - Project dependencies and scripts+**PlatformProvider** provides:+- `crash(message)` — Platform-specific fatal error handling+- `getEnv(key)` — Environment variable access (server/desktop use `process.env`, standalone maps URL query params like `?safeMode` → `TRILIUM_SAFE_MODE`)+- `isElectron`, `isMac`, `isWindows` — Platform detection flags-## Note Types and Features+**Critical rules for `trilium-core`**:+- **No `process.env` in core** — use `getPlatform().getEnv()` instead (not available in standalone/browser)+- **No `import path from "path"` in core** — Node's `path` module is externalized in browser builds. Use `packages/trilium-core/src/services/utils/path.ts` for `extname()`/`basename()` equivalents+- **No Node.js built-in modules in core** — core runs in both Node.js and the browser (standalone). Use platform-agnostic alternatives or platform providers+- **Platform detection via functions** — `isElectron()`, `isMac()`, `isWindows()` from `utils/index.ts` are functions (not constants) that call `getPlatform()`. They can only be called after `initializeCore()`, not at module top-level. If used in static definitions, wrap in a closure: `value: () => isWindows() ? "0.9" : "1.0"`+- **Barrel import caution** — `import { x } from "@triliumnext/core"` loads ALL core exports. Early-loading modules like `config.ts` should import specific subpaths (e.g. `@triliumnext/core/src/services/utils/index`) to avoid circular dependencies or initialization ordering issues+- **Electron IPC** — In desktop mode, client API calls use Electron IPC (not HTTP). The IPC handler in `apps/server/src/routes/electron.ts` must be registered via `utils.isElectron` from the **server's** utils (which correctly checks `process.versions["electron"]`), not from core's utils-Trilium supports multiple note types, each with specialized widgets:-- **Text**: Rich text with CKEditor5 (markdown import/export)-- **Code**: Syntax-highlighted code editing with CodeMirror-- **File**: Binary file attachments-- **Image**: Image display with editing capabilities-- **Canvas**: Drawing/diagramming with Excalidraw-- **Mermaid**: Diagram generation-- **Relation Map**: Visual note relationship mapping-- **Web View**: Embedded web pages-- **Doc/Book**: Hierarchical documentation structure+### Database-## Development Guidelines+SQLite via `better-sqlite3`. SQL abstraction in `packages/trilium-core/src/services/sql/` with `DatabaseProvider` interface, prepared statement caching, and transaction support.++- Schema: `apps/server/src/assets/db/schema.sql`+- Migrations: `apps/server/src/migrations/YYMMDD_HHMM__description.sql`+ ### Testing Strategy+ - Server tests run sequentially due to shared database+ - Client tests can run in parallel+ - E2E tests use Playwright for both server and desktop apps+ - Build validation tests check artifact integrity+ - **Write concise tests**: Group related assertions together in a single test case rather than creating many one-shot tests+ - **Extract and test business logic**: When adding pure business logic (e.g., data transformations, migrations, validations), extract it as a separate function and always write unit tests for it+-### Scripting System-Trilium provides powerful user scripting capabilities:-- Frontend scripts run in browser context-- Backend scripts run in Node.js context with full API access-- Script API documentation available in `docs/Script API/`-### Internationalization- Translation files in `apps/client/src/translations/`- Supported languages: English, German, Spanish, French, Romanian, Chinesediff --cc apps/client-standalone/package.jsonindex 09ab08f9e1,0000000000..216bb524fdmode 100644,000000..100644--- a/apps/client-standalone/package.json+++ b/apps/client-standalone/package.json@@@ -1,89 -1,0 +1,89 @@@+{+ "name": "@triliumnext/client-standalone",+ "version": "0.102.2",+ "description": "Standalone client for TriliumNext with SQLite WASM backend",+ "private": true,+ "license": "AGPL-3.0-only",+ "scripts": {+ "build": "cross-env NODE_OPTIONS=--max-old-space-size=4096 vite build",+ "dev": "vite dev",+ "test": "vitest",+ "start-prod": "pnpm build && pnpm vite preview --port 8888",+ "coverage": "vitest --coverage"+ },+ "dependencies": {+ "@excalidraw/excalidraw": "0.18.0",+ "@fullcalendar/core": "6.1.20",+ "@fullcalendar/daygrid": "6.1.20",+ "@fullcalendar/interaction": "6.1.20",+ "@fullcalendar/list": "6.1.20",+ "@fullcalendar/multimonth": "6.1.20",+ "@fullcalendar/timegrid": "6.1.20",+ "@maplibre/maplibre-gl-leaflet": "0.1.3",+ "@mermaid-js/layout-elk": "0.2.1",+ "@mind-elixir/node-menu": "5.0.1",+ "@popperjs/core": "2.11.8",+ "@preact/signals": "2.9.0",+ "@sqlite.org/sqlite-wasm": "3.51.1-build2",+ "@triliumnext/ckeditor5": "workspace:*",+ "@triliumnext/codemirror": "workspace:*",+ "@triliumnext/commons": "workspace:*",+ "@triliumnext/core": "workspace:*",+ "@triliumnext/highlightjs": "workspace:*",+ "@triliumnext/share-theme": "workspace:*",+ "@triliumnext/split.js": "workspace:*",+ "@zumer/snapdom": "2.7.0",+ "autocomplete.js": "0.38.1",+ "bootstrap": "5.3.8",+ "boxicons": "2.1.4",+ "clsx": "2.1.1",+ "color": "5.0.3",+ "debounce": "3.0.0",+ "draggabilly": "3.0.0",+ "fflate": "0.8.2",+ "force-graph": "1.51.2",+ "globals": "17.4.0",+ "i18next": "26.0.3",+ "i18next-http-backend": "3.0.4",+ "jquery": "4.0.0",+ "jquery.fancytree": "2.38.5",+ "js-md5": "0.8.3",+ "js-sha1": "0.7.0",+ "js-sha256": "0.11.1",+ "js-sha512": "0.9.0",+ "jsplumb": "2.15.6",+ "katex": "0.16.45",+ "knockout": "3.5.1",+ "leaflet": "1.9.4",+ "leaflet-gpx": "2.2.0",+ "mark.js": "8.11.1",- "marked": "17.0.5",++ "marked": "18.0.0",+ "mermaid": "11.14.0",+ "mind-elixir": "5.10.0",+ "normalize.css": "8.0.1",+ "panzoom": "9.4.4",+ "preact": "10.29.1",+ "react-i18next": "17.0.2",+ "react-window": "2.2.7",+ "reveal.js": "6.0.0",+ "svg-pan-zoom": "3.6.2",+ "tabulator-tables": "6.4.0",+ "vanilla-js-wheel-zoom": "9.0.4"+ },+ "devDependencies": {+ "@ckeditor/ckeditor5-inspector": "5.0.0",+ "@preact/preset-vite": "2.10.2",+ "@types/bootstrap": "5.2.10",+ "@types/jquery": "4.0.0",+ "@types/leaflet": "1.9.21",+ "@types/leaflet-gpx": "1.3.8",+ "@types/mark.js": "8.11.12",+ "@types/reveal.js": "5.2.2",+ "@types/tabulator-tables": "6.3.1",+ "copy-webpack-plugin": "14.0.0",+ "cross-env": "7.0.3",+ "happy-dom": "20.8.9",+ "script-loader": "0.7.2",+ "vite-plugin-static-copy": "4.0.1"+ }+}diff --cc apps/client/src/services/ws.tsindex 0b3b7eb464,b8c606d43b..23a24f5fc4--- a/apps/client/src/services/ws.ts+++ b/apps/client/src/services/ws.ts@@@ -59,43 -59,6 +59,43 @@@ export function unsubscribeToMessage(memessageHandlers = messageHandlers.filter(handler => handler !== messageHandler);}+/**+ * Dispatch a message to all handlers and process it.+ * This is the main entry point for incoming messages from any provider+ * (WebSocket, Worker, etc.)+ */+export async function dispatchMessage(message: WebSocketMessage) {+ // Notify all subscribers+ for (const messageHandler of messageHandlers) {+ messageHandler(message);+ }++ // Use string type for flexibility - server sends more message types than are typed+ const messageType = message.type as string;+ const msg = message as any;++ // Process the message+ if (messageType === "ping") {+ lastPingTs = Date.now();+ } else if (messageType === "reload-frontend") {+ utils.reloadFrontendApp("received request from backend to reload frontend");+ } else if (messageType === "frontend-update") {+ await executeFrontendUpdate(msg.data.entityChanges);+ } else if (messageType === "sync-hash-check-failed") {+ toastService.showError(t("ws.sync-check-failed"), 60000);+ } else if (messageType === "consistency-checks-failed") {+ toastService.showError(t("ws.consistency-checks-failed"), 50 * 60000);+ } else if (messageType === "api-log-messages") {+ appContext.triggerEvent("apiLogMessages", { noteId: msg.noteId, messages: msg.messages });+ } else if (messageType === "toast") {- toastService.showMessage(msg.message);++ toastService.showMessage(msg.message, msg.timeout);+ } else if (messageType === "execute-script") {+ const originEntity = msg.originEntityId ? await froca.getNote(msg.originEntityId) : null;++ bundleService.getAndExecuteBundle(msg.currentNoteId, originEntity, msg.script, msg.params);+ }+}+// used to serialize frontend update operationslet consumeQueuePromise: Promise<void> | null = null;diff --cc apps/client/src/setup.tsxindex 4d85277433,0000000000..6606baf4d2mode 100644,000000..100644--- a/apps/client/src/setup.tsx+++ b/apps/client/src/setup.tsx@@@ -1,524 -1,0 +1,524 @@@+import "./setup.css";++import { LOCALES, SetupSyncFromServerResponse } from "@triliumnext/commons";+import clsx from "clsx";+import { ComponentChildren, render } from "preact";+import { useEffect, useMemo, useRef, useState } from "preact/hooks";+import { useTranslation } from "react-i18next";++import logo from "./assets/icon-color.svg?url";+import { initLocale, t } from "./services/i18n";+import server from "./services/server";+import { isElectron, replaceHtmlEscapedSlashes } from "./services/utils";+import ActionButton from "./widgets/react/ActionButton";+import Admonition from "./widgets/react/Admonition";+import Button from "./widgets/react/Button";+import { Card, CardFrame, CardSection } from "./widgets/react/Card";+import FormGroup from "./widgets/react/FormGroup";+import FormList, { FormListItem } from "./widgets/react/FormList";+import FormTextBox from "./widgets/react/FormTextBox";+import Icon from "./widgets/react/Icon";++async function main() {+ await initLocale();++ const bodyWrapper = document.createElement("div");+ bodyWrapper.classList.add("setup-outer-wrapper");+ document.body.classList.add("setup");+ if (isElectron()) {+ document.body.classList.add("electron", `platform-${window.process.platform}`, "background-effects");+ }+ render(<App />, bodyWrapper);+ document.body.replaceChildren(bodyWrapper);+}++type State = "selectLanguage" | "firstOptions" | "createNewDocumentOptions" | "createNewDocumentWithDemo" | "createNewDocumentEmpty" | "syncFromDesktop" | "syncFromServer" | "syncFromServerInProgress" | "syncFromDesktopInProgress" | "syncFailed";++const STATE_ORDER: State[] = ["selectLanguage", "firstOptions", "createNewDocumentOptions", "createNewDocumentWithDemo", "createNewDocumentEmpty", "syncFromDesktop", "syncFromServer", "syncFromServerInProgress", "syncFromDesktopInProgress", "syncFailed"];++function renderState(state: State, setState: (state: State) => void) {+ switch (state) {+ case "selectLanguage": return <SelectLanguage setState={setState} />;+ case "firstOptions": return <SetupOptions setState={setState} />;+ case "createNewDocumentOptions": return <CreateNewDocumentOptions setState={setState} />;+ case "createNewDocumentWithDemo": return <CreateNewDocumentInProgress withDemo />;+ case "createNewDocumentEmpty": return <CreateNewDocumentInProgress />;+ case "syncFromServer": return <SyncFromServer setState={setState} />;+ case "syncFromDesktop": return <SyncFromDesktop setState={setState} />;+ case "syncFromServerInProgress": return <SyncInProgress device="server" />;+ case "syncFromDesktopInProgress": return <SyncInProgress device="desktop" />;+ default: return null;+ }+}++function App() {+ const [state, setState] = useState<State>("selectLanguage");+ const [prevState, setPrevState] = useState<State | null>(null);+ const [transitioning, setTransitioning] = useState(false);+ const prevStateRef = useRef<State>(state);++ function handleSetState(newState: State) {+ setPrevState(prevStateRef.current);+ prevStateRef.current = newState;+ setTransitioning(true);+ setState(newState);+ }++ const direction = prevState !== null+ ? STATE_ORDER.indexOf(state) > STATE_ORDER.indexOf(prevState) ? "forward" : "backward"+ : "forward";++ return (+ <div class="setup-container">+ <div class="drag-region" />+ {transitioning && prevState !== null && (+ <div+ class={`slide-page slide-out-${direction}`}+ onAnimationEnd={() => {+ setTransitioning(false);+ setPrevState(null);+ }}+ >+ {renderState(prevState, handleSetState)}+ </div>+ )}+ <div class={`slide-page ${transitioning ? `slide-in-${direction}` : "slide-current"}`} key={state}>+ {renderState(state, handleSetState)}+ </div>+ </div>+ );+}++function SelectLanguage({ setState }: { setState: (state: State) => void }) {+ const { t, i18n } = useTranslation();+ const [ currentLocale, setCurrentLocale ] = useState(i18n.language);+ const filteredLocales = useMemo(() => LOCALES.filter(l => !l.contentOnly), []);++ return (+ <SetupPage+ title={t("setup.language")}+ className="select-language"+ illustration={<Icon icon="bx bx-globe" className="illustration-icon" />}+ footer={<Button text={t("setup.continue")} kind="primary" onClick={() => setState("firstOptions")} />}+ >+ <FormList onSelect={async (id) => {+ await i18n.changeLanguage(id);+ setCurrentLocale(id);+ }}>+ {filteredLocales.map(locale => (+ <FormListItem key={locale.id} value={locale.id} active={locale.id === currentLocale}>{locale.name}</FormListItem>+ ))}+ </FormList>+ </SetupPage>+ );+}++function SetupOptions({ setState }: { setState: (state: State) => void }) {+ return (+ <SetupPage+ title={t("setup.heading")}+ className="setup-options-container"+ illustration={<img src={logo} alt="Setup illustration" className="illustration-logo" />}+ onBack={() => setState("selectLanguage")}+ >+ <div class="setup-options">+ <SetupOptionCard+ icon="bx bx-file-blank"+ title={t("setup.new-document")}+ description={t("setup.new-document-description")}+ onClick={() => setState("createNewDocumentOptions")}+ />++ <SetupOptionCard+ icon="bx bx-server"+ title={t("setup.sync-from-server")}+ description={t("setup.sync-from-server-description")}+ onClick={() => setState("syncFromServer")}+ />++ <SetupOptionCard+ icon="bx bx-desktop"+ title={t("setup.sync-from-desktop")}+ description={t("setup.sync-from-desktop-description")}+ disabled={glob.isStandalone}+ onClick={() => setState("syncFromDesktop")}+ />+ </div>+ </SetupPage>+ );+}++type SyncStep = "connecting" | "syncing" | "finalizing";++function getSyncStep(stats: { outstandingPullCount: number; totalPullCount: number | null; initialized: boolean }): SyncStep {+ if (stats.initialized) {+ return "finalizing"; // will reload momentarily+ }+ if (stats.totalPullCount !== null && stats.outstandingPullCount > 0) {+ return "syncing";+ }+ if (stats.totalPullCount !== null && stats.outstandingPullCount === 0) {+ return "finalizing";+ }+ return "connecting";+}++function SyncInProgress({ device }: { device: "server" | "desktop" }) {+ const stats = useOutstandingSyncInfo();+ const step = getSyncStep(stats);++ useEffect(() => {+ if (stats.initialized) {+ onSetupFinished();+ }+ }, [stats.initialized]);++ const steps: { key: SyncStep; label: string }[] = [+ { key: "connecting", label: t("setup.sync-step-connecting") },+ { key: "syncing", label: t("setup.sync-step-syncing") },+ { key: "finalizing", label: t("setup.sync-step-finalizing") }+ ];++ const currentIndex = steps.findIndex((s) => s.key === step);++ const syncingDone = currentIndex > steps.findIndex((s) => s.key === "syncing");+ let progress = 0;+ if (syncingDone) {+ progress = 100;+ } else if (stats.totalPullCount) {+ progress = Math.round(((stats.totalPullCount - stats.outstandingPullCount) / stats.totalPullCount) * 100);+ }++ return (+ <SetupPage+ className="sync-in-progress"+ illustration={<SyncIllustration targetDevice={device} />}+ title={t("setup.sync-in-progress-title")}+ >+ <Card className="sync-steps">+ {steps.map((s, i) => (+ <CardSection className={i < currentIndex ? "completed" : i === currentIndex ? "active" : ""} key={s.key}>+ <Icon icon={i < currentIndex ? "bx bx-check-circle" : i === currentIndex ? "bx bx-loader-circle bx-spin" : "bx bx-circle"} />{" "}+ {s.label}+ {s.key === "syncing" && (+ <div class="sync-progress">+ <progress value={syncingDone ? 1 : stats.totalPullCount! - stats.outstandingPullCount} max={syncingDone ? 1 : stats.totalPullCount!} />+ <span>{progress}%</span>+ </div>+ )}+ </CardSection>+ ))}+ </Card>+ </SetupPage>+ );+}++function useOutstandingSyncInfo() {+ const [ outstandingPullCount, setOutstandingPullCount ] = useState(0);+ const [ totalPullCount, setTotalPullCount ] = useState<number | null>(null);+ const [ initialized, setInitialized ] = useState(false);++ async function refresh() {+ const resp = await server.get<{ outstandingPullCount: number; totalPullCount: number | null; initialized: boolean }>("sync/stats");+ setOutstandingPullCount(resp.outstandingPullCount);+ setTotalPullCount(resp.totalPullCount);+ setInitialized(resp.initialized);+ }++ useEffect(() => {+ const interval = setInterval(refresh, 1000);+ refresh();++ return () => clearInterval(interval);+ }, []);+ return { outstandingPullCount, totalPullCount, initialized };+}++function CreateNewDocumentOptions({ setState }: { setState: (state: State) => void }) {+ return (+ <SetupPage+ className="create-new-document-options"+ title={t("setup.create-new-document-options-title")}+ illustration={<Icon icon="bx bx-star" className="illustration-icon" />}+ onBack={() => setState("firstOptions")}+ >+ <div class="setup-options">+ <SetupOptionCard icon="bx bx-book-open" title={t("setup.create-new-document-options-with-demo")} description={t("setup.create-new-document-options-with-demo-description")} onClick={() => setState("createNewDocumentWithDemo")} />+ <SetupOptionCard icon="bx bx-file-blank" title={t("setup.create-new-document-options-empty")} description={t("setup.create-new-document-options-empty-description")} onClick={() => setState("createNewDocumentEmpty")} />+ </div>+ </SetupPage>+ );+}++function CreateNewDocumentInProgress({ withDemo = false }: { withDemo?: boolean }) {+ useEffect(() => {+ server.post(`setup/new-document${withDemo ? "" : "?skipDemoDb"}`).then(onSetupFinished);+ }, [ withDemo ]);++ return (+ <SetupPage+ className="create-new-document"+ title={t("setup.create-new-document-title")}+ description={t("setup.create-new-document-description")}+ illustration={<Icon icon="bx bx-loader-circle bx-spin" className="illustration-icon" />}+ />+ );+}++function SyncFromServer({ setState }: { setState: (state: State) => void }) {+ const [ syncServerHost, setSyncServerHost ] = useState("");+ const [ password, setPassword ] = useState("");+ const [ syncProxy, setSyncProxy ] = useState("");+ const [ error, setError ] = useState<string | null>(null);+ const [ errorId, setErrorId ] = useState(0);+ const [ isWrongPassword, setIsWrongPassword ] = useState(false);+ const isValid = syncServerHost.trim() !== "" && password !== "";++ function raiseError(message: string) {+ setError(message);+ setErrorId(id => id + 1);+ }++ async function handleFinishSetup() {+ try {+ const resp = await server.post<SetupSyncFromServerResponse>("setup/sync-from-server", {- syncServerHost: syncServerHost.trim(),++ syncServerHost: syncServerHost.trim().replace(/\/+$/, ""),+ syncProxy: syncProxy.trim(),+ password+ });++ if (resp.result === "success") {+ setState("syncFromServerInProgress");+ } else if (resp.error.includes("Incorrect password")) {+ setIsWrongPassword(true);+ } else {+ raiseError(t("setup.sync-failed", { message: resp.error }));+ }+ } catch (e) {+ raiseError(e instanceof Error ? e.message : String(e));+ }+ }++ return (+ <SetupPage+ className="sync-from-server top-aligned"+ title={t("setup.sync-from-server")}+ description={t("setup.sync-from-server-page-description")}+ illustration={<SyncIllustration targetDevice="server" />}+ error={error}+ errorId={errorId}+ onBack={() => setState("firstOptions")}+ footer={<Button text={t("setup.button-finish-setup")} kind="primary" onClick={handleFinishSetup} disabled={!isValid} />}+ >+ <form>+ <Card>+ <CardSection>+ <FormGroup label={t("setup.server-host")} name="serverHost">+ <FormTextBox+ placeholder={t("setup.server-host-placeholder")}+ currentValue={syncServerHost} onChange={setSyncServerHost}+ autocomplete="trilium-sync-server-host"+ required+ />+ </FormGroup>+ </CardSection>++ <CardSection>+ <FormGroup+ label={t("setup.server-password")} name="serverPassword"+ error={isWrongPassword ? t("setup.wrong-password") : undefined}+ >+ <FormTextBox+ type="password"+ currentValue={password} onChange={setPassword}+ autocomplete="trilium-sync-server-password"+ required+ />+ </FormGroup>+ </CardSection>+ </Card>++ <Card heading={t("setup.advanced-options")}>+ <CardSection>+ <FormGroup+ name="proxyServer"+ label={t("setup.proxy-server")}+ description={isElectron() ? t("setup.proxy-instruction") : undefined}+ >+ <FormTextBox placeholder={t("setup.proxy-server-placeholder")} currentValue={syncProxy} onChange={setSyncProxy} />+ </FormGroup>+ </CardSection>+ </Card>+ </form>+ </SetupPage>+ );+}++function SyncFromDesktop({ setState }: { setState: (state: State) => void }) {+ const networkAddresses = getNetworkAddresses();++ useEffect(() => {+ const interval = setInterval(async () => {+ const status = await server.get<{ schemaExists: boolean }>("setup/status");+ if (status.schemaExists) {+ setState("syncFromDesktopInProgress");+ }+ }, 1000);+ return () => clearInterval(interval);+ }, [setState]);++ return (+ <SetupPage+ className="sync-from-desktop"+ title={t("setup.sync-from-desktop")}+ illustration={<SyncIllustration targetDevice="desktop" />}+ onBack={() => setState("firstOptions")}+ >+ <div class="card-columns">+ <Card heading="On the other device">+ <CardSection>1. {t("setup.sync-from-desktop-step1")}</CardSection>+ <CardSection>2. {t("setup.sync-from-desktop-step2")}</CardSection>+ <CardSection>3. {t("setup.sync-from-desktop-step3")}</CardSection>+ <CardSection>4. {t("setup.sync-from-desktop-step4")}</CardSection>+ <CardSection>5. {t("setup.sync-from-desktop-step5")}</CardSection>+ </Card>++ {networkAddresses.length > 0 && (+ <Card heading={t("setup.your-ip-addresses")} className="ip-addresses">+ {networkAddresses.map((addr) => (+ <CardSection key={addr}>{addr}</CardSection>+ ))}+ </Card>+ )}+ </div>++ <div class="sync-from-desktop-waiting">+ <div class="main"><Icon icon="bx bx-loader-circle bx-spin" />{" "} {t("setup.sync-from-desktop-waiting")}</div>+ <div class="subtle">{t("setup.sync-from-desktop-warning")}</div>+ </div>+ </SetupPage>+ );+}++function SyncIllustration({ targetDevice }: { targetDevice: "desktop" | "server" }) {+ return (+ <div class="sync-illustration">+ <div>+ <Icon icon={isElectron() ? "bx bx-desktop" : "bx bx-globe"} />+ {t("setup.sync-illustration-this-device")}+ </div>+ <div class="sync-illustration-arrows" />+ <div>+ <Icon icon={targetDevice === "desktop" ? "bx bx-desktop" : "bx bx-server"} />+ {targetDevice === "desktop" ? t("setup.sync-illustration-desktop-app") : t("setup.sync-illustration-server")}+ </div>+ </div>+ );+}++function SetupOptionCard({ title, description, icon, onClick, disabled }: { title: string; description: string, icon: string, onClick?: () => void, disabled?: boolean }) {+ return (+ <CardFrame+ className={clsx("setup-option-card", { disabled })}+ onClick={disabled ? undefined : onClick}+ >+ <Icon icon={icon} />++ <div>+ <h3>{title}</h3>+ <p>{description}</p>+ </div>+ </CardFrame>+ );+}++function SetupPage({ title, description, className, illustration, children, footer, error, errorId, onBack }: {+ title: string;+ description?: string;+ error?: string | null;+ errorId?: number;+ className?: string;+ illustration?: ComponentChildren;+ children?: ComponentChildren;+ footer?: ComponentChildren;+ onBack?: () => void;+}) {+ const [ showError, setShowError ] = useState(!!error);+ useEffect(() => {+ if (error) {+ setShowError(true);+ }+ }, [ error, errorId ]);++ return (+ <div className={clsx("page", className, { "contentless": !children })}>+ {onBack && (+ <Button+ className="back-button"+ icon="bx bx-arrow-back"+ text={t("setup.button-back")}+ onClick={onBack}+ kind="lowProfile"+ />+ )}+ {error && showError && (+ <Admonition className="page-error" type="caution">+ <ActionButton icon="bx bx-x" text={t("setup.dismiss-error")} onClick={() => setShowError(false)} />+ {replaceHtmlEscapedSlashes(error)}+ </Admonition>+ )}++ {illustration}+ <h1>{title}</h1>+ {description && <p class="page-description">{description}</p>}+ {children && <main>+ {children}+ </main>}+ {footer && <footer>{footer}</footer>}+ </div>+ );+}++function getNetworkAddresses(): string[] {+ if (!isElectron()) {+ return [`${location.protocol}//${location.host}`];+ }++ // eslint-disable-next-line @typescript-eslint/no-require-imports+ const os = require("os") as typeof import("os");+ const interfaces = os.networkInterfaces();+ const addresses: string[] = [];++ for (const nets of Object.values(interfaces)) {+ if (!nets) continue;+ for (const net of nets) {+ if (net.internal) continue;+ if (net.family === "IPv6" && net.scopeid !== 0) continue;+ addresses.push(net.address);+ }+ }++ // Sort by likelihood of being the local network address.+ addresses.sort((a, b) => networkScore(a) - networkScore(b));++ return addresses.map((addr) => `${location.protocol}//${addr}:${location.port}`);+}++function networkScore(addr: string): number {+ if (addr.startsWith("192.168.")) return 0;+ if (addr.startsWith("10.")) return 1;+ if (/^172\.(1[6-9]|2\d|3[01])\./.test(addr)) return 2;+ if (addr.includes(":")) return 4; // IPv6+ return 3;+}++function onSetupFinished() {+ if (isElectron()) {+ // On Electron we need to use the setup route because it handles the closing of the setup window and opening the main app window.+ location.href = "setup";+ } else {+ location.reload();+ }+}++main();diff --cc apps/edit-docs/src/edit-demo.tsindex 915d7c857e,d1430b567c..af7dd1e0c7--- a/apps/edit-docs/src/edit-demo.ts+++ b/apps/edit-docs/src/edit-demo.ts@@@ -1,9 -1,11 +1,11 @@@+ import { createZipFromDirectory, extractZip, importData, initializeDatabase, startElectron } from "./utils.js";+ import { initializeTranslations } from "@triliumnext/server/src/services/i18n.js";import debounce from "@triliumnext/client/src/services/debounce.js";+import cls from "@triliumnext/server/src/services/cls.js";import fs from "fs/promises";import { join } from "path";-- import { extractZip, importData, startElectron } from "./utils.js";-import cls from "@triliumnext/server/src/services/cls.js";+ import type { NoteMetaFile } from "@triliumnext/server/src/services/meta/note_meta.js";+ import type NoteMeta from "@triliumnext/server/src/services/meta/note_meta.js";// Paths are relative to apps/edit-docs/dist.const DEMO_ZIP_PATH = join(__dirname, "../../server/src/assets/db/demo.zip");@@@ -15,7 -17,13 +17,13 @@@ async function main()setTimeout(() => registerHandlers(), 10_000);});- // TODO: Initialize core.+ await initializeTranslations();+ await initializeDatabase(true);++ // Wait for becca to be loaded before importing data- const beccaLoader = await import("@triliumnext/server/src/becca/becca_loader.js");- await beccaLoader.beccaLoaded;++ const { becca_loader } = await import("@triliumnext/core");++ await becca_loader.beccaLoaded;+cls.init(async () => {await importData(DEMO_ZIP_DIR_PATH);setOptions();@@@ -54,8 -68,32 +68,32 @@@ async function registerHandlers()}async function exportData() {- const { exportToZipFile } = (await import("@triliumnext/server/src/services/export/zip.js")).default;- await exportToZipFile("root", "html", DEMO_ZIP_PATH);+ const { zipExportService } = (await import("@triliumnext/core"));+ await zipExportService.exportToZipFile("root", "html", DEMO_ZIP_PATH);}+ const EXPANDED_NOTE_IDS = new Set([+ "root",+ "rvaX6hEaQlmk" // Trilium Demo+ ]);++ async function cleanUpMeta(dirPath: string) {+ const metaPath = join(dirPath, "!!!meta.json");+ const meta = JSON.parse(await fs.readFile(metaPath, "utf-8")) as NoteMetaFile;++ for (const file of meta.files) {+ file.notePosition = 1;+ traverse(file);+ }++ function traverse(el: NoteMeta) {+ el.isExpanded = EXPANDED_NOTE_IDS.has(el.noteId);+ for (const child of el.children || []) {+ traverse(child);+ }+ }++ await fs.writeFile(metaPath, JSON.stringify(meta, null, 4));+ }+main();diff --cc apps/server/package.jsonindex 6f3741ad8e,5ac26c539a..91d9a3b6bc--- a/apps/server/package.json+++ b/apps/server/package.json@@@ -30,16 -30,16 +30,16 @@@"proxy-nginx-subdir": "docker run --name trilium-nginx-subdir --rm --network=host -v ./docker/nginx.conf:/etc/nginx/conf.d/default.conf:ro nginx:latest"},"dependencies": {- "@ai-sdk/anthropic": "3.0.66",- "@ai-sdk/google": "3.0.58",- "@ai-sdk/openai": "3.0.50",+ "@ai-sdk/anthropic": "3.0.68",+ "@ai-sdk/google": "3.0.60",+ "@ai-sdk/openai": "3.0.52","@modelcontextprotocol/sdk": "^1.12.1",- "ai": "6.0.146",+ "ai": "6.0.153","better-sqlite3": "12.8.0","html-to-text": "9.0.5",+ "i18next-fs-backend": "2.6.3",+ "i18next": "26.0.3","js-yaml": "4.1.1",- "node-html-parser": "7.1.0",- "sucrase": "3.35.1","unpdf": "1.4.0"},"devDependencies": {@@@ -73,7 -77,8 +73,6 @@@"@types/ws": "8.18.1","@types/xml2js": "0.4.14","archiver": "7.0.1",- "axios": "1.14.0",- "async-mutex": "0.5.0",- "chardet": "2.1.1","cheerio": "1.2.0","chokidar": "5.0.0","cls-hooked": "4.2.2",@@@ -101,8 -109,9 +100,8 @@@"ini": "6.0.0","is-animated": "2.0.2","is-svg": "6.1.0",- "jimp": "1.6.0",- "marked": "17.0.5",+ "jimp": "1.6.1",+ "marked": "18.0.0",- "mime-types": "3.0.2","multer": "2.1.1","normalize-strings": "1.1.1","officeparser": "6.0.7",@@@ -117,7 -129,9 +116,7 @@@"time2fa": "1.4.2","tmp": "0.2.5","turnish": "1.8.0",- "vite": "8.0.5",- "unescape": "1.0.1",+ "vite": "8.0.7",- "ws": "8.20.0","xml2js": "0.6.2","yauzl": "3.3.0"}diff --cc apps/server/src/routes/api/database.tsindex 08dc05121e,e014676712..ef73983bde--- a/apps/server/src/routes/api/database.ts+++ b/apps/server/src/routes/api/database.ts@@@ -1,9 -1,10 +1,10 @@@import { BackupDatabaseNowResponse, DatabaseCheckIntegrityResponse } from "@triliumnext/commons";+import { becca_loader, ValidationError } from "@triliumnext/core";- import type { Request } from "express";- import { readFileSync } from "fs";+ import type { Request, Response } from "express";-import fs from "fs";++import fs, { readFileSync } from "fs";+ import path from "path";-import becca_loader from "../../becca/becca_loader.js";-import ValidationError from "../../errors/validation_error.js";+import { getIntegrationTestDbPath } from "../../core_assets.js";import anonymizationService from "../../services/anonymization.js";import backupService from "../../services/backup.js";import consistencyChecksService from "../../services/consistency_checks.js";diff --cc apps/server/src/services/sql_init.tsindex 0b09bdc9a5,5212cfb6e5..c8a624b660--- a/apps/server/src/services/sql_init.ts+++ b/apps/server/src/services/sql_init.ts@@@ -1,22 -1,248 +1,18 @@@- import { type OptionRow } from "@triliumnext/commons";-import log from "./log.js";-import fs from "fs";-import resourceDir from "./resource_dir.js";-import sql from "./sql.js";-import { isElectron } from "./utils.js";-import optionService from "./options.js";-import port from "./port.js";-import BOption from "../becca/entities/boption.js";-import TaskContext from "./task_context.js";-import migrationService from "./migration.js";-import cls from "./cls.js";-import config from "./config.js";-import { deferred, type OptionRow } from "@triliumnext/commons";-import BNote from "../becca/entities/bnote.js";-import BBranch from "../becca/entities/bbranch.js";-import zipImportService from "./import/zip.js";-import password from "./encryption/password.js";-import backup from "./backup.js";-import eventService from "./events.js";-import { t } from "i18next";-import hidden_subtree from "./hidden_subtree.js";++import type { OptionRow } from "@triliumnext/commons";+import { sql_init as coreSqlInit } from "@triliumnext/core";- const schemaExists = coreSqlInit.schemaExists;- const isDbInitialized = coreSqlInit.isDbInitialized;- const dbReady = coreSqlInit.dbReady;- const setDbAsInitialized = coreSqlInit.setDbAsInitialized;- const createInitialDatabase = coreSqlInit.createInitialDatabase;- const initializeDb = coreSqlInit.initializeDb;-export const dbReady = deferred<void>();++export type { OptionRow };+-function schemaExists() {- return !!sql.getValue(/*sql*/`SELECT name FROM sqlite_master- WHERE type = 'table' AND name = 'options'`);-}--function isDbInitialized() {- if (!schemaExists()) {- return false;- }-- const initialized = sql.getValue("SELECT value FROM options WHERE name = 'initialized'");-- return initialized === "true";-}--async function initDbConnection() {- if (!isDbInitialized()) {- if (isElectron) {- log.info(t("sql_init.db_not_initialized_desktop"));- } else {- log.info(t("sql_init.db_not_initialized_server", { port }));- }-- return;- }-- await migrationService.migrateIfNecessary();-- sql.execute('CREATE TEMP TABLE IF NOT EXISTS "param_list" (`paramId` TEXT NOT NULL PRIMARY KEY)');-- sql.execute(`- CREATE TABLE IF NOT EXISTS "user_data"- (- tmpID INT,- username TEXT,- email TEXT,- userIDEncryptedDataKey TEXT,- userIDVerificationHash TEXT,- salt TEXT,- derivedKey TEXT,- isSetup TEXT DEFAULT "false",- UNIQUE (tmpID),- PRIMARY KEY (tmpID)- );`)-- dbReady.resolve();-}--/**- * Applies the database schema, creating the necessary tables and importing the demo content.- *- * @param skipDemoDb if set to `true`, then the demo database will not be imported, resulting in an empty root note.- * @throws {Error} if the database is already initialized.- */-async function createInitialDatabase(skipDemoDb?: boolean) {- if (isDbInitialized()) {- throw new Error("DB is already initialized");- }-- const schema = fs.readFileSync(`${resourceDir.DB_INIT_DIR}/schema.sql`, "utf-8");- const demoFile = (!skipDemoDb ? fs.readFileSync(`${resourceDir.DB_INIT_DIR}/demo.zip`) : null);-- let rootNote!: BNote;-- // We have to import async since options init requires keyboard actions which require translations.- const optionsInitService = (await import("./options_init.js")).default;- const becca_loader = (await import("../becca/becca_loader.js")).default;-- sql.transactional(() => {- log.info("Creating database schema ...");-- sql.executeScript(schema);-- becca_loader.load();-- log.info("Creating root note ...");-- rootNote = new BNote({- noteId: "root",- title: "root",- type: "text",- mime: "text/html"- }).save();-- rootNote.setContent("");-- new BBranch({- noteId: "root",- parentNoteId: "none",- isExpanded: true,- notePosition: 10- }).save();-- optionsInitService.initDocumentOptions();- optionsInitService.initNotSyncedOptions(true, {});- optionsInitService.initStartupOptions();- password.resetPassword();- });-- // Check hidden subtree.- // This ensures the existence of system templates, for the demo content.- console.log("Checking hidden subtree at first start.");- cls.init(() => hidden_subtree.checkHiddenSubtree());-- // Import demo content.- log.info("Importing demo content...");-- const dummyTaskContext = new TaskContext("no-progress-reporting", "importNotes", null);-- if (demoFile) {- await zipImportService.importZip(dummyTaskContext, demoFile, rootNote);- }-- // Post-demo.- sql.transactional(() => {- // this needs to happen after ZIP import,- // the previous solution was to move option initialization here, but then the important parts of initialization- // are not all in one transaction (because ZIP import is async and thus not transactional)-- const startNoteId = sql.getValue("SELECT noteId FROM branches WHERE parentNoteId = 'root' AND isDeleted = 0 AND noteId != '_hidden' ORDER BY notePosition") || "root";-- optionService.setOption(- "openNoteContexts",- JSON.stringify([- {- notePath: startNoteId,- active: true- }- ])- );- });-- log.info("Schema and initial content generated.");-- initDbConnection();-}--async function createDatabaseForSync(options: OptionRow[], syncServerHost = "", syncProxy = "") {- log.info("Creating database for sync");-- if (isDbInitialized()) {- throw new Error("DB is already initialized");- }-- const schema = fs.readFileSync(`${resourceDir.DB_INIT_DIR}/schema.sql`, "utf8");-- // We have to import async since options init requires keyboard actions which require translations.- const optionsInitService = (await import("./options_init.js")).default;-- sql.transactional(() => {- sql.executeScript(schema);-- optionsInitService.initNotSyncedOptions(false, { syncServerHost, syncProxy });-- // document options required for sync to kick off- for (const opt of options) {- new BOption(opt).save();- }- });-- log.info("Schema and not synced options generated.");-}--function setDbAsInitialized() {- if (!isDbInitialized()) {- optionService.setOption("initialized", "true");-- initDbConnection();-- // Emit an event to notify that the database is now initialized- eventService.emit(eventService.DB_INITIALIZED);-- log.info("Database initialization completed, emitted DB_INITIALIZED event");- }-}--function optimize() {- if (config.General.readOnly) {- return;- }- log.info("Optimizing database");- const start = Date.now();-- sql.execute("PRAGMA optimize");-- log.info(`Optimization finished in ${Date.now() - start}ms.`);-}--export function getDbSize() {- return sql.getValue<number>("SELECT page_count * page_size / 1000 as size FROM pragma_page_count(), pragma_page_size()");-}--function initializeDb() {- cls.init(initDbConnection);-- dbReady.then(() => {- if (config.General && config.General.noBackup === true) {- log.info("Disabling scheduled backups.");-- return;- }-- setInterval(() => backup.regularBackup(), 4 * 60 * 60 * 1000);-- // kickoff first backup soon after start up- setTimeout(() => backup.regularBackup(), 5 * 60 * 1000);-- // optimize is usually inexpensive no-op, so running it semi-frequently is not a big deal- setTimeout(() => optimize(), 60 * 60 * 1000);-- setInterval(() => optimize(), 10 * 60 * 60 * 1000);- });-}++export const dbReady = coreSqlInit.dbReady;+export const getDbSize = coreSqlInit.getDbSize;- const createDatabaseForSync = coreSqlInit.createDatabaseForSync;export default {-- dbReady,-- schemaExists,-- isDbInitialized,-- createInitialDatabase,-- createDatabaseForSync,-- setDbAsInitialized,-- getDbSize,-- initializeDb++ dbReady: coreSqlInit.dbReady,++ schemaExists: coreSqlInit.schemaExists,++ isDbInitialized: coreSqlInit.isDbInitialized,++ createInitialDatabase: coreSqlInit.createInitialDatabase,++ createDatabaseForSync: coreSqlInit.createDatabaseForSync,++ setDbAsInitialized: coreSqlInit.setDbAsInitialized,++ getDbSize: coreSqlInit.getDbSize,++ initializeDb: coreSqlInit.initializeDb};diff --cc packages/trilium-core/src/services/backend_script_api.tsindex 1ce6fc13eb,c7526654af..ef877a79bd--- a/packages/trilium-core/src/services/backend_script_api.ts+++ b/packages/trilium-core/src/services/backend_script_api.ts@@@ -1,15 -1,13 +1,16 @@@-import type { AttributeRow } from "@triliumnext/commons";-import { dayjs } from "@triliumnext/commons";-import { formatLogMessage } from "@triliumnext/commons";+import { type AttributeRow, dayjs, formatLogMessage } from "@triliumnext/commons";+import AbstractBeccaEntity from "../becca/entities/abstract_becca_entity";+import Becca from "../becca/becca-interface";+import axios from "axios";import * as cheerio from "cheerio";+ import * as htmlParser from "node-html-parser";import xml2js from "xml2js";-+import branchService from "./branches";+import { NoteParams } from "./notes.js";+import SearchContext from "./search/search_context";+import syncMutex from "./sync_mutex";+import zipExportService from "./export/zip";import becca from "../becca/becca.js";-import type Becca from "../becca/becca-interface.js";-import type AbstractBeccaEntity from "../becca/entities/abstract_becca_entity.js";import type BAttachment from "../becca/entities/battachment.js";import type BAttribute from "../becca/entities/battribute.js";import type BBranch from "../becca/entities/bbranch.js";diff --cc packages/trilium-core/src/services/script.tsindex bbe58f8cab,c030aae86a..d4fbb73df5--- a/packages/trilium-core/src/services/script.ts+++ b/packages/trilium-core/src/services/script.ts@@@ -1,13 -1,13 +1,15 @@@+import { ScriptParams } from "@triliumnext/commons";+ import { t } from "i18next";import { transform } from "sucrase";-import becca from "../becca/becca.js";+import type Becca from "../becca/becca-interface.js";import type BNote from "../becca/entities/bnote.js";import type { ApiParams } from "./backend_script_api_interface.js";-import cls from "./cls.js";-import log from "./log.js";+import { getLog } from "./log.js";import ScriptContext from "./script_context.js";+import { getContext } from "./context.js";+import { unwrapStringOrBuffer } from "./utils/binary.js";+ import ws from "./ws.js";export interface Bundle {note?: BNote;@@@ -18,10 -18,28 +20,26 @@@allNoteIds?: string[];}-type ScriptParams = any[];-function executeNote(note: BNote, apiParams: ApiParams) {- if (!note.isJavaScript() || note.getScriptEnv() !== "backend" || !note.isContentAvailable()) {+ if (!note.isContentAvailable()) {+ throw new Error(`Cannot execute script note '${note.noteId}' because it is protected and protected session is not available. Enter protected session and try again.`);+ }++ if (!note.isJavaScript() || note.getScriptEnv() !== "backend") {- log.info(`Cannot execute note ${note.noteId} "${note.title}", note must be of type "Code: JS backend"`);+ getLog().info(`Cannot execute note ${note.noteId} "${note.getTitleOrProtected()}", note must be of type "Code: JS backend"`);+ // Warn the user if they're trying to run a frontend script in the backend+ const actualEnv = note.getScriptEnv();+ if (note.isJavaScript() && actualEnv === "frontend") {+ const message = t("script.wrong-environment", {- noteTitle: note.title,++ noteTitle: note.getTitleOrProtected(),+ noteId: note.noteId,+ actualEnv: "frontend",+ expectedEnv: "backend"+ });+ ws.sendMessageToAllClients({ type: "toast", message, timeout: 10000 });+ }+return;}@@@ -119,6 -137,20 +137,20 @@@ function getParams(params?: ScriptParam}function getScriptBundleForFrontend(note: BNote, script?: string, params?: ScriptParams) {+ // Warn the user if they're trying to run a backend script in the frontend+ if (note.isJavaScript() && note.getScriptEnv() === "backend") {- log.info(`Cannot execute note ${note.noteId} "${note.title}" in frontend, note is of type "Code: JS backend"`);++ getLog().info(`Cannot execute note ${note.noteId} "${note.getTitleOrProtected()}" in frontend, note is of type "Code: JS backend"`);++ const message = t("script.wrong-environment", {- noteTitle: note.title,++ noteTitle: note.getTitleOrProtected(),+ noteId: note.noteId,+ actualEnv: "backend",+ expectedEnv: "frontend"+ });+ ws.sendMessageToAllClients({ type: "toast", message, timeout: 10000 });+ return;+ }+let overrideContent: string | null = null;if (script) {diff --cc packages/trilium-core/src/services/search/services/parse.tsindex c0a08d89d0,2d6092280b..6756c563f6--- a/packages/trilium-core/src/services/search/services/parse.ts+++ b/packages/trilium-core/src/services/search/services/parse.ts@@@ -1,5 -1,7 +1,6 @@@import { dayjs } from "@triliumnext/commons";+ import { t } from "i18next";-import { removeDiacritic } from "../../utils.js";import AncestorExp from "../expressions/ancestor.js";import AndExp from "../expressions/and.js";import AttributeExistsExp from "../expressions/attribute_exists.js";diff --cc pnpm-lock.yamlindex 603b6fb235,7a50c3fb77..abe72e5681--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@@ -165,29 -172,19 +172,26 @@@ importersspecifier: 6.0.2version: 6.0.2typescript-eslint:- specifier: 8.58.0- upath:- specifier: 2.0.1- version: 2.0.1+ specifier: 8.58.1vite:- specifier: 8.0.5- version: 8.0.5(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ specifier: 8.0.7+ version: 8.0.7(@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]))+ specifier: 4.1.3+ version: 4.1.3(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[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.4@@@ -420,225 -417,8 +424,225 @@@version: 0.7.2vite-plugin-static-copy:specifier: 4.0.1- version: 4.0.1([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 4.0.1([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.7.0+ version: 2.7.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: 26.0.3+ version: 26.0.3([email protected])+ i18next-http-backend:+ specifier: 3.0.4+ version: 3.0.4([email protected])+ jquery:+ specifier: 4.0.0+ version: 4.0.0+ jquery.fancytree:+ specifier: 2.38.5+ version: 2.38.5([email protected])+ js-md5:+ specifier: 0.8.3+ version: 0.8.3+ js-sha1:+ specifier: 0.7.0+ version: 0.7.0+ js-sha256:+ specifier: 0.11.1+ version: 0.11.1+ js-sha512:+ specifier: 0.9.0+ version: 0.9.0+ jsplumb:+ specifier: 2.15.6+ version: 2.15.6+ katex:+ specifier: 0.16.45+ version: 0.16.45+ knockout:+ specifier: 3.5.1+ version: 3.5.1+ leaflet:+ specifier: 1.9.4+ version: 1.9.4+ leaflet-gpx:+ specifier: 2.2.0+ version: 2.2.0+ mark.js:+ specifier: 8.11.1+ version: 8.11.1+ marked:- specifier: 17.0.5- version: 17.0.5++ specifier: 18.0.0++ version: 18.0.0+ mermaid:+ specifier: 11.14.0+ version: 11.14.0+ mind-elixir:+ specifier: 5.10.0+ version: 5.10.0+ normalize.css:+ specifier: 8.0.1+ version: 8.0.1+ panzoom:+ specifier: 9.4.4+ version: 9.4.4+ preact:+ specifier: 10.29.1+ version: 10.29.1+ react-i18next:+ specifier: 17.0.2+ version: 17.0.2([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]))+ 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: 4.0.1- version: 4.0.1([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))++ version: 4.0.1([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:@@@ -918,9 -704,12 +922,6 @@@archiver:specifier: 7.0.1version: 7.0.1- axios:- specifier: 1.14.0- version: 1.14.0([email protected])- async-mutex:- specifier: 0.5.0- version: 0.5.0- chardet:- specifier: 2.1.1- version: 2.1.1cheerio:specifier: 1.2.0version: 1.2.0@@@ -1003,11 -801,14 +1004,11 @@@specifier: 6.1.0version: 6.1.0jimp:- specifier: 1.6.0- version: 1.6.0+ specifier: 1.6.1+ version: 1.6.1marked:- specifier: 17.0.5- version: 17.0.5+ specifier: 18.0.0+ version: 18.0.0- mime-types:- specifier: 3.0.2- version: 3.0.2multer:specifier: 2.1.1version: 2.1.1@@@ -1050,9 -860,15 +1051,9 @@@turnish:specifier: 1.8.0version: 1.8.0- unescape:- specifier: 1.0.1- version: 1.0.1vite:- specifier: 8.0.5- version: 8.0.5(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ specifier: 8.0.7+ version: 8.0.7(@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@@@ -1634,64 -1450,9 +1635,64 @@@specifier: 20.8.9version: 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]))+ specifier: 4.1.3+ version: 4.1.3(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[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: 26.0.3+ version: 26.0.3([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:@@@ -4477,12 -4085,6 +4328,12 @@@ packages'@popperjs/[email protected]':resolution: {integrity: sha512-P1st0aksCrn9sGZhp8GMYwBnQsbvAWsZAX44oXNNvLHGqAOcoVxmjZiohstwQ7SqKnbR47akdNi+uleWD8+g6A==}+ '@preact/[email protected]':+ resolution: {integrity: sha512-K9wHlJOtkE+cGqlyQ5v9kL3Ge0Ql4LlIZjkUTL+1zf3nNdF88F9UZN6VTV8jdzBX9Fl7WSzeNMSDG7qECPmSmg==}+ peerDependencies:+ '@babel/core': 7.x- vite: 2.x || 3.x || 4.x || 5.x || 6.x || 7.x++ vite: '>=7.3.2'+'@preact/[email protected]':resolution: {integrity: sha512-p0vJpxiVO7KWWazWny3LUZ+saXyZKWv6Ju0bYMWNJRp2YveufRPgSUB1C4MTqGJfz07EehMgfN+AJNwQy+w6Iw==}peerDependencies:@@@ -18166,23 -17661,7 +17933,23 @@@ snapshots'@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+ picocolors: 1.1.1- vite: 8.0.5(@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.7(@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])