Skip to content

Build your personal knowledge base with Trilium Notes

chore(server): fix incompatibility with Uint8Array

Elian Doran20c90d1296cf
diff --git a/apps/server/src/routes/api/files.ts b/apps/server/src/routes/api/files.ts
index 2095f3b712..fbfa63a0d0 100644
--- a/apps/server/src/routes/api/files.ts
+++ b/apps/server/src/routes/api/files.ts
@@ -121,7 +121,7 @@ function attachmentContentProvider(req: Request) {
return streamContent(attachment.getContent(), attachment.getFileName(), attachment.mime);
}
-async function streamContent(content: string | Buffer, fileName: string, mimeType: string) {
+async function streamContent(content: string | Uint8Array, fileName: string, mimeType: string) {
if (typeof content === "string") {
content = Buffer.from(content, "utf8");
}
@@ -168,7 +168,7 @@ function saveAttachmentToTmpDir(req: Request) {
const createdTemporaryFiles = new Set<string>();
-function saveToTmpDir(fileName: string, content: string | Buffer, entityType: string, entityId: string) {
+function saveToTmpDir(fileName: string, content: string | Uint8Array, entityType: string, entityId: string) {
const tmpObj = tmp.fileSync({
postfix: fileName,
tmpdir: dataDirs.TMP_DIR
diff --git a/apps/server/src/routes/api/image.ts b/apps/server/src/routes/api/image.ts
index aa24e7aae9..ec7228d7b9 100644
--- a/apps/server/src/routes/api/image.ts
+++ b/apps/server/src/routes/api/image.ts
@@ -1,11 +1,12 @@
-"use strict";
-import imageService from "../../services/image.js";
-import becca from "../../becca/becca.js";
-import fs from "fs";
+
import type { Request, Response } from "express";
+import fs from "fs";
+
+import becca from "../../becca/becca.js";
import type BNote from "../../becca/entities/bnote.js";
import type BRevision from "../../becca/entities/brevision.js";
+import imageService from "../../services/image.js";
import { RESOURCE_DIR } from "../../services/resource_dir.js";
function returnImageFromNote(req: Request, res: Response) {
@@ -42,7 +43,7 @@ function returnImageInt(image: BNote | BRevision | null, res: Response) {
}
export function renderSvgAttachment(image: BNote | BRevision, res: Response, attachmentName: string) {
- let svg: string | Buffer = `<svg xmlns="http://www.w3.org/2000/svg"></svg>`;
+ let svg: string | Uint8Array = `<svg xmlns="http://www.w3.org/2000/svg"></svg>`;
const attachment = image.getAttachmentByTitle(attachmentName);
if (attachment) {
diff --git a/apps/server/src/services/export/single.ts b/apps/server/src/services/export/single.ts
index 16d36807e8..e115e0e54b 100644
--- a/apps/server/src/services/export/single.ts
+++ b/apps/server/src/services/export/single.ts
@@ -1,14 +1,15 @@
-"use strict";
-import mimeTypes from "mime-types";
+
+import type { Response } from "express";
import html from "html";
-import { getContentDisposition, escapeHtml } from "../utils.js";
-import mdService from "./markdown.js";
+import mimeTypes from "mime-types";
+
import becca from "../../becca/becca.js";
-import type TaskContext from "../task_context.js";
import type BBranch from "../../becca/entities/bbranch.js";
-import type { Response } from "express";
import type BNote from "../../becca/entities/bnote.js";
+import type TaskContext from "../task_context.js";
+import { escapeHtml,getContentDisposition } from "../utils.js";
+import mdService from "./markdown.js";
import type { ExportFormat } from "./zip/abstract_provider.js";
function exportSingleNote(taskContext: TaskContext<"export">, branch: BBranch, format: ExportFormat, res: Response) {
@@ -34,7 +35,7 @@ function exportSingleNote(taskContext: TaskContext<"export">, branch: BBranch, f
taskContext.taskSucceeded(null);
}
-export function mapByNoteType(note: BNote, content: string | Buffer<ArrayBufferLike>, format: ExportFormat) {
+export function mapByNoteType(note: BNote, content: string | Uint8Array, format: ExportFormat) {
let payload, extension, mime;
if (typeof content !== "string") {
diff --git a/apps/server/src/services/export/zip.ts b/apps/server/src/services/export/zip.ts
index dbab81687e..a0c32ef6bd 100644
--- a/apps/server/src/services/export/zip.ts
+++ b/apps/server/src/services/export/zip.ts
@@ -318,7 +318,7 @@ async function exportToZip(taskContext: TaskContext<"export">, branch: BBranch,
}
}
- function prepareContent(title: string, content: string | Buffer, noteMeta: NoteMeta, note?: BNote): string | Buffer {
+ function prepareContent(title: string, content: string | Uint8Array, noteMeta: NoteMeta, note?: BNote): string | Uint8Array {
const isText = ["html", "markdown"].includes(noteMeta?.format || "");
if (isText) {
content = content.toString();
@@ -339,11 +339,11 @@ async function exportToZip(taskContext: TaskContext<"export">, branch: BBranch,
if (noteMeta.isClone) {
const targetUrl = getNoteTargetUrl(noteMeta.noteId, noteMeta);
- let content: string | Buffer = `<p>This is a clone of a note. Go to its <a href="${targetUrl}">primary location</a>.</p>`;
+ let content: string | Uint8Array = `<p>This is a clone of a note. Go to its <a href="${targetUrl}">primary location</a>.</p>`;
content = prepareContent(noteMeta.title, content, noteMeta, undefined);
- archive.append(content, { name: filePathPrefix + noteMeta.dataFileName });
+ archive.append(content as Buffer, { name: filePathPrefix + noteMeta.dataFileName });
return;
}
@@ -359,7 +359,7 @@ async function exportToZip(taskContext: TaskContext<"export">, branch: BBranch,
if (noteMeta.dataFileName) {
const content = prepareContent(noteMeta.title, note.getContent(), noteMeta, note);
- archive.append(content, {
+ archive.append(content as string | Buffer, {
name: filePathPrefix + noteMeta.dataFileName,
date: dateUtils.parseDateTime(note.utcDateModified)
});
@@ -375,7 +375,7 @@ async function exportToZip(taskContext: TaskContext<"export">, branch: BBranch,
const attachment = note.getAttachmentById(attachmentMeta.attachmentId);
const content = attachment.getContent();
- archive.append(content, {
+ archive.append(content as Buffer, {
name: filePathPrefix + attachmentMeta.dataFileName,
date: dateUtils.parseDateTime(note.utcDateModified)
});
diff --git a/apps/server/src/services/export/zip/abstract_provider.ts b/apps/server/src/services/export/zip/abstract_provider.ts
index 5eda4b0767..d3c5ea2220 100644
--- a/apps/server/src/services/export/zip/abstract_provider.ts
+++ b/apps/server/src/services/export/zip/abstract_provider.ts
@@ -52,7 +52,7 @@ export abstract class ZipExportProvider {
}
abstract prepareMeta(metaFile: NoteMetaFile): void;
- abstract prepareContent(title: string, content: string | Buffer, noteMeta: NoteMeta, note: BNote | undefined, branch: BBranch): string | Buffer;
+ abstract prepareContent(title: string, content: string | Uint8Array, noteMeta: NoteMeta, note: BNote | undefined, branch: BBranch): string | Uint8Array;
abstract afterDone(rootMeta: NoteMeta): void;
/**
diff --git a/apps/server/src/services/export/zip/html.ts b/apps/server/src/services/export/zip/html.ts
index 14fb44acc3..0ba9ed2136 100644
--- a/apps/server/src/services/export/zip/html.ts
+++ b/apps/server/src/services/export/zip/html.ts
@@ -34,7 +34,7 @@ export default class HtmlExportProvider extends ZipExportProvider {
metaFile.files.push(this.cssMeta);
}
- prepareContent(title: string, content: string | Buffer, noteMeta: NoteMeta): string | Buffer {
+ prepareContent(title: string, content: string | Uint8Array, noteMeta: NoteMeta): string | Uint8Array {
if (noteMeta.format === "html" && typeof content === "string") {
if (!content.substr(0, 100).toLowerCase().includes("<html") && !this.zipExportOptions?.skipHtmlTemplate) {
if (!noteMeta?.notePath?.length) {
diff --git a/apps/server/src/services/export/zip/markdown.ts b/apps/server/src/services/export/zip/markdown.ts
index c876a5c161..382bef8747 100644
--- a/apps/server/src/services/export/zip/markdown.ts
+++ b/apps/server/src/services/export/zip/markdown.ts
@@ -1,12 +1,12 @@
-import NoteMeta from "../../meta/note_meta"
-import { ZipExportProvider } from "./abstract_provider.js"
+import NoteMeta from "../../meta/note_meta";
import mdService from "../markdown.js";
+import { ZipExportProvider } from "./abstract_provider.js";
export default class MarkdownExportProvider extends ZipExportProvider {
prepareMeta() { }
- prepareContent(title: string, content: string | Buffer, noteMeta: NoteMeta): string | Buffer {
+ prepareContent(title: string, content: string | Uint8Array, noteMeta: NoteMeta): string | Uint8Array {
if (noteMeta.format === "markdown" && typeof content === "string") {
content = this.rewriteFn(content, noteMeta);
content = mdService.toMarkdown(content);
diff --git a/apps/server/src/services/export/zip/share_theme.ts b/apps/server/src/services/export/zip/share_theme.ts
index 316984d50c..534ccf785b 100644
--- a/apps/server/src/services/export/zip/share_theme.ts
+++ b/apps/server/src/services/export/zip/share_theme.ts
@@ -61,7 +61,7 @@ export default class ShareThemeExportProvider extends ZipExportProvider {
metaFile.files.push(this.indexMeta);
}
- prepareContent(title: string, content: string | Buffer, noteMeta: NoteMeta, note: BNote | undefined, branch: BBranch): string | Buffer {
+ prepareContent(title: string, content: string | Uint8Array, noteMeta: NoteMeta, note: BNote | undefined, branch: BBranch): string | Uint8Array {
if (!noteMeta?.notePath?.length) {
throw new Error("Missing note path.");
}
@@ -150,7 +150,7 @@ export default class ShareThemeExportProvider extends ZipExportProvider {
const note = this.branch.getNote();
const fullHtml = this.prepareContent(rootMeta.title ?? "", note.getContent(), rootMeta, note, this.branch);
- this.archive.append(fullHtml, { name: this.indexMeta.dataFileName });
+ this.archive.append(fullHtml as Buffer, { name: this.indexMeta.dataFileName });
}
#saveAssets(rootMeta: NoteMeta, assetsMeta: NoteMeta[]) {
@@ -166,7 +166,7 @@ export default class ShareThemeExportProvider extends ZipExportProvider {
// Inject the custom fonts.
for (const iconPack of this.iconPacks) {
const extension = MIME_TO_EXTENSION_MAPPINGS[iconPack.fontMime];
- let fontData: Buffer | undefined;
+ let fontData: Uint8Array | undefined;
if (iconPack.builtin) {
fontData = readFileSync(join(getClientDir(), "fonts", `${iconPack.fontAttachmentId}.${extension}`));
} else {
@@ -178,7 +178,7 @@ export default class ShareThemeExportProvider extends ZipExportProvider {
continue;
};
const fontFileName = `assets/icon-pack-${iconPack.prefix.toLowerCase()}.${extension}`;
- this.archive.append(fontData, { name: fontFileName });
+ this.archive.append(fontData as Buffer, { name: fontFileName });
}
}
diff --git a/apps/server/src/services/llm/tools/read_note_tool.ts b/apps/server/src/services/llm/tools/read_note_tool.ts
index ddcad559f1..0230e59dad 100644
--- a/apps/server/src/services/llm/tools/read_note_tool.ts
+++ b/apps/server/src/services/llm/tools/read_note_tool.ts
@@ -4,16 +4,16 @@
* This tool allows the LLM to read the content of a specific note.
*/
-import type { Tool, ToolHandler } from './tool_interfaces.js';
-import log from '../../log.js';
import becca from '../../../becca/becca.js';
+import log from '../../log.js';
+import type { Tool, ToolHandler } from './tool_interfaces.js';
// Define type for note response
interface NoteResponse {
noteId: string;
title: string;
type: string;
- content: string | Buffer;
+ content: string | Uint8Array;
attributes?: Array<{
name: string;
value: string;
diff --git a/apps/server/src/services/notes.ts b/apps/server/src/services/notes.ts
index 8c4a66f968..de144196c7 100644
--- a/apps/server/src/services/notes.ts
+++ b/apps/server/src/services/notes.ts
@@ -670,7 +670,7 @@ function saveAttachments(note: BNote, content: string) {
return content;
}
-function saveLinks(note: BNote, content: string | Buffer) {
+function saveLinks(note: BNote, content: string | Uint8Array) {
if ((note.type !== "text" && note.type !== "relationMap") || (note.isProtected && !protectedSessionService.isProtectedSessionAvailable())) {
return {
forceFrontendReload: false,
@@ -889,7 +889,7 @@ function getUndeletedParentBranchIds(noteId: string, deleteId: string) {
);
}
-function scanForLinks(note: BNote, content: string | Buffer) {
+function scanForLinks(note: BNote, content: string | Uint8Array) {
if (!note || !["text", "relationMap"].includes(note.type)) {
return;
}
@@ -910,7 +910,7 @@ function scanForLinks(note: BNote, content: string | Buffer) {
/**
* Things which have to be executed after updating content, but asynchronously (separate transaction)
*/
-async function asyncPostProcessContent(note: BNote, content: string | Buffer) {
+async function asyncPostProcessContent(note: BNote, content: string | Uint8Array) {
if (cls.isMigrationRunning()) {
// this is rarely needed for migrations, but can cause trouble by e.g. triggering downloads
return;
diff --git a/apps/server/src/services/script.ts b/apps/server/src/services/script.ts
index 97dd99898a..4b335f11d2 100644
--- a/apps/server/src/services/script.ts
+++ b/apps/server/src/services/script.ts
@@ -1,3 +1,4 @@
+import { binary_utils } from "@triliumnext/core";
import { transform } from "sucrase";
import becca from "../becca/becca.js";
@@ -217,8 +218,8 @@ return module.exports;
return bundle;
}
-export function buildJsx(contentRaw: string | Buffer) {
- const content = Buffer.isBuffer(contentRaw) ? contentRaw.toString("utf-8") : contentRaw;
+export function buildJsx(contentRaw: string | Uint8Array) {
+ const content = binary_utils.unwrapStringOrBuffer(contentRaw);
const output = transform(content, {
transforms: ["jsx", "imports"],
jsxPragma: "api.preact.h",
diff --git a/apps/server/src/services/search/expressions/note_content_fulltext.ts b/apps/server/src/services/search/expressions/note_content_fulltext.ts
index 89ba1bc984..4bd3408f9e 100644
--- a/apps/server/src/services/search/expressions/note_content_fulltext.ts
+++ b/apps/server/src/services/search/expressions/note_content_fulltext.ts
@@ -1,24 +1,23 @@
-"use strict";
+
import type { NoteRow } from "@triliumnext/commons";
-import type SearchContext from "../search_context.js";
+import striptags from "striptags";
-import Expression from "./expression.js";
-import NoteSet from "../note_set.js";
-import log from "../../log.js";
import becca from "../../../becca/becca.js";
+import log from "../../log.js";
import protectedSessionService from "../../protected_session.js";
-import striptags from "striptags";
-import { normalize } from "../../utils.js";
import sql from "../../sql.js";
-import {
- normalizeSearchText,
- calculateOptimizedEditDistance,
- validateFuzzySearchTokens,
- validateAndPreprocessContent,
+import { normalize } from "../../utils.js";
+import NoteSet from "../note_set.js";
+import type SearchContext from "../search_context.js";
+import {
+ calculateOptimizedEditDistance,
+ FUZZY_SEARCH_CONFIG,
fuzzyMatchWord,
- FUZZY_SEARCH_CONFIG
-} from "../utils/text_utils.js";
+ normalizeSearchText,
+ validateAndPreprocessContent,
+ validateFuzzySearchTokens} from "../utils/text_utils.js";
+import Expression from "./expression.js";
const ALLOWED_OPERATORS = new Set(["=", "!=", "*=*", "*=", "=*", "%=", "~=", "~*"]);
@@ -295,7 +294,7 @@ class NoteContentFulltextExp extends Expression {
return content;
}
- preprocessContent(content: string | Buffer, type: string, mime: string) {
+ preprocessContent(content: string | Uint8Array, type: string, mime: string) {
content = normalize(content.toString());
if (type === "text" && mime === "text/html") {
@@ -338,16 +337,16 @@ class NoteContentFulltextExp extends Expression {
private tokenMatchesContent(token: string, content: string, noteId: string): boolean {
const normalizedToken = normalizeSearchText(token);
const normalizedContent = normalizeSearchText(content);
-
+
if (normalizedContent.includes(normalizedToken)) {
return true;
}
-
+
// Check flat text for default fulltext search
if (!this.flatText || !becca.notes[noteId].getFlatText().includes(token)) {
return false;
}
-
+
return true;
}
@@ -358,15 +357,15 @@ class NoteContentFulltextExp extends Expression {
try {
const normalizedContent = normalizeSearchText(content);
const flatText = this.flatText ? normalizeSearchText(becca.notes[noteId].getFlatText()) : "";
-
+
// For phrase matching, check if tokens appear within reasonable proximity
if (this.tokens.length > 1) {
return this.matchesPhrase(normalizedContent, flatText);
}
-
+
// Single token fuzzy matching
const token = normalizeSearchText(this.tokens[0]);
- return this.fuzzyMatchToken(token, normalizedContent) ||
+ return this.fuzzyMatchToken(token, normalizedContent) ||
(this.flatText && this.fuzzyMatchToken(token, flatText));
} catch (error) {
log.error(`Error in fuzzy matching for note ${noteId}: ${error}`);
@@ -379,45 +378,45 @@ class NoteContentFulltextExp extends Expression {
*/
private matchesPhrase(content: string, flatText: string): boolean {
const searchText = this.flatText ? `${content} ${flatText}` : content;
-
+
// Apply content size limits for phrase matching
const limitedText = validateAndPreprocessContent(searchText);
if (!limitedText) {
return false;
}
-
+
const words = limitedText.toLowerCase().split(/\s+/);
-
+
// Only skip phrase matching for truly extreme word counts that could crash the system
if (words.length > FUZZY_SEARCH_CONFIG.ABSOLUTE_MAX_WORD_COUNT) {
console.error(`Phrase matching skipped due to extreme word count that could cause system instability: ${words.length} words`);
return false;
}
-
+
// Warn about large word counts but still attempt matching
if (words.length > FUZZY_SEARCH_CONFIG.PERFORMANCE_WARNING_WORDS) {
console.info(`Large word count for phrase matching: ${words.length} words - may take longer but will attempt full matching`);
}
-
+
// Find positions of each token
const tokenPositions: number[][] = this.tokens.map(token => {
const normalizedToken = normalizeSearchText(token);
const positions: number[] = [];
-
+
words.forEach((word, index) => {
if (this.fuzzyMatchSingle(normalizedToken, word)) {
positions.push(index);
}
});
-
+
return positions;
});
-
+
// Check if we found all tokens
if (tokenPositions.some(positions => positions.length === 0)) {
return false;
}
-
+
// Check for phrase proximity using configurable distance
return this.hasProximityMatch(tokenPositions, FUZZY_SEARCH_CONFIG.MAX_PHRASE_PROXIMITY);
}
@@ -431,18 +430,18 @@ class NoteContentFulltextExp extends Expression {
const [pos1, pos2] = tokenPositions;
return pos1.some(p1 => pos2.some(p2 => Math.abs(p1 - p2) <= maxDistance));
}
-
+
// For more tokens, check if we can find a sequence where all tokens are within range
const findSequence = (remaining: number[][], currentPos: number): boolean => {
if (remaining.length === 0) return true;
-
+
const [nextPositions, ...rest] = remaining;
- return nextPositions.some(pos =>
- Math.abs(pos - currentPos) <= maxDistance &&
+ return nextPositions.some(pos =>
+ Math.abs(pos - currentPos) <= maxDistance &&
findSequence(rest, pos)
);
};
-
+
const [firstPositions, ...rest] = tokenPositions;
return firstPositions.some(startPos => findSequence(rest, startPos));
}
@@ -455,12 +454,12 @@ class NoteContentFulltextExp extends Expression {
// For short tokens, require exact match to avoid too many false positives
return content.includes(token);
}
-
+
const words = content.split(/\s+/);
-
+
// Only limit word processing for truly extreme cases to prevent system instability
const limitedWords = words.slice(0, FUZZY_SEARCH_CONFIG.ABSOLUTE_MAX_WORD_COUNT);
-
+
return limitedWords.some(word => this.fuzzyMatchSingle(token, word));
}
diff --git a/apps/server/src/share/content_renderer.ts b/apps/server/src/share/content_renderer.ts
index e37ac8ab45..2de68222e2 100644
--- a/apps/server/src/share/content_renderer.ts
+++ b/apps/server/src/share/content_renderer.ts
@@ -30,7 +30,7 @@ const templateCache: Map<string, string> = new Map();
*/
export interface Result {
header: string;
- content: string | Buffer | undefined;
+ content: string | Uint8Array | undefined;
/** Set to `true` if the provided content should be rendered as empty. */
isEmpty?: boolean;
}