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
refactor(attachments): make a role answer for itself, or fail to compile
Elian Dorand53d960ba311
diff --git a/apps/client/src/services/attachment_groups.spec.ts b/apps/client/src/services/attachment_groups.spec.tsindex c5ea4e8aaf..c60b8438bb 100644--- a/apps/client/src/services/attachment_groups.spec.ts+++ b/apps/client/src/services/attachment_groups.spec.ts@@ -1,17 +1,25 @@import { describe, expect, it } from "vitest";-import { attachmentGroupForRole, partitionAttachmentsByGroup, SYSTEM_ATTACHMENT_ROLES } from "./attachment_groups.js";+import { ATTACHMENT_ROLES } from "@triliumnext/commons";++import { ATTACHMENT_ROLE_GROUPS, attachmentGroupForRole, partitionAttachmentsByGroup } from "./attachment_groups.js";describe("attachmentGroupForRole", () => {it("puts what the user placed on one side and what the app made on the other", () => {expect(attachmentGroupForRole("image")).toBe("user");expect(attachmentGroupForRole("file")).toBe("user");- for (const role of SYSTEM_ATTACHMENT_ROLES) {- expect(attachmentGroupForRole(role), role).toBe("system");+ for (const [ role, group ] of Object.entries(ATTACHMENT_ROLE_GROUPS)) {+ expect(attachmentGroupForRole(role), role).toBe(group);}});+ it("places every role the app creates", () => {+ // The types already refuse a `Record` with a role missing from it; this says the same of a+ // role added to neither, which would otherwise reach the list as one more of the user's own.+ expect(Object.keys(ATTACHMENT_ROLE_GROUPS).sort()).toStrictEqual(Object.keys(ATTACHMENT_ROLES).sort());+ });+it("counts a role it has never heard of as the user's", () => {// The default view is the user's, so an unrecognised role — a script's own, or one added to// the app since — shows up rather than being buried under a group nobody thought to open.@@ -19,6 +27,10 @@ describe("attachmentGroupForRole", () => {expect(attachmentGroupForRole("unknownRole")).toBe("user");expect(attachmentGroupForRole(undefined)).toBe("user");expect(attachmentGroupForRole("")).toBe("user");+ // The role is whatever was stored, so these reach the lookup too; read off the object rather+ // than checked against it, they would answer with something from its prototype.+ expect(attachmentGroupForRole("constructor")).toBe("user");+ expect(attachmentGroupForRole("toString")).toBe("user");});it("matches a role exactly, rather than by resemblance", () => {diff --git a/apps/client/src/services/attachment_groups.ts b/apps/client/src/services/attachment_groups.tsindex 563c70ff37..5774386307 100644--- a/apps/client/src/services/attachment_groups.ts+++ b/apps/client/src/services/attachment_groups.ts@@ -1,3 +1,5 @@+import type { AttachmentRole } from "@triliumnext/commons";+/*** Which half of the attachment list an attachment belongs in.*@@ -11,34 +13,43 @@export type AttachmentGroup = "user" | "system";/**- * The roles the app creates for its own purposes.- *- * Listed rather than derived because there is no field that says so: a role is just a string, and- * whether it names something the user placed is knowledge about the role, not about the attachment.+ * Which half each role the app creates belongs in.*- * Named as the *system* half, so that a role nobody here has heard of — a script's own, a role added- * to the app since — counts as the user's and stays in the view that opens by default. The opposite- * arrangement would file each new role under `system` and quietly bury an attachment its owner is- * looking for; this way the worst an unknown role costs is one extra row among the user's own.+ * A `Record` over the roles rather than a list of the system ones, so that a role added to+ * `ATTACHMENT_ROLES` does not compile until it has been placed here. Which half something belongs in+ * is not derivable from the traits that live with the roles themselves — `viewConfig` and `favicon`+ * agree on nothing else — and it is only this list that presents them, so the answer is kept here.*/-export const SYSTEM_ATTACHMENT_ROLES: readonly string[] = [+export const ATTACHMENT_ROLE_GROUPS: Record<AttachmentRole, AttachmentGroup> = {+ // What the reader placed on the note.+ image: "user",+ file: "user",// The two pictures a link preview fetches: a site's icon and a page's thumbnail. Neither is// chosen, and a note that links a lot of pages accumulates a lot of them.- "favicon",- "coverImage",+ favicon: "system",+ coverImage: "system",// How a collection remembers the way it is being looked at, and how the PDF viewer remembers// where the reader had got to.- "viewConfig",+ viewConfig: "system",// Shapes saved into an Excalidraw canvas's library. Kept by the canvas for the canvas, rather// than attached to the note by hand.- "canvasLibraryItem",+ canvasLibraryItem: "system",// The file an import was read from, kept so an import that went wrong can be looked at again.- "importSource"-];+ importSource: "system"+};-/** Which half of the list an attachment of this role belongs in. */+/**+ * Which half of the list an attachment of this role belongs in.+ *+ * A role nobody here has heard of — a script's own, or one from a newer version reached over sync —+ * counts as the user's and stays in the view that opens by default. Filing it under `system` instead+ * would quietly bury an attachment its owner is looking for; this way the worst it costs is one extra+ * row among the user's own.+ */export function attachmentGroupForRole(role: string | undefined | null): AttachmentGroup {- return role && SYSTEM_ATTACHMENT_ROLES.includes(role) ? "system" : "user";+ return (role && Object.hasOwn(ATTACHMENT_ROLE_GROUPS, role)+ ? ATTACHMENT_ROLE_GROUPS[role as AttachmentRole]+ : undefined) ?? "user";}/**diff --git a/packages/commons/src/lib/attachment_roles.spec.ts b/packages/commons/src/lib/attachment_roles.spec.tsindex 81b324e72b..5366825056 100644--- a/packages/commons/src/lib/attachment_roles.spec.ts+++ b/packages/commons/src/lib/attachment_roles.spec.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";-import { IMAGE_ATTACHMENT_ROLES, isDeduplicatedAttachmentRole, isImageAttachmentRole } from "./attachment_roles.js";+import { ATTACHMENT_ROLES, attachmentRoleTraits, IMAGE_ATTACHMENT_ROLES, isDeduplicatedAttachmentRole, isEmbeddedAttachmentRole, isImageAttachmentRole } from "./attachment_roles.js";describe("isImageAttachmentRole", () => {it("recognises every picture role and nothing else", () => {@@ -25,6 +25,55 @@ describe("isImageAttachmentRole", () => {});});+describe("isEmbeddedAttachmentRole", () => {+ it("covers what lives in the note's content, and nothing that manages itself", () => {+ // What the cleanup that erases unreferenced attachments is allowed to look at. A link+ // preview's pictures belong here: nothing manages them, so deleting the preview has to be+ // what eventually takes them with it.+ for (const role of [ "image", "file", "favicon", "coverImage" ]) {+ expect(isEmbeddedAttachmentRole(role), role).toBe(true);+ }++ // Nothing in the content ever refers to these, so letting the cleanup see them would erase+ // every one of them on the next save.+ for (const role of [ "viewConfig", "canvasLibraryItem", "importSource" ]) {+ expect(isEmbeddedAttachmentRole(role), role).toBe(false);+ }+ });+});++describe("attachmentRoleTraits", () => {+ it("answers nothing for a role it does not recognise", () => {+ // A script's own role, or one from a newer version reached over sync.+ expect(attachmentRoleTraits("somethingAScriptInvented")).toBeUndefined();+ expect(attachmentRoleTraits(undefined)).toBeUndefined();+ expect(attachmentRoleTraits("")).toBeUndefined();++ // The role is whatever was stored, so these reach the lookup too. Read off the table rather+ // than checked against it, they would answer with something from its prototype — and+ // `"constructor"` is truthy, which would make every question below answer yes.+ expect(attachmentRoleTraits("constructor")).toBeUndefined();+ expect(attachmentRoleTraits("toString")).toBeUndefined();+ expect(isImageAttachmentRole("constructor")).toBe(false);+ });++ it("gives every role an answer to every question", () => {+ // The types already refuse a role that arrives without one; this says the same at runtime,+ // for the shape the table is actually read with.+ for (const [ role, traits ] of Object.entries(ATTACHMENT_ROLES)) {+ expect(Object.keys(traits).sort(), role).toStrictEqual([ "deduplicated", "embedded", "picture" ]);+ }+ });++ it("is what the questions are answered from", () => {+ for (const [ role, traits ] of Object.entries(ATTACHMENT_ROLES)) {+ expect(isImageAttachmentRole(role), role).toBe(traits.picture);+ expect(isDeduplicatedAttachmentRole(role), role).toBe(traits.deduplicated);+ expect(isEmbeddedAttachmentRole(role), role).toBe(traits.embedded);+ }+ });+});+describe("isDeduplicatedAttachmentRole", () => {it("deduplicates only what the app named itself", () => {// A site's icon: one per site rather than one per link to it.diff --git a/packages/commons/src/lib/attachment_roles.ts b/packages/commons/src/lib/attachment_roles.tsindex b0c02ef330..6795f68d1b 100644--- a/packages/commons/src/lib/attachment_roles.ts+++ b/packages/commons/src/lib/attachment_roles.ts@@ -1,48 +1,113 @@/**- * The attachment roles whose content is a picture.+ * What the app knows about an attachment of a given role.*- * A role is not a label — it is what the code branches on. `image` alone used to mean "this- * attachment is a picture", so every such branch spelled it that way, and a second picture role- * has to be admitted to all of them at once or it half-works: served but never cleaned up, cleaned- * up but never served, listed but rendered as an unknown file.+ * A role is not a label — it is what the code branches on, and each of these is a branch that used to+ * be written out by name at every site that cared. Spelling them here instead is what makes adding a+ * role a decision taken once: {@link ATTACHMENT_ROLES} is checked against this shape, so a role that+ * arrives without an answer to every question below does not compile, rather than half-working —+ * served but never cleaned up, cleaned up but never served, listed but rendered as an unknown file.+ */+export interface AttachmentRoleTraits {+ /**+ * Whether the content is a picture, and so is served, rendered and converted as one.+ *+ * `image` alone used to mean this, so every such branch spelled it that way, and a second picture+ * role had to be admitted to all of them at once.+ */+ picture: boolean;+ /**+ * Whether a second attachment of this role and title should reuse the first rather than be stored+ * again.+ *+ * Only for pictures the app fetched and named itself, where the title says which thing it is and+ * the same thing is fetched again and again: a note that links a site once usually links it many+ * times, and each link would otherwise bring its own copy of that site's icon. The title is the+ * key, so for these it is the caller's job to make it identify the thing — a site's hostname for a+ * favicon, a page's URL for its cover — and the server's not to shorten it.+ *+ * Never for a picture the user placed. Two images they happened to give the same name are two+ * images, and quietly collapsing them would lose one.+ */+ deduplicated: boolean;+ /**+ * Whether the attachment lives in the note's content, and so is scheduled for erasure once nothing+ * there refers to it any more.+ *+ * False for the ones their owner manages explicitly — a collection's saved view, a canvas's+ * library, the file an import was read from. Nothing in the content ever refers to those, so+ * leaving them to the cleanup would erase every one of them on the next save.+ */+ embedded: boolean;+}++/**+ * Every role the app itself creates, and what it does with each.*- * `favicon` and `coverImage` are separate from `image` so the two pictures a link preview carries- * can be told apart from one the user put in the note — they are created, deduplicated and replaced- * on completely different terms, and only `image` is something the user chose. Keeping them apart- * also keeps them out of the places that reason about the user's own pictures: both arrive already- * sized by the server (a 16x16 icon, a 256px thumbnail), so the compression inventory has nothing- * to gain from either and offering to recompress one is noise.+ * Not a closed set at runtime: a script or ETAPI client can attach anything under a role of its own,+ * which is why the questions are asked of a `string` below rather than of this union. It is closed to+ * *us*, though — see {@link AttachmentRoleTraits}.*/-export const IMAGE_ATTACHMENT_ROLES = [ "image", "favicon", "coverImage" ] as const;+export const ATTACHMENT_ROLES = {+ /** A picture the user placed in the note. */+ image: { picture: true, deduplicated: false, embedded: true },+ /** A file the user attached to the note. */+ file: { picture: false, deduplicated: false, embedded: true },+ /**+ * A link preview's two pictures, kept apart from `image` so they can be told from one the user+ * chose. Both arrive already sized by the server (a 16x16 icon, a 256px thumbnail), so the+ * compression inventory has nothing to gain from either and offering to recompress one is noise.+ * They are embedded all the same: nothing else manages them, so deleting the preview has to be+ * what eventually takes them with it.+ */+ favicon: { picture: true, deduplicated: true, embedded: true },+ coverImage: { picture: true, deduplicated: true, embedded: true },+ /** How a collection remembers the way it is being looked at, and a PDF where the reader had got to. */+ viewConfig: { picture: false, deduplicated: false, embedded: false },+ /** Shapes saved into an Excalidraw canvas's library. */+ canvasLibraryItem: { picture: false, deduplicated: false, embedded: false },+ /** The file an import was read from, kept so an import that went wrong can be looked at again. */+ importSource: { picture: false, deduplicated: false, embedded: false }+} as const satisfies Record<string, AttachmentRoleTraits>;-export type ImageAttachmentRole = typeof IMAGE_ATTACHMENT_ROLES[number];+/** A role the app itself creates. Arbitrary strings reach the same fields — see {@link ATTACHMENT_ROLES}. */+export type AttachmentRole = keyof typeof ATTACHMENT_ROLES;++/** The roles whose content is a picture, read off {@link ATTACHMENT_ROLES} rather than listed again. */+export type ImageAttachmentRole = {+ [Role in AttachmentRole]: typeof ATTACHMENT_ROLES[Role]["picture"] extends true ? Role : never+}[AttachmentRole];++/** @see ImageAttachmentRole */+export const IMAGE_ATTACHMENT_ROLES: readonly ImageAttachmentRole[] =+ attachmentRolesWhere("picture") as readonly ImageAttachmentRole[];/** Whether an attachment of this role holds a picture, whoever created it. */export function isImageAttachmentRole(role: string | undefined | null): role is ImageAttachmentRole {- return !!role && (IMAGE_ATTACHMENT_ROLES as readonly string[]).includes(role);+ return attachmentRoleTraits(role)?.picture ?? false;+}++/** @see AttachmentRoleTraits.deduplicated */+export function isDeduplicatedAttachmentRole(role: string | undefined | null): boolean {+ return attachmentRoleTraits(role)?.deduplicated ?? false;+}++/** @see AttachmentRoleTraits.embedded */+export function isEmbeddedAttachmentRole(role: string | undefined | null): boolean {+ return attachmentRoleTraits(role)?.embedded ?? false;}/**- * Roles that keep one attachment per title in a note, rather than one per use.- *- * Only for pictures the app fetched and named itself, where the title says which thing it is and- * the same thing is fetched again and again. A note that links a site once usually links it many- * times, so each link would otherwise bring its own copy of that site's icon; and pasting the same- * URL twice is ordinary, so each paste would bring its own copy of that page's cover. One row per- * thing instead of one per use is the difference between an attachment list a reader can use and a- * wall of identical pictures.+ * What the app knows about this role, or nothing at all for one it does not recognise — a script's+ * own, or a role from a newer version reached over sync.*- * Never for a picture the user placed. Two images they happened to give the same name are two- * images, and quietly collapsing them would lose one.+ * `hasOwn` rather than a plain lookup: the role is whatever was stored, so `"constructor"` and+ * `"toString"` reach this, and reading them off the object would answer with something from its+ * prototype instead of with nothing.*/-const DEDUPLICATED_ATTACHMENT_ROLES: readonly string[] = [ "favicon", "coverImage" ];+export function attachmentRoleTraits(role: string | undefined | null): AttachmentRoleTraits | undefined {+ return role && Object.hasOwn(ATTACHMENT_ROLES, role) ? ATTACHMENT_ROLES[role as AttachmentRole] : undefined;+}-/**- * Whether a second attachment of this role and title should reuse the first rather than be stored- * again. The title is the key, so for these roles it is the caller's job to make it identify the- * thing — a site's hostname for a favicon, a page's URL for its cover — and the server's not to- * shorten it.- */-export function isDeduplicatedAttachmentRole(role: string | undefined | null): boolean {- return !!role && DEDUPLICATED_ATTACHMENT_ROLES.includes(role);+function attachmentRolesWhere(trait: keyof AttachmentRoleTraits): readonly AttachmentRole[] {+ return (Object.keys(ATTACHMENT_ROLES) as AttachmentRole[]).filter((role) => ATTACHMENT_ROLES[role][trait]);}diff --git a/packages/trilium-core/src/services/notes.ts b/packages/trilium-core/src/services/notes.tsindex 11d1bdab8f..3bb9300f55 100644--- a/packages/trilium-core/src/services/notes.ts+++ b/packages/trilium-core/src/services/notes.ts@@ -1,4 +1,4 @@-import { type AttachmentRow, type AttributeRow, type BranchRow, dayjs, isImageAttachmentRole, type NoteRow, NOTE_TYPE_IMAGE_ATTACHMENTS, type NoteType } from "@triliumnext/commons";+import { type AttachmentRow, type AttributeRow, type BranchRow, dayjs, isEmbeddedAttachmentRole, isImageAttachmentRole, type NoteRow, NOTE_TYPE_IMAGE_ATTACHMENTS, type NoteType } from "@triliumnext/commons";import { t } from "i18next";import { parse as parseHtml } from "node-html-parser";import url from "url";@@ -483,12 +483,10 @@ export function checkImageAttachments(note: BNote, content: string) {const attachments = note.getAttachments();for (const attachment of attachments) {- // Only attachments that are meant to be embedded in the note content (pictures, files) are- // auto-scheduled for erasure when no longer referenced. Other roles (e.g. "viewConfig",- // "importSource") are managed explicitly by their owners and must not be cleaned up here.- // A link preview's favicon belongs to the first group: nothing manages it, so deleting the- // preview has to be what eventually takes the icon with it.- if (!isImageAttachmentRole(attachment.role) && attachment.role !== "file") {+ // Only attachments that live in the note content are auto-scheduled for erasure when nothing+ // refers to them any more; the rest are managed explicitly by their owners and must not be+ // cleaned up here. Which is which is a property of the role — see `AttachmentRoleTraits`.+ if (!isEmbeddedAttachmentRole(attachment.role)) {continue;}