由 Kira 出售

TriliumNext Notes is an open-source, cross-platform hierarchical note-taking application for building large personal knowledge bases, featuring rich editing, scripting, encryption, and self-hosted sync.
This block provides the full backend source of TriliumNext (apps/server/src), a self-hosted note-taking application server built on Express and TypeScript. It includes routing, database access, ETAPI (REST), LLM/AI context services, sync, and share infrastructure. The target buyer is a developer embedding or extending a TriliumNext server instance in their own Node.js project.
main.ts - Application entry point; initializes i18n then starts the HTTP serverwww.ts - HTTP/HTTPS server bootstrap, port binding, socket setupapp.ts - Express application factory; registers all middleware and routersanonymize.ts - Database anonymization utility for safe data exportdocker_healthcheck.ts - Docker health-check script that pings the serverexpress.d.ts - Express Request type augmentation for Trilium-specific fieldstypes.d.ts - Global ambient type declarations shared across the backendbecca/ - In-memory note/attribute cache (Becca) and entity model classeserrors/ - Custom error classes used throughout the applicationetapi/ - ETAPI (External Trilium API) route handlers and validatorsmigrations/ - Database migration scripts indexed by versionroutes/ - Express route handlers for the main UI, API, and share endpointsservices/ - Core business logic: SQL, sync, options, LLM, search, scripting, and moreshare/ - Share-specific rendering and asset-serving logicassets/ - Static assets: DB schema, views (EJS templates), images, translations, config samplenpm install express express-session better-sqlite3 sanitize-html sanitize-filename
npm install i18next i18next-fs-backend i18next-http-middleware
npm install multer compression cookie-parser csurf rate-limiter-flexible
npm install winston dayjs xml2js jszip image-size sharp
npm install @electron/remote electron # only if running in Electron mode
No native pod/gradle linking is required for pure Node.js use.
better-sqlite3requires a native build step—ensure you havenode-gypand a C++ toolchain (build-essentialon Linux, Xcode CLT on macOS) before .
启动隔离沙箱并在服务器端直接运行 — 无需本地配置。
此版本的 Tetrees AI Review
This TypeScript cli / script completed archive review. Structure, dependency manifests, documentation, functional source, and common risk patterns were checked by the Tetrees verification pipeline; runtime phases are stated separately.
Deterministic AVCP artifact review
管道 avcp-2026-08-04.1 · SHA-256 6d8b2cfba09686c6…
This version-scoped review deterministically inspects the submitted archive for structure, dependencies, documentation, functional source, and common malicious or high-risk signals. Build and test phases are reported as passed only after an isolated sandbox audition. It is not a guarantee of perfect security.
审查日期 2026年8月4日
将此产品直接导入你的 AI IDE、网页构建器或云端 IDE。
将 Tetrees 连接到兼容的 AI IDE,列出你拥有的产品并获取已验证 ZIP,同时不会开放卖家上传权限。
暂无评价。
Sign in to join the discussion
Loading discussion…
npm installCopy the contents of the source/ directory into src/ (or any source root) of your Node.js TypeScript project.
In tsconfig.json, enable ESM and set the module resolution to bundler or node16:
{
"compilerOptions": {
"module": "NodeNext",
"moduleResolution": "NodeNext",
"target": "ES2022",
"outDir": "dist",
"rootDir": "src",
"esModuleInterop": true,
"strict": true
}
}
Set "type": "module" in your package.json so Node.js treats .js output files as ESM.
Provide a data/ directory (configurable via env) that Trilium uses for its SQLite database and config:
export TRILIUM_DATA_DIR=/absolute/path/to/data
export TRILIUM_NETWORK_ACCESS=true # expose to non-localhost
export TRILIUM_PORT=8080
If you have a package.json sibling to source/, ensure it has a version field — routes/index.ts imports it directly via ../../package.json.
Run the application:
node --experimental-vm-modules dist/main.js
// src/main.ts
async function startApplication(): Promise<void>;
Called once at process start. Initializes translations via initializeTranslations(), then dynamically imports and calls the default export of www.ts. Use this as your sole entry point; do not import www.ts directly before translations are ready.
import { initializeTranslations } from "./services/i18n.js";
await initializeTranslations(): Promise<void>;
Sets up i18next with filesystem backend and HTTP middleware integration. Must be awaited before any route handler that returns localized strings. Called automatically by startApplication().
async function getSemanticContext(
noteId: string,
options?: { maxSimilarNotes?: number }
): Promise<string>;
Returns a plain-text semantic context string for the given note ID by delegating to the AI service manager's context service. Use when building LLM prompts that need surrounding note content. Returns a safe fallback string on error rather than throwing.
import restChatService from "./services/llm/chat/index.js";
Handles REST-based LLM chat sessions. Exported as the default from the chat module. Use when you need to create or continue a ChatSession against any configured LLM backend (OpenAI, Anthropic, etc.).
import contextService from "./services/llm/context/services/index.js";
Central entry point for context extraction. Wraps ContextService and QueryProcessor. Use directly when you need to call processQuery outside the normal chat flow, e.g., a custom search route.
Embed the Trilium server inside another Node.js process, wait for it to be ready before continuing.
import { initializeTranslations } from "./src/services/i18n.js";
async function main() {
// Must happen before any module that uses translated strings
await initializeTranslations();
// Dynamically import avoids loading Express before i18n is ready
const startTriliumServer = (await import("./src/www.js")).default;
await startTriliumServer();
console.log("Trilium server is running");
}
main().catch((err) => {
console.error("Failed to start Trilium:", err);
process.exit(1);
});
Add a custom Express route that returns LLM-ready context for a note by ID.
import express from "express";
import { getSemanticContext } from "./src/services/llm/context/index.js";
const router = express.Router();
router.get("/api/custom/note-context/:noteId", async (req, res) => {
const { noteId } = req.params;
const maxSimilarNotes = parseInt(req.query.max as string) || 5;
try {
const context = await getSemanticContext(noteId, { maxSimilarNotes });
res.json({ noteId, context });
} catch (err) {
res.status(500).json({ error: "Context retrieval failed" });
}
});
export default router;
Decompose a user query into sub-queries before sending them to an LLM.
import { queryProcessor, contextService } from "./src/services/llm/context/services/index.js";
import type { DecomposedQuery } from "./src/services/llm/context/services/index.js";
async function buildAugmentedPrompt(userQuery: string, noteId: string): Promise<string> {
// contextService.processQuery accepts a query string, an LLM service, and options
const { default: aiServiceManager } = await import("./src/services/llm/ai_service_manager.js");
const llmService = await aiServiceManager.getInstance().getService();
const result = await contextService.processQuery(userQuery, llmService, {
maxResults: 8,
contextNoteId: noteId
});
return `Context:\n${result.context}\n\nUser question: ${userQuery}`;
}
main.ts - Sole process entry point; sequences i18n init before server boot.www.ts - Creates the Node.js HTTP(S) server, binds port, attaches WebSocket handlers.app.ts - Builds and exports the Express Application; registers all routers and middleware.anonymize.ts - Strips personal data from the SQLite database for bug reports.docker_healthcheck.ts - Tiny script that exits non-zero if the server does not respond.express.d.ts - Augments Express's Request interface with Trilium session/user fields.types.d.ts - Project-wide ambient declarations (e.g., global config shape).becca/ - Live in-memory entity cache; the source of truth for notes, branches, attributes at runtime.errors/ - Typed error subclasses (e.g., NotFoundError, ValidationError) consumed by route handlers.etapi/ - ETAPI v1 REST handlers; each file maps to a resource (notes, attachments, branches, etc.).migrations/ - Ordered SQL/TS migration files applied at startup when the DB version is behind.routes/ - Express routers for the main SPA index, login, custom JS/CSS, and API endpoints.services/ - All business logic: sql.ts (DB), sync/, search/, llm/, options.ts, log.ts, and more.share/ - Standalone share-page router and asset pipeline for publicly shared notes.assets/ - EJS view templates, schema.sql, static images, i18n JSON files, and sample config.better-sqlite3 build failure: Ensure node-gyp and a matching C++ toolchain are installed; run npm rebuild better-sqlite3 after switching Node.js versions..js extension required in imports: All internal imports use explicit .js extensions (e.g., ./services/i18n.js). Your tsconfig must use "moduleResolution": "NodeNext" or TypeScript will not resolve them.package.json version field missing: routes/index.ts does import packageJson from "../../package.json". If your layout differs, update the relative path or you will get a runtime import error.TRILIUM_DATA_DIR not set: The server will default to ~/trilium-data; in containerized or multi-tenant environments always set this explicitly to avoid data collisions.initializeTranslations(): Any module that calls t() before the await in main.ts will return empty strings. Keep initializeTranslations() as the very first await in your entry point.www.js inside startApplication: This pattern is intentional to prevent module-level side effects before i18n is ready. Do not hoist the import to the top of main.ts.I have a copy of the TriliumNext server backend source at `./source/` and its
integration guide at `./USAGE.md`. The upstream package is
`@triliumnext/source@0.95.0`.
Please help me integrate this backend into my existing Node.js TypeScript project:
1. Read USAGE.md fully before writing any code.
2. Identify which parts of `source/` I need to copy and where they should live
in my project layout (describe the directory mapping).
3. Update my `tsconfig.json` and `package.json` to support ESM NodeNext resolution
as described in USAGE.md.
4. Wire the server entry point (`source/main.ts`) so it starts after my own
initialization logic completes.
5. Add a custom Express route that calls `getSemanticContext` from
`source/services/llm/context/index.ts` and returns JSON.
6. Show me how to set required environment variables (`TRILIUM_DATA_DIR`,
`TRILIUM_PORT`) in a `.env` file and load them before the server starts.
7. Provide a working `docker-compose.yml` snippet that mounts a data volume and
sets those env vars.
Use only the exports documented in USAGE.md and visible in the source files.
Do not invent any module paths or function signatures.
TriliumNext is a fork of the original zadam/trilium project, now maintained at https://github.com/TriliumNext/Trilium. The upstream license applies to all files in source/; see source/LICENSE if present, or refer to the repository for the full AGPL-3.0 license text. Credit the TriliumNext contributors when redistributing or embedding this code.
This product’s unique contribution is clean room implementation of valuable code block into AVCP compatible standard.
完整安装指南与集成提示词将在购买后解锁。
Automation, Utilities & Developer Tools
免费