Skip to content

Build your personal knowledge base with Trilium Notes

feat(import): preserve Anytype inline images and embedded files

Elian Doranae0ef299216d
diff --git a/packages/trilium-core/src/services/import/anytype/content.spec.ts b/packages/trilium-core/src/services/import/anytype/content.spec.ts
index 59348b8946..57e09d5673 100644
--- a/packages/trilium-core/src/services/import/anytype/content.spec.ts
+++ b/packages/trilium-core/src/services/import/anytype/content.spec.ts
@@ -210,6 +210,36 @@ describe("links", () => {
});
});
+describe("inline files", () => {
+ /** A file/media block embedding a `FileObject` by its id. */
+ const fileBlock = (id: string, file: AnytypeBlock["file"]): AnytypeBlock => ({ id, file, childrenIds: [] });
+
+ it("renders an Image block as an image figure whose src is the target file id (resolved later by the importer)", () => {
+ const doc = listDoc(["f1"], [fileBlock("f1", { type: "Image", name: "shot.png", targetObjectId: "file-cid", state: "Done", style: "Embed" })]);
+ expect(parseObject(doc).content).toBe('<figure class="image"><img src="file-cid"></figure>');
+ });
+
+ it("renders a non-image file block as a marked anchor carrying the file name and target id", () => {
+ const doc = listDoc(["f1"], [fileBlock("f1", { type: "PDF", name: "report.pdf", targetObjectId: "pdf-cid", state: "Done", style: "Link" })]);
+ expect(parseObject(doc).content).toBe('<p><a class="anytype-file" href="pdf-cid">report.pdf</a></p>');
+ });
+
+ it("falls back to the target id as the link text when the file has no name", () => {
+ const doc = listDoc(["f1"], [fileBlock("f1", { type: "File", targetObjectId: "bare-cid" })]);
+ expect(parseObject(doc).content).toBe('<p><a class="anytype-file" href="bare-cid">bare-cid</a></p>');
+ });
+
+ it("escapes the file name in a non-image anchor", () => {
+ const doc = listDoc(["f1"], [fileBlock("f1", { type: "File", name: "a & b <x>.txt", targetObjectId: "c" })]);
+ expect(parseObject(doc).content).toBe('<p><a class="anytype-file" href="c">a &amp; b &lt;x&gt;.txt</a></p>');
+ });
+
+ it("drops a file block with no target (e.g. a still-uploading file)", () => {
+ const doc = listDoc(["f1"], [fileBlock("f1", { type: "Image", name: "pending.png", state: "Uploading" })]);
+ expect(parseObject(doc).content).toBe("");
+ });
+});
+
describe("renderInlineText", () => {
it("returns escaped plain text when there are no marks", () => {
expect(renderInlineText("a < b & c > d", [])).toBe("a &lt; b &amp; c &gt; d");
diff --git a/packages/trilium-core/src/services/import/anytype/content.ts b/packages/trilium-core/src/services/import/anytype/content.ts
index f04be7c11a..a72e6fd57d 100644
--- a/packages/trilium-core/src/services/import/anytype/content.ts
+++ b/packages/trilium-core/src/services/import/anytype/content.ts
@@ -110,6 +110,22 @@ export function extractContent(blocks: AnytypeBlock[], rootId: string, resolveLi
return `<p><a class="reference-link" href="#root/${target.noteId}">${escapeHtml(target.title)}</a></p>`;
}
+ // A file/media block — an embedded image or attached file (PDF, audio, …). The placeholder carries
+ // the linked FileObject's id in the `src`/`href`; the importer resolves it to a saved attachment
+ // once the note (and thus the attachment) exists — an inline image for an Image, a reference link
+ // for any other file type. A block with no target (still uploading, or a broken reference) is dropped.
+ if (block.file) {
+ const targetId = block.file.targetObjectId;
+ if (!targetId) {
+ return "";
+ }
+ if (block.file.type === "Image") {
+ return `<figure class="image"><img src="${escapeHtml(targetId)}"></figure>`;
+ }
+ const name = (block.file.name ?? "").trim() || targetId;
+ return `<p><a class="anytype-file" href="${escapeHtml(targetId)}">${escapeHtml(name)}</a></p>`;
+ }
+
// A LaTeX block — a Mermaid diagram or LaTeX math.
if (block.latex) {
return renderLatexBlock(block.latex.text ?? "", block.latex.processor);
diff --git a/packages/trilium-core/src/services/import/anytype/importer.integration.spec.ts b/packages/trilium-core/src/services/import/anytype/importer.integration.spec.ts
index 0b17be4bd2..30ab52c491 100644
--- a/packages/trilium-core/src/services/import/anytype/importer.integration.spec.ts
+++ b/packages/trilium-core/src/services/import/anytype/importer.integration.spec.ts
@@ -725,6 +725,101 @@ describe("Anytype importer — integration", () => {
expect(content).toContain(">log.txt</a>");
});
+ it("imports an inline image block as a role:image attachment, rewriting the <img src> to point at it", async () => {
+ // An Image file block in the body references a FileObject (its `targetObjectId`), whose bytes ship under files/.
+ const imageCid = "bafyreiimage";
+ const page = JSON.stringify({
+ sbType: "Page",
+ snapshot: {
+ data: {
+ blocks: [
+ { id: "pg", childrenIds: ["header", "img"] },
+ { id: "header", childrenIds: ["title"] },
+ { id: "title", text: { text: "", style: "Title" } },
+ { id: "img", file: { type: "Image", name: "shot.png", mime: "image/png", targetObjectId: imageCid, state: "Done", style: "Embed" } }
+ ],
+ details: { id: "pg", name: "Page with image", resolvedLayout: 0 }
+ }
+ }
+ });
+ const importRoot = await importAnytype({
+ "objects/pg.pb.json": page,
+ "filesObjects/f1.pb.json": fileObjectJson(imageCid, "shot", "png", "image/png", "files\\shot.png"),
+ "files/shot.png": Buffer.from("\x89PNG\r\n\x1a\nfake-png-bytes")
+ });
+
+ const note = importRoot.getChildNotes().find((n) => n.title === "Page with image");
+ // The image becomes a role:"image" attachment titled from the file's name.
+ const attachments = note?.getAttachmentsByRole("image") ?? [];
+ expect(attachments.map((a) => a.title)).toEqual(["shot.png"]);
+
+ // The <img src> is rewritten to the attachment URL (no bare file id left in the body).
+ const content = decodeUtf8(note?.getContent() ?? "");
+ expect(content).toContain(`<figure class="image"><img src="api/attachments/${attachments[0]?.attachmentId}/image/`);
+ expect(content).not.toContain(imageCid);
+ });
+
+ it("imports an inline non-image file block as a role:file attachment with a reference link in the body", async () => {
+ const fileCid = "bafyreipdf";
+ const page = JSON.stringify({
+ sbType: "Page",
+ snapshot: {
+ data: {
+ blocks: [
+ { id: "pg", childrenIds: ["header", "file"] },
+ { id: "header", childrenIds: ["title"] },
+ { id: "title", text: { text: "", style: "Title" } },
+ { id: "file", file: { type: "PDF", name: "report.pdf", mime: "application/pdf", targetObjectId: fileCid, state: "Done", style: "Link" } }
+ ],
+ details: { id: "pg", name: "Page with file", resolvedLayout: 0 }
+ }
+ }
+ });
+ const importRoot = await importAnytype({
+ "objects/pg.pb.json": page,
+ "filesObjects/f1.pb.json": fileObjectJson(fileCid, "report", "pdf", "application/pdf", "files\\report.pdf"),
+ "files/report.pdf": Buffer.from("%PDF-1.4 fake")
+ });
+
+ const note = importRoot.getChildNotes().find((n) => n.title === "Page with file");
+ const attachments = note?.getAttachmentsByRole("file") ?? [];
+ expect(attachments.map((a) => a.title)).toEqual(["report.pdf"]);
+ expect(attachments[0]?.mime).toBe("application/pdf");
+
+ // The anchor is rewritten into a Trilium attachment reference-link.
+ const content = decodeUtf8(note?.getContent() ?? "");
+ expect(content).toContain(`class="reference-link"`);
+ expect(content).toContain(`href="#root/${note?.noteId}?viewMode=attachments&attachmentId=${attachments[0]?.attachmentId}"`);
+ expect(content).toContain(">report.pdf</a>");
+ expect(content).not.toContain("anytype-file");
+ });
+
+ it("drops an inline image whose bytes are missing from the export, leaving no broken <img>", async () => {
+ const page = JSON.stringify({
+ sbType: "Page",
+ snapshot: {
+ data: {
+ blocks: [
+ { id: "pg", childrenIds: ["header", "p", "img"] },
+ { id: "header", childrenIds: ["title"] },
+ { id: "title", text: { text: "", style: "Title" } },
+ { id: "p", text: { text: "Body", style: "Paragraph" } },
+ { id: "img", file: { type: "Image", name: "gone.png", targetObjectId: "bafyreimissing", state: "Done", style: "Embed" } }
+ ],
+ details: { id: "pg", name: "Missing image", resolvedLayout: 0 }
+ }
+ }
+ });
+ // No filesObjects/files entries for the referenced id.
+ const importRoot = await importAnytype({ "objects/pg.pb.json": page });
+
+ const note = importRoot.getChildNotes().find((n) => n.title === "Missing image");
+ expect(note?.getAttachmentsByRole("image")).toHaveLength(0);
+ const content = decodeUtf8(note?.getContent() ?? "");
+ // The broken figure is dropped; the rest of the body survives.
+ expect(content).toBe("<p>Body</p>");
+ });
+
it("imports a collection-scoped export (no wrapper) as a named table whose columns are synthesized from members", async () => {
// Exporting a single collection omits the collection object itself, so its members all carry the same
// absent createdInContext — the signal to recover the collection (name from the file, columns from members).
diff --git a/packages/trilium-core/src/services/import/anytype/importer.ts b/packages/trilium-core/src/services/import/anytype/importer.ts
index f7a2805deb..5b632567fd 100644
--- a/packages/trilium-core/src/services/import/anytype/importer.ts
+++ b/packages/trilium-core/src/services/import/anytype/importer.ts
@@ -7,9 +7,12 @@
* headings, inline marks (bold/italic/strikethrough/underline/inline-code and text/background colours),
* code blocks (with the language preserved as the Trilium MIME), bullet/numbered/task lists (grouped and
* nested), toggles (normal toggles → collapsible blocks; toggle headings → plain headings), callouts
- * (→ admonitions), quotes/highlights (→ `<blockquote>`), dividers (→ `<hr>`) and cross-page links
- * (Anytype's block-level "link to object" → a Trilium reference link plus an `internalLink` relation, so
- * backlinks resolve). Each page keeps its original creation and modification timestamps.
+ * (→ admonitions), quotes/highlights (→ `<blockquote>`), dividers (→ `<hr>`), inline file/media blocks
+ * (an embedded image → an inline `role:"image"` attachment; any other attached file → a `role:"file"`
+ * attachment reference link, the bytes resolved from the export's `filesObjects/` metadata + `files/`
+ * bytes) and cross-page links (Anytype's block-level "link to object" → a Trilium reference link plus an
+ * `internalLink` relation, so backlinks resolve). Each page keeps its original creation and modification
+ * timestamps.
*
* Collections and their properties are handled in {@link ./collection.js}: a collection becomes a `book` in
* its mapped view (table / list / grid / calendar / board) whose columns are promoted-attribute definitions,
@@ -23,16 +26,20 @@
*/
import { t } from "i18next";
+import { parse } from "node-html-parser";
import type BNote from "../../../becca/entities/bnote.js";
import cloningService from "../../cloning.js";
+import imageService from "../../image.js";
import noteService from "../../notes.js";
import protectedSessionService from "../../protected_session.js";
import type TaskContext from "../../task_context.js";
+import { decodeUtf8 } from "../../utils/binary.js";
import date_utils from "../../utils/date.js";
import { newEntityId } from "../../utils/index.js";
import { basename } from "../../utils/path.js";
import { getZipProvider } from "../../zip_provider.js";
+import { saveFileAttachment } from "../collection_utils.js";
import { applyCollectionView, applyFiles, applyProperties, buildFileObjectMap, buildOptionMap, buildRelationMap, createCollectionNote, normalizePath, parseCollection, parseFiles, parseProperties, synthesizeColumns } from "./collection.js";
import { extractContent } from "./content.js";
import type { AnytypeDetails, AnytypeSnapshot, FileObjectInfo, LinkResolver, ParsedColumn, ParsedObject, RelationInfo, ResolvedLink } from "./model.js";
@@ -330,6 +337,7 @@ function createNotes(importRootNote: BNote, pages: ParsedObject[], targets: Map<
applyProperties(note, page.properties);
applyFiles(note, page, fileObjects, files);
+ applyInlineFiles(note, fileObjects, files);
applyDates(note, page);
notesByPageId.set(page.id, note);
taskContext.increaseProgressCount();
@@ -359,6 +367,76 @@ function createNotes(importRootNote: BNote, pages: ParsedObject[], targets: Map<
return rootNote;
}
+/**
+ * Resolves the inline file/media placeholders a page's body carries ({@link ./content.js} emits each
+ * `file` block as an `<img>` / `<a class="anytype-file">` whose `src`/`href` is the linked `FileObject`'s
+ * id). For each one it looks the id up in the export's file metadata and bytes, then saves the bytes as an
+ * attachment and rewrites the reference to point at it — an inline `role:"image"` for an image, a
+ * `role:"file"` attachment reference-link for any other file type (matching the Notion importer). A
+ * placeholder whose file is missing from the export (no metadata or bytes — e.g. a still-uploading file) is
+ * dropped (image) or left as plain text (other). Only re-saves the content when something changed.
+ */
+function applyInlineFiles(note: BNote, fileObjects: Map<string, FileObjectInfo>, files: Map<string, Uint8Array>) {
+ const content = decodeUtf8(note.getContent());
+ // Cheap guard: parse only when the body actually holds a placeholder to resolve.
+ if (!content.includes("<img") && !content.includes('class="anytype-file"')) {
+ return;
+ }
+
+ const root = parse(content);
+ let changed = false;
+
+ for (const img of root.querySelectorAll("img")) {
+ const targetId = img.getAttribute("src");
+ const bytes = targetId ? inlineFileBytes(targetId, fileObjects, files) : undefined;
+ if (!targetId || !bytes) {
+ // Unresolved image (still uploading, or bytes absent) — drop the broken figure rather than
+ // leaving an `<img>` pointing at a bare file id.
+ (img.parentNode ?? img).remove();
+ changed = true;
+ continue;
+ }
+ const info = fileObjects.get(targetId);
+ const { attachmentId, title } = imageService.saveImageToAttachment(note.noteId, bytes, info?.title || "image", false);
+ /* v8 ignore next -- saveImageToAttachment always returns the id of the attachment it just created, so this guard is never false in practice */
+ if (attachmentId) {
+ img.setAttribute("src", `api/attachments/${attachmentId}/image/${encodeURIComponent(title)}`);
+ changed = true;
+ }
+ }
+
+ for (const anchor of root.querySelectorAll("a.anytype-file")) {
+ anchor.removeAttribute("class");
+ changed = true;
+
+ const targetId = anchor.getAttribute("href");
+ const info = targetId ? fileObjects.get(targetId) : undefined;
+ const bytes = targetId ? inlineFileBytes(targetId, fileObjects, files) : undefined;
+ if (!info || !bytes) {
+ // Unresolved file — keep the (now class-less) link text but drop the bare-id href.
+ anchor.removeAttribute("href");
+ continue;
+ }
+ const attachment = saveFileAttachment(note, info.title, bytes, info.mime);
+ /* v8 ignore next -- saveAttachment always returns the id of the attachment it just created, so this guard is never false in practice */
+ if (attachment.attachmentId) {
+ anchor.setAttribute("href", `#root/${note.noteId}?viewMode=attachments&attachmentId=${attachment.attachmentId}`);
+ anchor.setAttribute("class", "reference-link");
+ }
+ }
+
+ if (changed) {
+ note.setContent(root.toString());
+ }
+}
+
+/** The raw bytes a file id (an inline block's `targetObjectId`) resolves to, via its `FileObject`'s source
+ * path, or undefined when either the metadata or the bytes are absent from the export. */
+function inlineFileBytes(targetId: string, fileObjects: Map<string, FileObjectInfo>, files: Map<string, Uint8Array>): Uint8Array | undefined {
+ const info = fileObjects.get(targetId);
+ return info ? files.get(normalizePath(info.source)) : undefined;
+}
+
/**
* Restores a page's original timestamps (note creation stamps "modified" — and the blob — with now). A
* date-less page is left untouched, keeping its import-time dates. When only one date is present we fall back
diff --git a/packages/trilium-core/src/services/import/anytype/model.ts b/packages/trilium-core/src/services/import/anytype/model.ts
index 0d5740e473..9bae775c46 100644
--- a/packages/trilium-core/src/services/import/anytype/model.ts
+++ b/packages/trilium-core/src/services/import/anytype/model.ts
@@ -57,6 +57,19 @@ export interface AnytypeBlock {
targetBlockId?: string;
style?: string;
};
+ /** A file/media block — an embedded image, PDF or other attached file. `type` is the kind ("Image",
+ * "PDF", "File", "Audio", "Video"); `targetObjectId` is the linked `FileObject`'s id (resolved to its
+ * bytes via the `filesObjects/` metadata + `files/` bytes); `name` is the original filename. Rendered as
+ * an inline `<img>` (Image) or an attachment reference link (other types) pointing at the saved
+ * attachment. `state` is "Done" once the upload finished — a still-uploading file has no bytes. */
+ file?: {
+ name?: string;
+ type?: string;
+ mime?: string;
+ targetObjectId?: string;
+ state?: string;
+ style?: string;
+ };
/** A "latex" block — Anytype's embed for code-rendered diagrams and math. `processor` picks the renderer
* ("Mermaid" for a Mermaid diagram; otherwise the `text` is LaTeX math). */
latex?: {