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(attributes): keep one promoted attribute definition parser
Elian Doran082debf60376
diff --git a/apps/client/src/entities/fattribute.ts b/apps/client/src/entities/fattribute.tsindex 2d5ddbf264..df5dd9a52c 100644--- a/apps/client/src/entities/fattribute.ts+++ b/apps/client/src/entities/fattribute.ts@@ -1,5 +1,6 @@+import { promotedAttributeDefinitionParser } from "@triliumnext/commons";+import type { Froca } from "../services/froca-interface.js";-import promotedAttributeDefinitionParser from "../services/promoted_attribute_definition_parser.js";/*** There are currently only two types of attributes, labels or relations.diff --git a/apps/client/src/services/promoted_attribute_definition_parser.spec.ts b/apps/client/src/services/promoted_attribute_definition_parser.spec.tsdeleted file mode 100644index a6ae4da858..0000000000--- a/apps/client/src/services/promoted_attribute_definition_parser.spec.ts+++ /dev/null@@ -1,95 +0,0 @@-import { describe, expect, it, vi } from "vitest";--import parser, { extractAttributeDefinitionTypeAndName } from "./promoted_attribute_definition_parser.js";--describe("promoted_attribute_definition_parser.parse", () => {- it("parses promoted, label type and multiplicity tokens (with surrounding whitespace)", () => {- const def = parser.parse(" promoted , number , single ");-- expect(def).toEqual({- isPromoted: true,- labelType: "number",- multiplicity: "single"- });- });-- it("accepts every supported label type and multi multiplicity", () => {- const labelTypes = ["text", "textarea", "number", "boolean", "date", "datetime", "time", "url", "color"];- for (const labelType of labelTypes) {- expect(parser.parse(labelType)).toEqual({ labelType });- }-- expect(parser.parse("multi")).toEqual({ multiplicity: "multi" });- });-- it("parses precision, alias and inverse key=value tokens", () => {- const def = parser.parse("precision=2,alias=foo,inverse=isChildOf");-- expect(def).toEqual({- numberPrecision: 2,- promotedAlias: "foo",- inverseRelation: "isChildOf"- });- });-- it("logs and ignores unrecognized tokens", () => {- const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});- try {- const def = parser.parse("bogus");- expect(def).toEqual({});- expect(logSpy).toHaveBeenCalledWith("Unrecognized attribute definition token:", "bogus");- } finally {- logSpy.mockRestore();- }- });-});--describe("promoted_attribute_definition_parser.serialize", () => {- it("writes the promoted flag and its alias, the alias only when promoted", () => {- expect(parser.serialize({ isPromoted: true, promotedAlias: "Foo" }, "label")).toBe("promoted,alias=Foo,single,text");-- // An alias is meaningless without the flag, so it is left out.- expect(parser.serialize({ promotedAlias: "Foo" }, "label")).toBe("single,text");- });-- it("falls back to the multiplicity and label type the consumers assume", () => {- expect(parser.serialize({}, "label")).toBe("single,text");- expect(parser.serialize({}, "relation")).toBe("single");- expect(parser.serialize({ multiplicity: "multi", labelType: "boolean" }, "label")).toBe("multi,boolean");- });-- it("writes the precision only for a number with one set", () => {- expect(parser.serialize({ labelType: "number", numberPrecision: 2 }, "label")).toBe("single,number,precision=2");- expect(parser.serialize({ labelType: "number" }, "label")).toBe("single,number");- expect(parser.serialize({ labelType: "text", numberPrecision: 2 }, "label")).toBe("single,text");- // Zero digits is a precision like any other.- expect(parser.serialize({ labelType: "number", numberPrecision: 0 }, "label")).toBe("single,number,precision=0");- });-- it("writes the inverse relation for relations only, filtering invalid characters", () => {- expect(parser.serialize({ inverseRelation: "isChildOf" }, "relation")).toBe("single,inverse=isChildOf");- expect(parser.serialize({ inverseRelation: "is child#Of!" }, "relation")).toBe("single,inverse=ischildOf");-- // A blank name is dropped, and a label definition has no inverse to write.- expect(parser.serialize({ inverseRelation: " " }, "relation")).toBe("single");- expect(parser.serialize({ inverseRelation: "isChildOf" }, "label")).toBe("single,text");- });-- it("round-trips through parse without losing settings", () => {- const labelDefinition = "promoted,alias=Foo,multi,number,precision=2";- expect(parser.serialize(parser.parse(labelDefinition), "label")).toBe(labelDefinition);-- const relationDefinition = "promoted,single,inverse=isChildOf";- expect(parser.serialize(parser.parse(relationDefinition), "relation")).toBe(relationDefinition);- });-});--describe("extractAttributeDefinitionTypeAndName", () => {- it("extracts the label type and strips the prefix", () => {- expect(extractAttributeDefinitionTypeAndName("label:TEST:TEST1")).toEqual(["label", "TEST:TEST1"]);- });-- it("treats anything not starting with label: as a relation", () => {- expect(extractAttributeDefinitionTypeAndName("relation:author")).toEqual(["relation", "author"]);- });-});diff --git a/apps/client/src/services/promoted_attribute_definition_parser.ts b/apps/client/src/services/promoted_attribute_definition_parser.tsdeleted file mode 100644index 65551f7f53..0000000000--- a/apps/client/src/services/promoted_attribute_definition_parser.ts+++ /dev/null@@ -1,91 +0,0 @@-import { DefinitionObject, LabelType, Multiplicity } from "@triliumnext/commons";--import utils from "./utils.js";--const { filterAttributeName } = utils;--function parse(value: string) {- const tokens = value.split(",").map((t) => t.trim());- const defObj: DefinitionObject = {};-- for (const token of tokens) {- if (token === "promoted") {- defObj.isPromoted = true;- } else if (["text", "textarea", "number", "boolean", "date", "datetime", "time", "url", "color"].includes(token)) {- defObj.labelType = token as LabelType;- } else if (["single", "multi"].includes(token)) {- defObj.multiplicity = token as Multiplicity;- } else if (token.startsWith("precision")) {- const chunks = token.split("=");-- defObj.numberPrecision = parseInt(chunks[1]);- } else if (token.startsWith("alias")) {- const chunks = token.split("=");-- defObj.promotedAlias = chunks[1];- } else if (token.startsWith("inverse")) {- const chunks = token.split("=");-- defObj.inverseRelation = chunks[1];- } else {- console.log("Unrecognized attribute definition token:", token);- }- }-- return defObj;-}--/**- * Serializes a definition back into the comma separated form stored in the attribute value, e.g.- * `promoted,alias=Foo,single,number,precision=2`. The inverse of {@link parse}.- *- * The multiplicity and the label type are always written out, falling back to the defaults their- * consumers assume (`single` and `text`) rather than to the empty token {@link parse} would reject.- *- * @param definition the definition to serialize.- * @param valueType whether the definition describes a label or a relation, which decides between- * writing a label type and writing an inverse relation.- */-function serialize(definition: DefinitionObject, valueType: "label" | "relation") {- const props: string[] = [];-- if (definition.isPromoted) {- props.push("promoted");-- if (definition.promotedAlias) {- props.push(`alias=${definition.promotedAlias}`);- }- }-- props.push(definition.multiplicity ?? "single");-- if (valueType === "label") {- const labelType = definition.labelType ?? "text";- props.push(labelType);-- // A precision is only meaningful for numbers, and only once it has been set.- if (labelType === "number" && definition.numberPrecision !== undefined) {- props.push(`precision=${definition.numberPrecision}`);- }- } else if (definition.inverseRelation?.trim()) {- props.push(`inverse=${filterAttributeName(definition.inverseRelation)}`);- }-- return props.join(",");-}--/**- * For an attribute definition name (e.g. `label:TEST:TEST1`), extracts its type (label) and name (TEST:TEST1).- * @param definitionAttrName the attribute definition name, without the leading `#` (e.g. `label:TEST:TEST1`)- * @return a tuple of [type, name].- */-export function extractAttributeDefinitionTypeAndName(definitionAttrName: string): [ "label" | "relation", string ] {- const valueType = definitionAttrName.startsWith("label:") ? "label" : "relation";- const valueName = definitionAttrName.substring(valueType.length + 1);- return [ valueType, valueName ];-}--export default {- parse,- serialize-};diff --git a/apps/client/src/services/utils.ts b/apps/client/src/services/utils.tsindex 725b46c2da..f58559468a 100644--- a/apps/client/src/services/utils.ts+++ b/apps/client/src/services/utils.ts@@ -1,4 +1,4 @@-import { dayjs } from "@triliumnext/commons";+import { dayjs, filterAttributeName, isValidAttributeName } from "@triliumnext/commons";import FNote from "../entities/fnote";import type { ViewMode, ViewScope } from "./link.js";@@ -493,16 +493,6 @@ export async function openInReusableSplit(targetNoteId: string, targetViewMode:}}-function filterAttributeName(name: string) {- return name.replace(/[^\p{L}\p{N}_:]/gu, "");-}--const ATTR_NAME_MATCHER = new RegExp("^[\\p{L}\\p{N}_:]+$", "u");--function isValidAttributeName(name: string) {- return ATTR_NAME_MATCHER.test(name);-}-function sleep(time_ms: number) {return new Promise((resolve) => {setTimeout(resolve, time_ms);diff --git a/apps/client/src/widgets/PromotedAttributes.tsx b/apps/client/src/widgets/PromotedAttributes.tsxindex ebf9f6eeb4..eb18099cb3 100644--- a/apps/client/src/widgets/PromotedAttributes.tsx+++ b/apps/client/src/widgets/PromotedAttributes.tsx@@ -1,6 +1,6 @@import "./PromotedAttributes.css";-import { DefinitionObject, LabelType, UpdateAttributeResponse } from "@triliumnext/commons";+import { DefinitionObject, extractAttributeDefinitionTypeAndName, LabelType, UpdateAttributeResponse } from "@triliumnext/commons";import clsx from "clsx";import { ComponentChild, createElement, HTMLInputTypeAttribute, InputHTMLAttributes, MouseEventHandler, TargetedEvent, TargetedInputEvent } from "preact";import { Dispatch, StateUpdater, useCallback, useEffect, useRef, useState } from "preact/hooks";@@ -11,7 +11,6 @@ import FNote from "../entities/fnote";import { Attribute } from "../services/attribute_parser";import attributes from "../services/attributes";import { t } from "../services/i18n";-import { extractAttributeDefinitionTypeAndName } from "../services/promoted_attribute_definition_parser";import server from "../services/server";import { randomString } from "../services/utils";import ws from "../services/ws";diff --git a/apps/client/src/widgets/attribute_widgets/attribute_detail.tsx b/apps/client/src/widgets/attribute_widgets/attribute_detail.tsxindex a61d9528af..e35114e9b8 100644--- a/apps/client/src/widgets/attribute_widgets/attribute_detail.tsx+++ b/apps/client/src/widgets/attribute_widgets/attribute_detail.tsx@@ -1,6 +1,6 @@import "./attribute_detail.css";-import type { DefinitionObject, LabelType } from "@triliumnext/commons";+import { type DefinitionObject, type LabelType, promotedAttributeDefinitionParser } from "@triliumnext/commons";import { ComponentProps } from "preact";import { useCallback, useContext, useEffect, useLayoutEffect, useRef, useState } from "preact/hooks";@@ -11,7 +11,6 @@ import { isExperimentalFeatureEnabled } from "../../services/experimental_featurimport { focusSavedElement, saveFocusedElement } from "../../services/focus.js";import froca from "../../services/froca.js";import { t } from "../../services/i18n.js";-import promotedAttributeDefinitionParser from "../../services/promoted_attribute_definition_parser.js";import server from "../../services/server.js";import { isIMEComposing } from "../../services/shortcuts.js";import utils from "../../services/utils.js";diff --git a/apps/client/src/widgets/collections/table/rows.ts b/apps/client/src/widgets/collections/table/rows.tsindex 55a19eae6c..75542010fc 100644--- a/apps/client/src/widgets/collections/table/rows.ts+++ b/apps/client/src/widgets/collections/table/rows.ts@@ -1,7 +1,6 @@-import { LabelType } from "@triliumnext/commons";+import { extractAttributeDefinitionTypeAndName, LabelType } from "@triliumnext/commons";import FNote from "../../../entities/fnote.js";-import { extractAttributeDefinitionTypeAndName } from "../../../services/promoted_attribute_definition_parser.js";import type { AttributeDefinitionInformation } from "./columns.js";export type TableData = {diff --git a/apps/client/src/widgets/sidebar/AttributeList.tsx b/apps/client/src/widgets/sidebar/AttributeList.tsxindex 7d6908662e..10bf3630b6 100644--- a/apps/client/src/widgets/sidebar/AttributeList.tsx+++ b/apps/client/src/widgets/sidebar/AttributeList.tsx@@ -1,5 +1,6 @@import "./AttributeList.css";+import { promotedAttributeDefinitionParser } from "@triliumnext/commons";import clsx from "clsx";import { createPortal } from "preact/compat";import { useContext, useEffect, useRef, useState } from "preact/hooks";@@ -10,7 +11,6 @@ import contextMenu from "../../menus/context_menu";import type { Attribute } from "../../services/attribute_parser";import attributes from "../../services/attributes";import { t } from "../../services/i18n";-import promotedAttributeDefinitionParser from "../../services/promoted_attribute_definition_parser";import server from "../../services/server";import { AttributeDetail, AttributeDetailOpts, AttrType, getAttrType, LABEL_TYPES } from "../attribute_widgets/attribute_detail";import ActionButton from "../react/ActionButton";diff --git a/packages/commons/src/index.ts b/packages/commons/src/index.tsindex f8991d1b91..908817c037 100644--- a/packages/commons/src/index.ts+++ b/packages/commons/src/index.ts@@ -12,6 +12,8 @@ export * from "./lib/shared_constants.js";export * from "./lib/shared_types.js";export * from "./lib/ws_api.js";export * from "./lib/attribute_names.js";+export * from "./lib/promoted_attribute_definition_parser.js";+export { default as promotedAttributeDefinitionParser } from "./lib/promoted_attribute_definition_parser.js";export * from "./lib/utils.js";export * from "./lib/dayjs.js";export * from "./lib/notes.js";diff --git a/packages/commons/src/lib/attribute_names.spec.ts b/packages/commons/src/lib/attribute_names.spec.tsnew file mode 100644index 0000000000..89184d8c93--- /dev/null+++ b/packages/commons/src/lib/attribute_names.spec.ts@@ -0,0 +1,52 @@+import { describe, expect, it } from "vitest";++import { filterAttributeName, isValidAttributeName } from "./attribute_names.js";++describe("filterAttributeName", () => {+ it("keeps only letters, numbers, underscore and colon", () => {+ expect(filterAttributeName("a b#c:d_1!")).toBe("abc:d_1");+ expect(filterAttributeName("valid_name:1")).toBe("valid_name:1");+ });++ it("keeps non-ASCII letters and numbers", () => {+ // The character set is expressed in Unicode property escapes, not [a-z].+ expect(filterAttributeName("étiquette")).toBe("étiquette");+ expect(filterAttributeName("日本語:名前")).toBe("日本語:名前");+ });++ it("can filter a name down to nothing", () => {+ expect(filterAttributeName("!@#$")).toBe("");+ expect(filterAttributeName("")).toBe("");+ });++ it("returns the same result when called repeatedly", () => {+ // The matcher is a module-level global regex, so a leaked `lastIndex` would make+ // successive calls disagree.+ expect(filterAttributeName("a b#c")).toBe("abc");+ expect(filterAttributeName("a b#c")).toBe("abc");+ expect(filterAttributeName("a b#c")).toBe("abc");+ });+});++describe("isValidAttributeName", () => {+ it("accepts a name made only of allowed characters", () => {+ expect(isValidAttributeName("valid_name:1")).toBe(true);+ expect(isValidAttributeName("étiquette")).toBe(true);+ });++ it("rejects disallowed characters and the empty name", () => {+ expect(isValidAttributeName("has space")).toBe(false);+ expect(isValidAttributeName("has#hash")).toBe(false);+ expect(isValidAttributeName("has-dash")).toBe(false);+ expect(isValidAttributeName("")).toBe(false);+ });++ it("agrees with filterAttributeName", () => {+ // Filtering yields a valid name whenever anything survives, which is what the callers+ // that filter-then-use rely on.+ for (const name of [ "a b#c:d_1!", "valid_name:1", "étiquette", "!@#$" ]) {+ const filtered = filterAttributeName(name);+ expect(isValidAttributeName(filtered)).toBe(filtered !== "");+ }+ });+});diff --git a/packages/commons/src/lib/attribute_names.ts b/packages/commons/src/lib/attribute_names.tsindex aa848c0bf7..7f72ae7fa2 100644--- a/packages/commons/src/lib/attribute_names.ts+++ b/packages/commons/src/lib/attribute_names.ts@@ -107,6 +107,29 @@ type Relations = [export type LabelNames = keyof Labels;export type RelationNames = Relations[number];+/**+ * The characters an attribute name may consist of: letters, numbers, underscore and colon. Kept as a+ * single source of truth so that {@link filterAttributeName} and {@link isValidAttributeName} cannot+ * drift apart.+ *+ * Note that {@link sanitizeAttributeName} in `trilium-core` deliberately applies the *same* character+ * set with different semantics (it substitutes an underscore and renames the empty string, rather than+ * stripping), so it is not expressed in terms of these helpers.+ */+const ATTRIBUTE_NAME_CHARS = "\\p{L}\\p{N}_:";+const DISALLOWED_MATCHER = new RegExp(`[^${ATTRIBUTE_NAME_CHARS}]`, "gu");+const ATTR_NAME_MATCHER = new RegExp(`^[${ATTRIBUTE_NAME_CHARS}]+$`, "u");++/** Strips every character an attribute name may not contain, returning a usable (possibly empty) name. */+export function filterAttributeName(name: string) {+ return name.replace(DISALLOWED_MATCHER, "");+}++/** Whether the name is a valid attribute name, i.e. non-empty and free of disallowed characters. */+export function isValidAttributeName(name: string) {+ return ATTR_NAME_MATCHER.test(name);+}+export type FilterLabelsByType<U> = {[K in keyof Labels]: Labels[K] extends U ? K : never;}[keyof Labels];diff --git a/packages/commons/src/lib/promoted_attribute_definition_parser.spec.ts b/packages/commons/src/lib/promoted_attribute_definition_parser.spec.tsnew file mode 100644index 0000000000..4b36bce1f0--- /dev/null+++ b/packages/commons/src/lib/promoted_attribute_definition_parser.spec.ts@@ -0,0 +1,172 @@+import { describe, expect, it, vi } from "vitest";++import parser, {+ extractAttributeDefinitionTypeAndName,+ LABEL_TYPES,+ MULTIPLICITIES+} from "./promoted_attribute_definition_parser.js";++const { parse, serialize } = parser;++/** Runs `fn` with `console.log` silenced, handing it the spy so logged tokens can be asserted. */+function withSilencedLog(fn: (logSpy: ReturnType<typeof vi.spyOn>) => void) {+ const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});+ try {+ fn(logSpy);+ } finally {+ logSpy.mockRestore();+ }+}++describe("promoted_attribute_definition_parser.parse", () => {+ it("parses the promoted flag, label type and multiplicity, trimming whitespace", () => {+ expect(parse("promoted")).toEqual({ isPromoted: true });+ expect(parse(" promoted , number , single ")).toEqual({+ isPromoted: true,+ labelType: "number",+ multiplicity: "single"+ });+ });++ it("accepts every declared label type and multiplicity", () => {+ // Driven off the exported constants so a newly declared type cannot be left unparsed.+ for (const labelType of LABEL_TYPES) {+ expect(parse(labelType)).toEqual({ labelType });+ }++ for (const multiplicity of MULTIPLICITIES) {+ expect(parse(multiplicity)).toEqual({ multiplicity });+ }+ });++ it("parses the precision, tolerating a malformed or missing one", () => {+ expect(parse("precision=2")).toEqual({ numberPrecision: 2 });+ expect(parse("precision=0")).toEqual({ numberPrecision: 0 });+ // parseInt tolerates trailing characters.+ expect(parse("precision=3px")).toEqual({ numberPrecision: 3 });+ // A missing value yields NaN rather than throwing.+ expect(parse("precision")).toEqual({ numberPrecision: NaN });+ });++ it("parses the promoted alias verbatim, including spaces", () => {+ expect(parse("alias=My Label")).toEqual({ promotedAlias: "My Label" });+ expect(parse("alias=")).toEqual({ promotedAlias: "" });+ // A missing value yields undefined rather than throwing.+ expect(parse("alias")).toEqual({ promotedAlias: undefined });+ });++ it("keeps everything after the first '=' as the value", () => {+ // Splitting on every '=' would truncate these at the second separator.+ expect(parse("alias=a=b")).toEqual({ promotedAlias: "a=b" });+ expect(parse("alias====")).toEqual({ promotedAlias: "===" });+ });++ it("parses the inverse relation, stripping characters a relation name may not hold", () => {+ // Allowed: letters, numbers, underscore and colon.+ expect(parse("inverse=isParentOf")).toEqual({ inverseRelation: "isParentOf" });+ expect(parse("inverse=is:parent_of2")).toEqual({ inverseRelation: "is:parent_of2" });+ // Disallowed characters (spaces, punctuation, dashes) are removed.+ expect(parse("inverse=is parent-of!")).toEqual({ inverseRelation: "isparentof" });+ // A missing value yields an empty name rather than throwing.+ expect(parse("inverse")).toEqual({ inverseRelation: "" });+ });++ it("combines multiple tokens, letting a later token of the same kind win", () => {+ expect(parse("promoted,single,text,precision=4,alias=Foo")).toEqual({+ isPromoted: true,+ multiplicity: "single",+ labelType: "text",+ numberPrecision: 4,+ promotedAlias: "Foo"+ });++ expect(parse("text,number")).toEqual({ labelType: "number" });+ expect(parse("single,multi")).toEqual({ multiplicity: "multi" });+ });++ it("logs and skips an unrecognized token while still parsing the valid ones", () => {+ withSilencedLog((logSpy) => {+ expect(parse("bogus,promoted")).toEqual({ isPromoted: true });+ expect(logSpy).toHaveBeenCalledWith(+ "Unrecognized attribute definition token:", "bogus"+ );+ });+ });++ it("returns an empty definition for an empty value, and tolerates a trailing separator", () => {+ withSilencedLog(() => {+ // An empty string splits into a single empty token, which is unrecognized.+ expect(parse("")).toEqual({});+ expect(parse("promoted,")).toEqual({ isPromoted: true });+ });+ });+});++describe("promoted_attribute_definition_parser.serialize", () => {+ it("writes the promoted flag and its alias, the alias only when promoted", () => {+ expect(serialize({ isPromoted: true, promotedAlias: "Foo" }, "label"))+ .toBe("promoted,alias=Foo,single,text");++ // An alias is meaningless without the flag, so it is left out.+ expect(serialize({ promotedAlias: "Foo" }, "label")).toBe("single,text");+ });++ it("falls back to the multiplicity and label type the consumers assume", () => {+ expect(serialize({}, "label")).toBe("single,text");+ expect(serialize({}, "relation")).toBe("single");+ expect(serialize({ multiplicity: "multi", labelType: "boolean" }, "label"))+ .toBe("multi,boolean");+ });++ it("writes the precision only for a number with one set", () => {+ expect(serialize({ labelType: "number", numberPrecision: 2 }, "label"))+ .toBe("single,number,precision=2");+ expect(serialize({ labelType: "number" }, "label")).toBe("single,number");+ expect(serialize({ labelType: "text", numberPrecision: 2 }, "label")).toBe("single,text");+ // Zero digits is a precision like any other.+ expect(serialize({ labelType: "number", numberPrecision: 0 }, "label"))+ .toBe("single,number,precision=0");+ });++ it("writes the inverse relation for relations only, filtering invalid characters", () => {+ expect(serialize({ inverseRelation: "isChildOf" }, "relation"))+ .toBe("single,inverse=isChildOf");+ expect(serialize({ inverseRelation: "is child#Of!" }, "relation"))+ .toBe("single,inverse=ischildOf");++ // A blank name is dropped, and a label definition has no inverse to write.+ expect(serialize({ inverseRelation: " " }, "relation")).toBe("single");+ expect(serialize({ inverseRelation: "isChildOf" }, "label")).toBe("single,text");+ });+});++describe("promoted_attribute_definition_parser round-trip", () => {+ it("serializes a parsed definition back to the same value", () => {+ const labelDefinition = "promoted,alias=Foo,multi,number,precision=2";+ expect(serialize(parse(labelDefinition), "label")).toBe(labelDefinition);++ const relationDefinition = "promoted,single,inverse=isChildOf";+ expect(serialize(parse(relationDefinition), "relation")).toBe(relationDefinition);+ });++ it("parses a serialized definition back to the same object, for every label type", () => {+ for (const labelType of LABEL_TYPES) {+ const definition = {+ isPromoted: true, promotedAlias: "Foo", multiplicity: "multi", labelType+ } as const;+ expect(parse(serialize(definition, "label"))).toEqual(definition);+ }+ });+});++describe("extractAttributeDefinitionTypeAndName", () => {+ it("extracts the label type and strips the prefix, keeping colons in the name", () => {+ expect(extractAttributeDefinitionTypeAndName("label:TEST:TEST1"))+ .toEqual([ "label", "TEST:TEST1" ]);+ });++ it("treats anything not starting with label: as a relation", () => {+ expect(extractAttributeDefinitionTypeAndName("relation:author"))+ .toEqual([ "relation", "author" ]);+ });+});diff --git a/packages/commons/src/lib/promoted_attribute_definition_parser.ts b/packages/commons/src/lib/promoted_attribute_definition_parser.tsnew file mode 100644index 0000000000..37c814bb96--- /dev/null+++ b/packages/commons/src/lib/promoted_attribute_definition_parser.ts@@ -0,0 +1,143 @@+import { filterAttributeName } from "./attribute_names.js";++/**+ * Every label type a promoted attribute definition may declare, in the order they are offered to+ * the user. This is the runtime source of truth: {@link LabelType} is derived from it, so a new+ * type cannot be added to the union without {@link parse} also accepting it.+ */+export const LABEL_TYPES = [+ "text", "textarea", "number", "boolean", "date", "datetime", "time", "url", "color"+] as const;++export type LabelType = typeof LABEL_TYPES[number];++export const MULTIPLICITIES = [ "single", "multi" ] as const;++export type Multiplicity = typeof MULTIPLICITIES[number];++export interface DefinitionObject {+ isPromoted?: boolean;+ labelType?: LabelType;+ multiplicity?: Multiplicity;+ numberPrecision?: number;+ promotedAlias?: string;+ inverseRelation?: string;+}++/**+ * Parses the comma-separated form a definition is stored in, e.g.+ * `promoted,alias=Foo,single,number,precision=2`.+ *+ * Tokens are matched leniently: whitespace around them is trimmed, a later token of the same kind+ * wins over an earlier one, and an unrecognized token is logged and skipped rather than throwing,+ * so a definition written by a newer version degrades to its recognized parts instead of being+ * lost.+ *+ * @param value the raw attribute value of a `label:`/`relation:` definition attribute.+ */+function parse(value: string): DefinitionObject {+ const tokens = value.split(",").map((t) => t.trim());+ const defObj: DefinitionObject = {};++ for (const token of tokens) {+ if (token === "promoted") {+ defObj.isPromoted = true;+ } else if (isLabelType(token)) {+ defObj.labelType = token;+ } else if (isMultiplicity(token)) {+ defObj.multiplicity = token;+ } else if (token.startsWith("precision")) {+ // A missing value parses to NaN, which the consumers treat as "no precision set".+ defObj.numberPrecision = parseInt(parameterValue(token) ?? "");+ } else if (token.startsWith("alias")) {+ defObj.promotedAlias = parameterValue(token);+ } else if (token.startsWith("inverse")) {+ // An inverse relation is a relation name, so the same characters are dropped as when+ // one is written by `serialize`. Definitions reaching us from an import, ETAPI or a+ // hand-typed attribute are not otherwise guaranteed to hold a usable name.+ defObj.inverseRelation = filterAttributeName(parameterValue(token) ?? "");+ } else {+ console.log("Unrecognized attribute definition token:", token);+ }+ }++ return defObj;+}++/**+ * Serializes a definition back into the comma separated form stored in the attribute value, e.g.+ * `promoted,alias=Foo,single,number,precision=2`. The inverse of {@link parse}.+ *+ * The multiplicity and the label type are always written out, falling back to the defaults their+ * consumers assume (`single` and `text`) rather than to the empty token {@link parse} would reject.+ *+ * @param definition the definition to serialize.+ * @param valueType whether the definition describes a label or a relation, which decides between+ * writing a label type and writing an inverse relation.+ */+function serialize(definition: DefinitionObject, valueType: "label" | "relation") {+ const props: string[] = [];++ if (definition.isPromoted) {+ props.push("promoted");++ if (definition.promotedAlias) {+ props.push(`alias=${definition.promotedAlias}`);+ }+ }++ props.push(definition.multiplicity ?? "single");++ if (valueType === "label") {+ const labelType = definition.labelType ?? "text";+ props.push(labelType);++ // A precision is only meaningful for numbers, and only once it has been set.+ if (labelType === "number" && definition.numberPrecision !== undefined) {+ props.push(`precision=${definition.numberPrecision}`);+ }+ } else if (definition.inverseRelation?.trim()) {+ props.push(`inverse=${filterAttributeName(definition.inverseRelation)}`);+ }++ return props.join(",");+}++/**+ * For an attribute definition name (e.g. `label:TEST:TEST1`), extracts its type (label) and name+ * (TEST:TEST1).+ * @param definitionAttrName the attribute definition name, without the leading `#`+ * (e.g. `label:TEST:TEST1`)+ * @return a tuple of [type, name].+ */+export function extractAttributeDefinitionTypeAndName(+ definitionAttrName: string+): [ "label" | "relation", string ] {+ const valueType = definitionAttrName.startsWith("label:") ? "label" : "relation";+ const valueName = definitionAttrName.substring(valueType.length + 1);+ return [ valueType, valueName ];+}++/**+ * Reads the value out of a `key=value` token, or `undefined` when the token carries no `=` at all.+ *+ * Only the first `=` separates the two: a value may legitimately contain one (an alias such as+ * `alias=a=b`), and splitting on every occurrence would silently truncate it at the second.+ */+function parameterValue(token: string): string | undefined {+ const separatorIndex = token.indexOf("=");+ return separatorIndex < 0 ? undefined : token.substring(separatorIndex + 1);+}++function isLabelType(token: string): token is LabelType {+ return (LABEL_TYPES as readonly string[]).includes(token);+}++function isMultiplicity(token: string): token is Multiplicity {+ return (MULTIPLICITIES as readonly string[]).includes(token);+}++export default {+ parse,+ serialize+};diff --git a/packages/commons/src/lib/server_api.ts b/packages/commons/src/lib/server_api.tsindex ff98a71750..23ad0fd672 100644--- a/packages/commons/src/lib/server_api.ts+++ b/packages/commons/src/lib/server_api.ts@@ -369,18 +369,6 @@ export interface IconRegistry {}[];}-export type LabelType = "text" | "textarea" | "number" | "boolean" | "date" | "datetime" | "time" | "url" | "color";-export type Multiplicity = "single" | "multi";--export interface DefinitionObject {- isPromoted?: boolean;- labelType?: LabelType;- multiplicity?: Multiplicity;- numberPrecision?: number;- promotedAlias?: string;- inverseRelation?: string;-}-/*** Bootstrap items that the client needs to start up. These are sent by the server in the HTML and made available as `window.glob`.*/diff --git a/packages/trilium-core/src/becca/entities/battribute.ts b/packages/trilium-core/src/becca/entities/battribute.tsindex 48c5283360..8b287bbcab 100644--- a/packages/trilium-core/src/becca/entities/battribute.ts+++ b/packages/trilium-core/src/becca/entities/battribute.ts@@ -3,7 +3,7 @@import BNote from "./bnote.js";import AbstractBeccaEntity from "./abstract_becca_entity.js";import dateUtils from "../../services/utils/date";-import promotedAttributeDefinitionParser from "../../services/promoted_attribute_definition_parser.js";+import { promotedAttributeDefinitionParser } from "@triliumnext/commons";import type { AttributeRow, AttributeType } from "@triliumnext/commons";import { normalize, sanitizeAttributeName } from "../../services/utils/index.js";diff --git a/packages/trilium-core/src/services/promoted_attribute_definition_parser.spec.ts b/packages/trilium-core/src/services/promoted_attribute_definition_parser.spec.tsdeleted file mode 100644index 0423b4ad51..0000000000--- a/packages/trilium-core/src/services/promoted_attribute_definition_parser.spec.ts+++ /dev/null@@ -1,88 +0,0 @@-import { describe, expect, it, vi } from "vitest";-import promotedAttributeDefinitionParser from "./promoted_attribute_definition_parser.js";--const { parse } = promotedAttributeDefinitionParser;--describe("promoted attribute definition parser", () => {- it("parses the 'promoted' flag", () => {- expect(parse("promoted")).toEqual({ isPromoted: true });- });-- it("parses every recognized label type", () => {- for (const labelType of ["text", "textarea", "number", "boolean", "date", "datetime", "time", "url", "color"]) {- expect(parse(labelType)).toEqual({ labelType });- }- });-- it("parses both multiplicity values", () => {- expect(parse("single")).toEqual({ multiplicity: "single" });- expect(parse("multi")).toEqual({ multiplicity: "multi" });- });-- it("parses numeric precision and yields NaN when it is missing or malformed", () => {- expect(parse("precision=2")).toEqual({ numberPrecision: 2 });- // parseInt tolerates trailing characters.- expect(parse("precision=3px")).toEqual({ numberPrecision: 3 });- // Missing value -> parseInt(undefined) -> NaN.- expect(parse("precision")).toEqual({ numberPrecision: NaN });- });-- it("parses the promoted alias verbatim", () => {- expect(parse("alias=My Label")).toEqual({ promotedAlias: "My Label" });- // Missing value yields undefined rather than throwing.- expect(parse("alias")).toEqual({ promotedAlias: undefined });- });-- it("parses the inverse relation and strips disallowed characters", () => {- // Allowed: letters, numbers, underscore and colon.- expect(parse("inverse=isParentOf")).toEqual({ inverseRelation: "isParentOf" });- expect(parse("inverse=is:parent_of2")).toEqual({ inverseRelation: "is:parent_of2" });- // Disallowed characters (spaces, punctuation, dashes) are removed.- expect(parse("inverse=is parent-of!")).toEqual({ inverseRelation: "isparentof" });- });-- it("combines multiple comma-separated tokens into one definition", () => {- expect(parse("promoted,single,text,precision=4,alias=Foo")).toEqual({- isPromoted: true,- multiplicity: "single",- labelType: "text",- numberPrecision: 4,- promotedAlias: "Foo"- });- });-- it("trims surrounding whitespace from each token", () => {- expect(parse(" promoted , number , precision=1 ")).toEqual({- isPromoted: true,- labelType: "number",- numberPrecision: 1- });- });-- it("lets later tokens of the same kind override earlier ones", () => {- expect(parse("text,number")).toEqual({ labelType: "number" });- expect(parse("single,multi")).toEqual({ multiplicity: "multi" });- });-- it("ignores unrecognized tokens (and logs them) while still parsing valid ones", () => {- const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});- try {- expect(parse("bogus,promoted")).toEqual({ isPromoted: true });- expect(logSpy).toHaveBeenCalledWith("Unrecognized attribute definition token:", "bogus");- } finally {- logSpy.mockRestore();- }- });-- it("returns an empty definition for an empty string and ignores empty tokens", () => {- const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});- try {- // An empty string splits into a single empty token, which is unrecognized.- expect(parse("")).toEqual({});- // Trailing comma produces an extra empty token that is ignored.- expect(parse("promoted,")).toEqual({ isPromoted: true });- } finally {- logSpy.mockRestore();- }- });-});diff --git a/packages/trilium-core/src/services/promoted_attribute_definition_parser.ts b/packages/trilium-core/src/services/promoted_attribute_definition_parser.tsdeleted file mode 100644index 9d4d55b9db..0000000000--- a/packages/trilium-core/src/services/promoted_attribute_definition_parser.ts+++ /dev/null@@ -1,36 +0,0 @@-import { DefinitionObject, LabelType, Multiplicity } from "@triliumnext/commons";--function parse(value: string): DefinitionObject {- const tokens = value.split(",").map((t) => t.trim());- const defObj: DefinitionObject = {};-- for (const token of tokens) {- if (token === "promoted") {- defObj.isPromoted = true;- } else if (["text", "textarea", "number", "boolean", "date", "datetime", "time", "url", "color"].includes(token)) {- defObj.labelType = token as LabelType;- } else if (["single", "multi"].includes(token)) {- defObj.multiplicity = token as Multiplicity;- } else if (token.startsWith("precision")) {- const chunks = token.split("=");-- defObj.numberPrecision = parseInt(chunks[1]);- } else if (token.startsWith("alias")) {- const chunks = token.split("=");-- defObj.promotedAlias = chunks[1];- } else if (token.startsWith("inverse")) {- const chunks = token.split("=");-- defObj.inverseRelation = chunks[1].replace(/[^\p{L}\p{N}_:]/gu, "");- } else {- console.log("Unrecognized attribute definition token:", token);- }- }-- return defObj;-}--export default {- parse-};