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
feat(export/markdown): rewrite attachment links
Elian Doran30f5fc7226ef
diff --git a/apps/server/src/services/export/rewrite_links.spec.ts b/apps/server/src/services/export/rewrite_links.spec.tsnew file mode 100644index 0000000000..712029f3dd--- /dev/null+++ b/apps/server/src/services/export/rewrite_links.spec.ts@@ -0,0 +1,191 @@+import { describe, expect, it } from "vitest";+import { rewriteMarkdownContentLinks } from "./rewrite_links.js";+import type NoteMeta from "../meta/note_meta.js";++function buildNoteMeta(attachments: Array<{ attachmentId: string; dataFileName: string }>): NoteMeta {+ return {+ noteId: "testNote1",+ notePath: ["root", "testNote1"],+ attachments: attachments.map((a) => ({+ ...a,+ title: a.dataFileName,+ role: "image" as const,+ mime: "image/jpeg",+ position: 0+ }))+ };+}++const nullNoteUrl = () => null;++describe("rewriteMarkdownContentLinks", () => {+ describe("attachment images", () => {+ it("rewrites attachment image URL to data filename", () => {+ const content = "";+ const noteMeta = buildNoteMeta([{ attachmentId: "abc123", dataFileName: "Note_Photo.jpeg" }]);++ expect(rewriteMarkdownContentLinks(content, noteMeta, nullNoteUrl))+ .toBe("");+ });++ it("preserves attachment URL when attachment is not found in noteMeta", () => {+ const content = "";+ const noteMeta = buildNoteMeta([]);++ expect(rewriteMarkdownContentLinks(content, noteMeta, nullNoteUrl))+ .toBe(content);+ });++ it("rewrites multiple attachment images", () => {+ const content = [+ "",+ "",+ ""+ ].join("\n");+ const noteMeta = buildNoteMeta([+ { attachmentId: "att1", dataFileName: "Note_a.png" },+ { attachmentId: "att2", dataFileName: "Note_b.png" }+ ]);++ expect(rewriteMarkdownContentLinks(content, noteMeta, nullNoteUrl))+ .toBe("\n\n");+ });++ it("handles attachment URL with generic 'image' as filename", () => {+ const content = "";+ const noteMeta = buildNoteMeta([+ { attachmentId: "y9zRJ8HJmJRC", dataFileName: "Note_Photo from 2024-02-21 19-41-25.225874.jpeg" }+ ]);++ expect(rewriteMarkdownContentLinks(content, noteMeta, nullNoteUrl))+ .toBe("");+ });++ it("handles URL-encoded attachment paths", () => {+ const content = "";+ const noteMeta = buildNoteMeta([{ attachmentId: "abc123", dataFileName: "Note_Photo Name.jpeg" }]);++ expect(rewriteMarkdownContentLinks(content, noteMeta, nullNoteUrl))+ .toBe("");+ });++ it("handles attachment URL with leading slash", () => {+ const content = "";+ const noteMeta = buildNoteMeta([{ attachmentId: "abc123", dataFileName: "Note_photo.png" }]);++ expect(rewriteMarkdownContentLinks(content, noteMeta, nullNoteUrl))+ .toBe("");+ });+ });++ describe("image notes", () => {+ it("rewrites image note URL to target path", () => {+ const content = "";+ const noteMeta = buildNoteMeta([]);+ const getNoteTargetUrl = (noteId: string) => noteId === "imgNote1" ? "../images/diagram.png" : null;++ expect(rewriteMarkdownContentLinks(content, noteMeta, getNoteTargetUrl))+ .toBe("");+ });++ it("preserves image note URL when note not found in export", () => {+ const content = "";+ const noteMeta = buildNoteMeta([]);++ expect(rewriteMarkdownContentLinks(content, noteMeta, nullNoteUrl))+ .toBe(content);+ });+ });++ describe("internal note links", () => {+ it("rewrites internal note link to target path", () => {+ const content = "[My Note](#root/abc123/def456)";+ const noteMeta = buildNoteMeta([]);+ const getNoteTargetUrl = (noteId: string) => noteId === "def456" ? "../Other/My Note.md" : null;++ expect(rewriteMarkdownContentLinks(content, noteMeta, getNoteTargetUrl))+ .toBe("[My Note](../Other/My Note.md)");+ });++ it("preserves internal note link when note not found in export", () => {+ const content = "[My Note](#root/abc123/def456)";+ const noteMeta = buildNoteMeta([]);++ expect(rewriteMarkdownContentLinks(content, noteMeta, nullNoteUrl))+ .toBe(content);+ });+ });++ describe("attachment download links", () => {+ it("rewrites attachment download link to data filename", () => {+ const content = "[document.pdf](#root/noteId123?attachmentId=att456)";+ const noteMeta = buildNoteMeta([{ attachmentId: "att456", dataFileName: "Note_document.pdf" }]);++ expect(rewriteMarkdownContentLinks(content, noteMeta, nullNoteUrl))+ .toBe("[document.pdf](Note_document.pdf)");+ });++ it("preserves attachment download link when attachment not found", () => {+ const content = "[document.pdf](#root/noteId123?attachmentId=unknownAtt)";+ const noteMeta = buildNoteMeta([]);++ expect(rewriteMarkdownContentLinks(content, noteMeta, nullNoteUrl))+ .toBe(content);+ });+ });++ describe("non-Trilium URLs", () => {+ it("preserves external URLs", () => {+ const content = "\n[link](https://example.com)";+ const noteMeta = buildNoteMeta([]);++ expect(rewriteMarkdownContentLinks(content, noteMeta, nullNoteUrl))+ .toBe(content);+ });++ it("preserves relative URLs that are not API paths", () => {+ const content = "";+ const noteMeta = buildNoteMeta([]);++ expect(rewriteMarkdownContentLinks(content, noteMeta, nullNoteUrl))+ .toBe(content);+ });+ });++ describe("mixed content", () => {+ it("rewrites all link types in a single document", () => {+ const content = [+ "# My Note",+ "",+ "Here is an image: ",+ "",+ "And a [link to another note](#root/parent1/note2).",+ "",+ "External link: [Google](https://google.com)",+ "",+ "Download: [file.pdf](#root/note1?attachmentId=att2)"+ ].join("\n");++ const noteMeta = buildNoteMeta([+ { attachmentId: "att1", dataFileName: "Note_photo.png" },+ { attachmentId: "att2", dataFileName: "Note_file.pdf" }+ ]);+ const getNoteTargetUrl = (noteId: string) => noteId === "note2" ? "../Other/Note2.md" : null;++ const expected = [+ "# My Note",+ "",+ "Here is an image: ",+ "",+ "And a [link to another note](../Other/Note2.md).",+ "",+ "External link: [Google](https://google.com)",+ "",+ "Download: [file.pdf](Note_file.pdf)"+ ].join("\n");++ expect(rewriteMarkdownContentLinks(content, noteMeta, getNoteTargetUrl))+ .toBe(expected);+ });+ });+});diff --git a/apps/server/src/services/export/rewrite_links.ts b/apps/server/src/services/export/rewrite_links.tsnew file mode 100644index 0000000000..31f65e962f--- /dev/null+++ b/apps/server/src/services/export/rewrite_links.ts@@ -0,0 +1,65 @@+import type NoteMeta from "../meta/note_meta.js";++const MARKDOWN_MIMES = new Set(["text/x-markdown", "text/markdown", "text/x-gfm"]);++export function isMarkdownCodeNote(mime: string | undefined): boolean {+ return !!mime && MARKDOWN_MIMES.has(mime);+}++/**+ * Rewrites Trilium-internal links in markdown content to use relative file paths+ * suitable for export. This handles code notes with markdown MIME type, where+ * the content is already in markdown format (unlike text notes which store HTML).+ *+ * Counterpart to `rewriteLinks` in `zip.ts` which handles HTML-style patterns.+ */+export function rewriteMarkdownContentLinks(+ content: string,+ noteMeta: NoteMeta,+ getNoteTargetUrl: (targetNoteId: string, sourceMeta: NoteMeta) => string | null+): string {+ // Attachment images: + content = content.replace(+ /!\[([^\]]*)\]\([^)]*?api\/attachments\/([a-zA-Z0-9_]+)\/image\/[^)]*\)/g,+ (match, alt, attachmentId) => {+ const url = findAttachmentUrl(noteMeta, attachmentId);+ return url ? `` : match;+ }+ );++ // Image notes: + content = content.replace(+ /!\[([^\]]*)\]\([^)]*?api\/images\/([a-zA-Z0-9_]+)\/[^)]*\)/g,+ (match, alt, noteId) => {+ const url = getNoteTargetUrl(noteId, noteMeta);+ return url ? `` : match;+ }+ );++ // Attachment download links: [text](#root/...?attachmentId={id})+ // Must be matched before internal note links to avoid partial matches.+ content = content.replace(+ /\[([^\]]*)\]\([^)]*#root[^)]*attachmentId=([a-zA-Z0-9_]+)[^)]*\)/g,+ (match, text, attachmentId) => {+ const url = findAttachmentUrl(noteMeta, attachmentId);+ return url ? `[${text}](${url})` : match;+ }+ );++ // Internal note links: [text](#root/.../noteId)+ content = content.replace(+ /\[([^\]]*)\]\(#root[a-zA-Z0-9_\/]*\/([a-zA-Z0-9_]+)[^)]*\)/g,+ (match, text, noteId) => {+ const url = getNoteTargetUrl(noteId, noteMeta);+ return url ? `[${text}](${url})` : match;+ }+ );++ return content;+}++function findAttachmentUrl(noteMeta: NoteMeta, attachmentId: string): string | undefined {+ return (noteMeta.attachments || [])+ .find((a) => a.attachmentId === attachmentId)+ ?.dataFileName;+}diff --git a/apps/server/src/services/export/zip.ts b/apps/server/src/services/export/zip.tsindex a6cd5b59c3..60412233ed 100644--- a/apps/server/src/services/export/zip.ts+++ b/apps/server/src/services/export/zip.ts@@ -1,29 +1,31 @@-"use strict";-import dateUtils from "../date_utils.js";++import { NoteType } from "@triliumnext/commons";+import archiver from "archiver";+import type { Response } from "express";+import fs from "fs";import path from "path";-import packageInfo from "../../../package.json" with { type: "json" };-import { getContentDisposition, waitForStreamToFinish } from "../utils.js";-import protectedSessionService from "../protected_session.js";import sanitize from "sanitize-filename";-import fs from "fs";++import packageInfo from "../../../package.json" with { type: "json" };import becca from "../../becca/becca.js";-import archiver from "archiver";-import log from "../log.js";-import TaskContext from "../task_context.js";+import BBranch from "../../becca/entities/bbranch.js";+import type BNote from "../../becca/entities/bnote.js";import ValidationError from "../../errors/validation_error.js";-import type NoteMeta from "../meta/note_meta.js";+import dateUtils from "../date_utils.js";+import log from "../log.js";import type AttachmentMeta from "../meta/attachment_meta.js";import type AttributeMeta from "../meta/attribute_meta.js";-import BBranch from "../../becca/entities/bbranch.js";-import type { Response } from "express";+import type NoteMeta from "../meta/note_meta.js";import type { NoteMetaFile } from "../meta/note_meta.js";-import HtmlExportProvider from "./zip/html.js";+import protectedSessionService from "../protected_session.js";+import TaskContext from "../task_context.js";+import { getContentDisposition, waitForStreamToFinish } from "../utils.js";import { AdvancedExportOptions, type ExportFormat, ZipExportProviderData } from "./zip/abstract_provider.js";+import HtmlExportProvider from "./zip/html.js";import MarkdownExportProvider from "./zip/markdown.js";import ShareThemeExportProvider from "./zip/share_theme.js";-import type BNote from "../../becca/entities/bnote.js";-import { NoteType } from "@triliumnext/commons";+import { rewriteMarkdownContentLinks, isMarkdownCodeNote } from "./rewrite_links.js";async function exportToZip(taskContext: TaskContext<"export">, branch: BBranch, format: ExportFormat, res: Response | fs.WriteStream, setHeaders = true, zipExportOptions?: AdvancedExportOptions) {if (!["html", "markdown", "share"].includes(format)) {@@ -73,11 +75,11 @@ async function exportToZip(taskContext: TaskContext<"export">, branch: BBranch,} while (newName in existingFileNames);return `${index}_${fileName}`;- } else {- existingFileNames[lcFileName] = 1;+ }+ existingFileNames[lcFileName] = 1;- return fileName;- }+ return fileName;+}function getDataFileName(type: NoteType | null, mime: string, baseFileName: string, existingFileNames: Record<string, number>): string {@@ -89,15 +91,15 @@ async function exportToZip(taskContext: TaskContext<"export">, branch: BBranch,// Crop fileName to avoid its length exceeding 30 and prevent cutting into the extension.if (fileName.length > 30) {// We use regex to match the extension to preserve multiple dots in extensions (e.g. .tar.gz).- let match = fileName.match(/(\.[a-zA-Z0-9_.!#-]+)$/);- let ext = match ? match[0] : "";+ const match = fileName.match(/(\.[a-zA-Z0-9_.!#-]+)$/);+ const ext = match ? match[0] : "";// Crop the extension if extension length exceeds 30const croppedExt = ext.slice(-30);// Crop the file name section and append the cropped extensionfileName = fileName.slice(0, 30 - croppedExt.length) + croppedExt;}- let existingExtension = path.extname(fileName).toLowerCase();+ const existingExtension = path.extname(fileName).toLowerCase();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@@ -140,7 +142,7 @@ async function exportToZip(taskContext: TaskContext<"export">, branch: BBranch,const meta: NoteMeta = {isClone: true,noteId: note.noteId,- notePath: notePath,+ notePath,title: note.getTitleOrProtected(),prefix: branch.prefix,dataFileName: fileName,@@ -198,16 +200,16 @@ async function exportToZip(taskContext: TaskContext<"export">, branch: BBranch,meta.attachments = attachments.toSorted((a, b) => ((a.attachmentId ?? "").localeCompare(b.attachmentId ?? "", "en") ?? 1)).map((attachment) => {- const attMeta: AttachmentMeta = {- attachmentId: attachment.attachmentId,- title: attachment.title,- role: attachment.role,- mime: attachment.mime,- position: attachment.position,- dataFileName: getDataFileName(null, attachment.mime, baseFileName + "_" + attachment.title, existingFileNames)- };- return attMeta;- });+ const attMeta: AttachmentMeta = {+ attachmentId: attachment.attachmentId,+ title: attachment.title,+ role: attachment.role,+ mime: attachment.mime,+ position: attachment.position,+ dataFileName: getDataFileName(null, attachment.mime, `${baseFileName }_${ attachment.title}`, existingFileNames)+ };+ return attMeta;+ });if (childBranches.length > 0) {meta.dirFileName = getUniqueFilename(existingFileNames, baseFileName);@@ -327,6 +329,13 @@ async function exportToZip(taskContext: TaskContext<"export">, branch: BBranch,content = provider.prepareContent(title, content, noteMeta, note, branch);+ // Rewrite markdown-style links for code notes with markdown MIME.+ // These notes store content as markdown (not HTML), so the HTML-based+ // rewriteLinks in the providers won't match their link syntax.+ if (noteMeta.type === "code" && isMarkdownCodeNote(noteMeta.mime) && typeof content === "string") {+ content = rewriteMarkdownContentLinks(content, noteMeta, getNoteTargetUrl);+ }+return content;}@@ -421,9 +430,9 @@ async function exportToZip(taskContext: TaskContext<"export">, branch: BBranch,} else if (attr.value === "root" || attr.value?.startsWith("_")) {// relations to "named" noteIds can be preservedreturn true;- } else {- return false;- }+ }+ return false;+});}