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(anytype): import a single-collection export as a named table
Elian Dorande66b84185fc
diff --git a/packages/trilium-core/src/routes/api/import.ts b/packages/trilium-core/src/routes/api/import.tsindex 61f492c377..fab30df1db 100644--- a/packages/trilium-core/src/routes/api/import.ts+++ b/packages/trilium-core/src/routes/api/import.ts@@ -69,7 +69,7 @@ async function importNotesToBranch(req: ImportRequest<{ parentNoteId: string }>)} else if (format === "anytype" && typeof file.buffer !== "string") {// An Anytype JSON export is likewise a plain `.zip`; the Anytype import dialog tags the upload so// it routes to the Anytype importer rather than the generic zip importer.- note = await anytypeImportService.importAnytype(taskContext, file.buffer, parentNote);+ note = await anytypeImportService.importAnytype(taskContext, file.buffer, parentNote, file.originalname);} else if (extension === ".zip" && options.explodeArchives && typeof file.buffer !== "string") {note = await zipImportService.importZip(taskContext, file.buffer, parentNote);} else if (extension === ".opml" && options.explodeArchives) {diff --git a/packages/trilium-core/src/services/import/anytype/collection.spec.ts b/packages/trilium-core/src/services/import/anytype/collection.spec.tsindex df4962c47b..45c240d16a 100644--- a/packages/trilium-core/src/services/import/anytype/collection.spec.ts+++ b/packages/trilium-core/src/services/import/anytype/collection.spec.ts@@ -1,5 +1,6 @@import { describe, expect, it } from "vitest";+import { synthesizeColumns } from "./collection.js";import { isCollectionObject, isPage, parseObject } from "./importer.js";import type { AnytypeBlock, AnytypeMark, AnytypeSnapshot, RelationInfo } from "./model.js";@@ -211,4 +212,16 @@ describe("collection properties", () => {expect(parseObject(page("Plain", [textBlock("b1", "body")]), undefined, rels).collection).toBeUndefined();});});++ describe("synthesizeColumns", () => {+ it("builds the union of the members' supported custom-relation columns, de-duplicated, in first-seen order", () => {+ // A collection-scoped export has no view, so the columns come from the properties the members carry.+ const m1 = { id: "m1", "6a3e335dcafa6953a4661c74": "https://x" }; // URL+ const m2 = { id: "m2", "6a3e336dcafa6953a4661c75": "[email protected]", "6a3e335dcafa6953a4661c74": "https://y" }; // Email + URL (already seen)+ expect(synthesizeColumns([m1, m2], rels)).toEqual([+ { name: "url", labelType: "url", alias: "URL", multiplicity: "single" },+ { name: "email", labelType: "url", alias: "Email", multiplicity: "single" }+ ]);+ });+ });});diff --git a/packages/trilium-core/src/services/import/anytype/collection.ts b/packages/trilium-core/src/services/import/anytype/collection.tsindex d7d59d3547..c4c7cc696c 100644--- a/packages/trilium-core/src/services/import/anytype/collection.ts+++ b/packages/trilium-core/src/services/import/anytype/collection.ts@@ -175,11 +175,25 @@ export function parseCollection(blocks: AnytypeBlock[], details: AnytypeDetails,return undefined;}+ const visibleKeys = (dataview.views?.[0]?.relations ?? []).filter((relation) => relation.isVisible).map((relation) => relation.key);+ return { memberIds: details.links ?? [], columns: columnsFromKeys(visibleKeys, relations) };+}++/**+ * Synthesizes a table schema for a collection-scoped export, whose collection wrapper (and therefore its+ * view) wasn't exported — so there's no column list. The columns are the union of the supported custom+ * relations actually carried by the member objects, in first-seen order, de-duplicated by attribute name.+ */+export function synthesizeColumns(memberDetails: AnytypeDetails[], relations: Map<string, RelationInfo>): ParsedColumn[] {+ return columnsFromKeys(memberDetails.flatMap((details) => Object.keys(details)), relations);+}++/** Maps a list of relation keys to their (supported, custom) table columns, in order, de-duplicated by name. */+function columnsFromKeys(keys: (string | undefined)[], relations: Map<string, RelationInfo>): ParsedColumn[] {const columns: ParsedColumn[] = [];const seen = new Set<string>();- for (const relation of dataview.views?.[0]?.relations ?? []) {- const key = relation.key;- if (!relation.isVisible || !key || !isCustomRelationKey(key)) {+ for (const key of keys) {+ if (!key || !isCustomRelationKey(key)) {continue;}const info = relations.get(key);@@ -193,8 +207,7 @@ export function parseCollection(blocks: AnytypeBlock[], details: AnytypeDetails,columns.push({ name, labelType: mapping.labelType, alias: info.name, multiplicity: mapping.multiplicity });}}-- return { memberIds: details.links ?? [], columns };+ return columns;}/**@@ -243,16 +256,25 @@ function formatPropertyValue(raw: unknown, labelType: PropertyLabelType, scheme:*/export function createCollectionNote(parentNoteId: string, page: ParsedObject, collection: ParsedCollection, noteId: string | undefined, isProtected: boolean | undefined): BNote {const { note } = noteService.createNewNote({ noteId, parentNoteId, title: page.title, content: "", type: "book", mime: "", isProtected, utcDateCreated: page.dateCreated });+ applyTableView(note, collection.columns);+ return note;+}++/**+ * Turns `note` into a `table`-view collection whose columns are the given properties, each an *inheritable*+ * promoted-attribute definition (so the table renders the column and every child row inherits the field,+ * showing its own value or blank). Used for both an imported collection and a collection-scoped export's root.+ */+export function applyTableView(note: BNote, columns: ParsedColumn[]) {note.addLabel("viewType", "table");- // Increasing positions keep the columns in their Anytype view order (the promoted-attributes UI sorts by+ // Increasing positions keep the columns in their stored order (the promoted-attributes UI sorts by// position, and equal positions aren't ordered deterministically).let position = 0;- for (const column of collection.columns) {+ for (const column of columns) {position += 10;note.addAttribute("label", `label:${column.name}`, buildPromotedDefinition({ alias: column.alias, labelType: column.labelType, multiplicity: column.multiplicity }), true, position);}- return note;}/** Applies a page's custom property values to its note as labels. */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.tsindex 96baeeffa8..0776de198c 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@@ -24,7 +24,7 @@ async function createZipBuffer(files: Record<string, string | Buffer>): Promise<}/** Runs the Anytype importer over `files` and returns the import root note. */-async function importAnytype(files: Record<string, string | Buffer>): Promise<BNote> {+async function importAnytype(files: Record<string, string | Buffer>, fileName?: string): Promise<BNote> {const buffer = await createZipBuffer(files);const taskContext = TaskContext.getInstance("anytype-integration", "importNotes", { safeImport: true });@@ -32,7 +32,7 @@ async function importAnytype(files: Record<string, string | Buffer>): Promise<BNvoid getContext().init(async () => {try {const root = becca.getNoteOrThrow("root");- resolve(await anytypeImporter.importAnytype(taskContext, new Uint8Array(buffer), root));+ resolve(await anytypeImporter.importAnytype(taskContext, new Uint8Array(buffer), root, fileName));} catch (e) {reject(e);}@@ -620,6 +620,45 @@ describe("Anytype importer — integration", () => {expect(content).toContain(">log.txt</a>");});+ 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).+ const ctx = "bafyreicollectioncontext";+ const urlKey = "6a3e335dcafa6953a4661c74";+ const importRoot = await importAnytype(+ {+ "objects/m1.pb.json": memberObject("m1", { createdInContext: ctx, [urlKey]: "https://triliumnotes.org" }),+ "objects/m2.pb.json": memberObject("m2", { createdInContext: ctx }),+ "relations/url.pb.json": relationObject(urlKey, "URL", 7)+ },+ "My custom collection.zip"+ );++ // The root *is* the collection: named from the zip, a table whose column is synthesized from the member.+ expect(importRoot.title).toBe("My custom collection");+ expect(importRoot.type).toBe("book");+ expect(importRoot.getOwnedLabelValue("viewType")).toBe("table");+ expect(importRoot.getOwnedLabelValue("label:url")).toBe("promoted,single,url,alias=URL");++ // The members are its rows, carrying their own values.+ const rows = importRoot.getChildNotes();+ expect(rows).toHaveLength(2);+ expect(rows.find((n) => n.getOwnedLabelValue("url"))?.getOwnedLabelValue("url")).toBe("https://triliumnotes.org");+ });++ it("keeps the default 'Anytype import' text root for a regular multi-page export", async () => {+ const importRoot = await importAnytype(+ {+ "objects/p1.pb.json": pageObject("p1", "Page one", ["body"]),+ "objects/p2.pb.json": pageObject("p2", "Page two", ["body"])+ },+ "Some space export.zip"+ );++ expect(importRoot.title).toBe("Anytype import");+ expect(importRoot.type).toBe("text");+ });+it("produces an empty root when the export has no pages", async () => {const importRoot = await importAnytype({"types/type1.pb.json": JSON.stringify({ sbType: "STType", snapshot: { data: { details: { id: "type1", name: "Article" } } } })diff --git a/packages/trilium-core/src/services/import/anytype/importer.spec.ts b/packages/trilium-core/src/services/import/anytype/importer.spec.tsindex eee09c0d9f..8d7f5cf285 100644--- a/packages/trilium-core/src/services/import/anytype/importer.spec.ts+++ b/packages/trilium-core/src/services/import/anytype/importer.spec.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";-import { anytypeDate, isPage, parseObject } from "./importer.js";+import { anytypeDate, collectionTitleFromFileName, isPage, isSingleCollectionExport, parseObject } from "./importer.js";import type { AnytypeBlock, AnytypeMark, AnytypeSnapshot } from "./model.js";/** Wraps blocks + details into the export's snapshot shape. Details accepts arbitrary relation-key entries@@ -137,3 +137,30 @@ describe("dates", () => {expect(result.dateModified).toBeUndefined();});});++describe("single-collection export", () => {+ /** A page created inside `ctx` (the collection's id). */+ const member = (id: string, ctx?: string) => snapshot([{ id, childrenIds: [] }], { id, name: "", createdInContext: ctx });++ it("detects an export whose pages all share one createdInContext that is itself absent", () => {+ // A collection-scoped export ships only the members; the collection wrapper (their shared context) is gone.+ const pages = [member("m1", "coll"), member("m2", "coll"), member("m3", "coll")];+ expect(isSingleCollectionExport(pages, new Set(["m1", "m2", "m3"]))).toBe(true);+ });++ it("rejects when the shared context is present (a full export keeps the collection wrapper)", () => {+ const pages = [member("m1", "coll"), member("m2", "coll")];+ expect(isSingleCollectionExport(pages, new Set(["m1", "m2", "coll"]))).toBe(false);+ });++ it("rejects when the pages don't all share one context, when a page has none, and when there are no pages", () => {+ expect(isSingleCollectionExport([member("m1", "coll"), member("m2", "other")], new Set(["m1", "m2"]))).toBe(false);+ expect(isSingleCollectionExport([member("m1", "coll"), member("m2")], new Set(["m1", "m2"]))).toBe(false);+ expect(isSingleCollectionExport([], new Set())).toBe(false);+ });++ it("derives the root title from the export file name, dropping the extension", () => {+ expect(collectionTitleFromFileName("My custom collection.zip")).toBe("My custom collection");+ expect(collectionTitleFromFileName("noext")).toBe("noext");+ });+});diff --git a/packages/trilium-core/src/services/import/anytype/importer.ts b/packages/trilium-core/src/services/import/anytype/importer.tsindex 9e64375101..65d72133ed 100644--- a/packages/trilium-core/src/services/import/anytype/importer.ts+++ b/packages/trilium-core/src/services/import/anytype/importer.ts@@ -30,12 +30,13 @@ import protectedSessionService from "../../protected_session.js";import type TaskContext from "../../task_context.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 { applyFiles, applyProperties, buildFileObjectMap, buildOptionMap, buildRelationMap, createCollectionNote, normalizePath, parseCollection, parseFiles, parseProperties } from "./collection.js";+import { applyFiles, applyProperties, applyTableView, buildFileObjectMap, buildOptionMap, buildRelationMap, createCollectionNote, normalizePath, parseCollection, parseFiles, parseProperties, synthesizeColumns } from "./collection.js";import { extractContent } from "./content.js";-import type { AnytypeDetails, AnytypeSnapshot, FileObjectInfo, LinkResolver, ParsedObject, RelationInfo, ResolvedLink } from "./model.js";+import type { AnytypeDetails, AnytypeSnapshot, FileObjectInfo, LinkResolver, ParsedColumn, ParsedObject, RelationInfo, ResolvedLink } from "./model.js";-async function importAnytype(taskContext: TaskContext<"importNotes">, fileBuffer: Uint8Array, importRootNote: BNote): Promise<BNote> {+async function importAnytype(taskContext: TaskContext<"importNotes">, fileBuffer: Uint8Array, importRootNote: BNote, fileName?: string): Promise<BNote> {const { objects, relations, options, fileObjects, files } = await parseZip(fileBuffer);const relationMap = buildRelationMap(relations);const optionMap = buildOptionMap(options);@@ -44,6 +45,14 @@ async function importAnytype(taskContext: TaskContext<"importNotes">, fileBuffer// query sets and system objects stay out.const pageSnapshots = objects.filter((snapshot) => isPage(snapshot) || isCollectionObject(snapshot));+ // A collection-scoped export omits the collection itself (Anytype doesn't export the wrapper), so its+ // name and column schema are lost. Recover them: name the import root from the zip and make it a `table`+ // collection whose columns are synthesized from the properties its member pages carry.+ const objectIds = new Set(objects.map((snapshot) => snapshot.snapshot?.data?.details?.id).filter((id): id is string => !!id));+ const collectionExport = !!fileName && isSingleCollectionExport(pageSnapshots, objectIds);+ const rootTitle = collectionExport && fileName ? collectionTitleFromFileName(fileName) : undefined;+ const rootColumns = collectionExport ? synthesizeColumns(pageSnapshots.map((snapshot) => snapshot.snapshot?.data?.details ?? {}), relationMap) : undefined;+// Assign each page its Trilium note id up front so cross-page links resolve even when they point at a// page that hasn't been created yet (links routinely point forward in the export). The note is later// created with this forced id, keeping the reference link's href and the real note in sync.@@ -60,7 +69,7 @@ async function importAnytype(taskContext: TaskContext<"importNotes">, fileBufferconst pages = pageSnapshots.map((snapshot) => parseObject(snapshot, resolveLink, relationMap, optionMap));taskContext.setTotalCount(pages.length);- return createNotes(importRootNote, pages, targets, fileObjectMap, files, taskContext);+ return createNotes(importRootNote, pages, targets, fileObjectMap, files, rootTitle, rootColumns, taskContext);}/**@@ -163,6 +172,30 @@ export function isCollectionObject(snapshot: AnytypeSnapshot): boolean {return (snapshot.snapshot?.data?.blocks ?? []).some((block) => block.dataview?.isCollection);}+/**+ * Whether the export is a single collection's contents. Exporting just a collection (rather than the whole+ * space) omits the collection object itself, so its name is lost and only its member objects ship — each+ * created inside the same (now absent) collection. So: every imported page shares one `createdInContext` id+ * that isn't itself present in the export. A regular export fails this (pages have varied or no context, and+ * a full export keeps the collection wrapper). When true, the import root is named from the zip instead.+ */+export function isSingleCollectionExport(pageSnapshots: AnytypeSnapshot[], objectIds: Set<string>): boolean {+ if (pageSnapshots.length === 0) {+ return false;+ }+ const context = pageSnapshots[0].snapshot?.data?.details?.createdInContext;+ if (!context || objectIds.has(context)) {+ return false;+ }+ return pageSnapshots.every((snapshot) => snapshot.snapshot?.data?.details?.createdInContext === context);+}++/** The import-root title for a collection-scoped export: the export file's base name without its extension. */+export function collectionTitleFromFileName(fileName: string): string {+ const base = basename(fileName.replace(/\\/g, "/"));+ return base.replace(/\.[^.]+$/, "").trim() || base;+}+/*** Reduces a page snapshot to the title, body HTML, outgoing link targets, property values and (for a* collection) its table schema and membership. `resolveLink` maps a linked object's id to the Trilium note@@ -216,11 +249,19 @@ export function anytypeDate(seconds: number | undefined): string | undefined {* the body. Once every page exists, each page's outgoing links are recorded as `internalLink` relations,* which Trilium uses for backlink detection ("what links here").*/-function createNotes(importRootNote: BNote, pages: ParsedObject[], targets: Map<string, ResolvedLink>, fileObjects: Map<string, FileObjectInfo>, files: Map<string, Uint8Array>, taskContext: TaskContext<"importNotes">): BNote {+function createNotes(importRootNote: BNote, pages: ParsedObject[], targets: Map<string, ResolvedLink>, fileObjects: Map<string, FileObjectInfo>, files: Map<string, Uint8Array>, rootTitle: string | undefined, rootColumns: ParsedColumn[] | undefined, taskContext: TaskContext<"importNotes">): BNote {/* v8 ignore next -- the protected branch needs a protected import root with an active protected session, which the in-memory test DB has no way to set up */const isProtected = importRootNote.isProtected && protectedSessionService.isProtectedSessionAvailable();- const rootNote = noteService.createNewNote({ parentNoteId: importRootNote.noteId, title: t("anytype_import.root-title"), content: "", type: "text", mime: "text/html", isProtected }).note;+ // A collection-scoped export's root *is* the collection: a `table`-view book carrying the synthesized+ // columns, with the member pages as its rows. A normal export's root is a plain container.+ const title = rootTitle ?? t("anytype_import.root-title");+ const rootNote = rootColumns+ ? noteService.createNewNote({ parentNoteId: importRootNote.noteId, title, content: "", type: "book", mime: "", isProtected }).note+ : noteService.createNewNote({ parentNoteId: importRootNote.noteId, title, content: "", type: "text", mime: "text/html", isProtected }).note;+ if (rootColumns) {+ applyTableView(rootNote, rootColumns);+ }rootNote.addLabel("iconClass", "bx bx-import");// Each member's primary parent is the first collection that lists it (a collection itself stays at thediff --git a/packages/trilium-core/src/services/import/anytype/model.ts b/packages/trilium-core/src/services/import/anytype/model.tsindex 8dffd533a5..4b726624c4 100644--- a/packages/trilium-core/src/services/import/anytype/model.ts+++ b/packages/trilium-core/src/services/import/anytype/model.ts@@ -86,6 +86,10 @@ export interface AnytypeDetails {lastModifiedDate?: number;/** Outgoing object links; for a collection, this is its membership. */links?: string[];+ /** The id of the object (e.g. a collection) this object was created inside. A collection-scoped export+ * omits the collection itself, so its members all point at the same absent id — the signal that the+ * export is a single collection's contents. */+ createdInContext?: string;/** On a relation-definition object: the key objects carry the value under, the format code, and (for a* date format) whether the value includes a time component. */relationKey?: string;