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
fix(export): preserve file extension on long multi-byte export names
Elian Doran04501353f3af
diff --git a/packages/trilium-core/src/services/export/zip.spec.ts b/packages/trilium-core/src/services/export/zip.spec.tsindex dbde7391c2..ea863bae9f 100644--- a/packages/trilium-core/src/services/export/zip.spec.ts+++ b/packages/trilium-core/src/services/export/zip.spec.ts@@ -281,6 +281,24 @@ describe.skipIf(isBrowserRuntime)("zip export (real DB)", () => {expect(entries[attFileName]).toBeDefined();});+ it("keeps the extension on very long multi-byte titles within the 255-byte limit", async () => {+ // A title of 3-byte CJK characters long enough that, once the upstream+ // 255-byte sanitize cap fills the base, appending the extension would+ // push past 255 bytes. The extension must survive and the whole name+ // must stay within the filesystem's 255-byte limit.+ const cjkTitle = "汉".repeat(120);+ const { note } = createNote("root", { title: cjkTitle, content: "<h2>Heading</h2>" });+ const branch = note.getParentBranches()[0];++ const { entries } = await exportSubtree(branch, "markdown");+ const rootMeta = parseMeta(entries).files[0];++ const name = rootMeta.dataFileName ?? "";+ expect(name.endsWith(".md")).toBe(true);+ expect(Buffer.byteLength(name, "utf-8")).toBeLessThanOrEqual(255);+ expect(entries[name]).toBeDefined();+ });+it("emits a .clone data file when the same note appears twice in the subtree", async () => {const { note: parent } = createNote("root", { title: "CloneHolder", content: "" });const { note: folderA } = createNote(parent.noteId, { title: "FolderA", content: "" });diff --git a/packages/trilium-core/src/services/export/zip.ts b/packages/trilium-core/src/services/export/zip.tsindex 2b116eb548..8ea3ef7600 100644--- a/packages/trilium-core/src/services/export/zip.ts+++ b/packages/trilium-core/src/services/export/zip.ts@@ -16,8 +16,12 @@ import { getZipExportProviderFactory } from "./zip_export_provider_factory.js";import { AttachmentMeta, AttributeMeta, ExportFormat, NoteMeta, NoteMetaFile } from "../../meta";import { ValidationError } from "../../errors";import { extname } from "../utils/path";+import { truncateUtf8Bytes } from "../utils/binary";import { rewriteMarkdownContentLinks, isMarkdownCodeNote } from "./rewrite_links.js";+// Most filesystems cap a single path component at 255 bytes; keep exported file names within that.+const MAX_FILENAME_BYTES = 255;+// eslint-disable-next-line @typescript-eslint/no-explicit-anyasync function exportToZip(taskContext: TaskContext<"export">, branch: BBranch, format: ExportFormat, res: Record<string, any>, setHeaders = true, zipExportOptions?: AdvancedExportOptions) {const archive = getZipProvider().createZipArchive();@@ -70,17 +74,15 @@ async function exportToZip(taskContext: TaskContext<"export">, branch: BBranch,const newExtension = provider.mapExtension(type, mime, existingExtension, format);// if the note is already named with the extension (e.g. "image.jpg"), then it's silly to append the exact same extension again- if (newExtension && existingExtension !== `.${newExtension.toLowerCase()}`) {- fileName += `.${newExtension}`;- }+ const extension = newExtension && existingExtension !== `.${newExtension.toLowerCase()}` ? `.${newExtension}` : "";- // sanitize() strips illegal filename characters and truncates to the 255-byte- // filesystem limit (byte-aware, via truncate-utf8-bytes). This keeps long- // titles and attachment names intact instead of hard-capping them at 30- // characters, while still guarding against over-long / unsafe names.- fileName = sanitize(fileName);+ // sanitize() strips illegal filename characters; we then byte-truncate the base+ // name so the whole entry (extension included) stays within the 255-byte+ // filesystem limit without ever chopping the extension off long / multi-byte+ // titles and attachment names. This replaces the old arbitrary 30-char cap.+ const base = truncateUtf8Bytes(sanitize(fileName), MAX_FILENAME_BYTES - extension.length);- return getUniqueFilename(existingFileNames, fileName);+ return getUniqueFilename(existingFileNames, `${base}${extension}`);}function createNoteMeta(branch: BBranch, parentMeta: Partial<NoteMeta>, existingFileNames: Record<string, number>): NoteMeta | null {diff --git a/packages/trilium-core/src/services/utils/binary.spec.ts b/packages/trilium-core/src/services/utils/binary.spec.tsindex 7ef6b82c72..6d661ca310 100644Binary files a/packages/trilium-core/src/services/utils/binary.spec.ts and b/packages/trilium-core/src/services/utils/binary.spec.ts differdiff --git a/packages/trilium-core/src/services/utils/binary.ts b/packages/trilium-core/src/services/utils/binary.tsindex a2dac2f365..aad58882ee 100644--- a/packages/trilium-core/src/services/utils/binary.ts+++ b/packages/trilium-core/src/services/utils/binary.ts@@ -47,6 +47,27 @@ export function encodeUtf8(string: string | Uint8Array) {return utf8Encoder.encode(unwrapStringOrBuffer(string));}+/**+ * Truncates a string so that its UTF-8 encoding does not exceed `maxBytes`,+ * without ever splitting a multi-byte character (the cut is moved back to the+ * nearest character boundary). Returns the input unchanged when it already fits.+ */+export function truncateUtf8Bytes(text: string, maxBytes: number): string {+ const encoded = encodeUtf8(text);+ if (encoded.length <= maxBytes) {+ return text;+ }++ // UTF-8 continuation bytes match 0b10xxxxxx (0x80–0xBF); back up while the+ // cut would land inside a multi-byte sequence so we never emit a partial char.+ let end = Math.max(0, maxBytes);+ while (end > 0 && (encoded[end] & 0xc0) === 0x80) {+ end--;+ }++ return decodeUtf8(encoded.slice(0, end));+}+export function unwrapStringOrBuffer(stringOrBuffer: string | Uint8Array) {if (typeof stringOrBuffer === "string") {return stringOrBuffer;