Skip to content

Build your personal knowledge base with Trilium Notes

feat(codemirror/autocomplete): improve typings for Preact & backend scripting

Elian Doran706319673e01
diff --git a/apps/script-deployer/src/trilium-env.d.ts b/apps/script-deployer/src/trilium-env.d.ts
index 6d8249ea37..674c3dc8e4 100644
--- a/apps/script-deployer/src/trilium-env.d.ts
+++ b/apps/script-deployer/src/trilium-env.d.ts
@@ -115,4 +115,4 @@ declare module "trilium:preact" {
* Trilium injects this as a global.
*/
// eslint-disable-next-line no-var
-declare var api: import("@triliumnext/server/src/services/backend_script_api").Api;
+declare var api: import("@triliumnext/commons/src/lib/script_api").BackendApi;
diff --git a/packages/codemirror/src/type_completion/backend_api.ts b/packages/codemirror/src/type_completion/backend_api.ts
deleted file mode 100644
index d6381bf3ca..0000000000
--- a/packages/codemirror/src/type_completion/backend_api.ts
+++ /dev/null
@@ -1,139 +0,0 @@
-/**
- * Ambient type definitions fed to the TypeScript language service when editing
- * a **backend** script note (`application/javascript;env=backend`).
- *
- * Hand-curated subset of the real `Api` interface declared in
- * `packages/trilium-core/src/services/backend_script_api.ts`. Standalone `.d.ts`
- * (no imports) for the same reason as the frontend stub.
- *
- * Follow-up (see PoC notes): auto-generate from the live source at build time.
- */
-export default /* ts */ `
-interface BAttribute {
- attributeId: string;
- type: "label" | "relation";
- name: string;
- value: string;
- isInheritable: boolean;
-}
-
-interface BNote {
- noteId: string;
- title: string;
- type: string;
- mime: string;
- isProtected: boolean;
- getContent(): string | Buffer;
- setContent(content: string | Buffer, opts?: { forceSave?: boolean }): void;
- getParentNotes(): BNote[];
- getChildNotes(): BNote[];
- getAttributes(type?: string, name?: string): BAttribute[];
- getOwnedAttributes(type?: string, name?: string): BAttribute[];
- getLabelValue(name: string): string | null;
- hasLabel(name: string): boolean;
- setLabel(name: string, value?: string): BAttribute;
- setRelation(name: string, targetNoteId: string): BAttribute;
- getRelationTarget(name: string): BNote | null;
-}
-
-interface BBranch {
- branchId: string;
- noteId: string;
- parentNoteId: string;
- prefix: string | null;
- notePosition: number;
- isExpanded: boolean;
-}
-
-interface CreateNoteResult {
- note: BNote;
- branch: BBranch;
-}
-
-/** Trilium backend script API, exposed to "JS backend" code notes as the global \`api\`. */
-interface BackendApi {
- /** Note where the script started executing (the event entrypoint). */
- startNote: BNote;
- /** Note where the script is currently executing. */
- currentNote: BNote;
- /** Entity whose event triggered this execution (or null). */
- originEntity: unknown | null;
-
- /** day.js instance for date manipulation. */
- dayjs: (date?: string | number | Date) => { format(template: string): string };
- /** axios HTTP client. */
- axios: unknown;
- /** cheerio HTML parser. */
- cheerio: unknown;
-
- /** Returns a note by its ID, or null. */
- getNote(noteId: string): BNote | null;
- /** Returns a branch by its ID, or null. */
- getBranch(branchId: string): BBranch | null;
- /** Returns an attribute by its ID, or null. */
- getAttribute(attributeId: string): BAttribute | null;
-
- /** Powerful attribute/value search, e.g. "#dateModified =* MONTH AND #log". */
- searchForNotes(searchString: string, params?: Record<string, unknown>): BNote[];
- /** Returns the first note matching the search, or null. */
- searchForNote(searchString: string, params?: Record<string, unknown>): BNote | null;
- /** Returns all notes carrying the given label. */
- getNotesWithLabel(name: string, value?: string): BNote[];
- /** Returns the first note carrying the given label, or null. */
- getNoteWithLabel(name: string, value?: string): BNote | null;
-
- /** Creates a new note under the given parent. */
- createNewNote(params: {
- parentNoteId: string;
- title: string;
- content: string | Buffer;
- type: string;
- mime?: string;
- }): CreateNoteResult;
- /** Convenience: create a text note. */
- createTextNote(parentNoteId: string, title: string, content: string): CreateNoteResult;
- /** Convenience: create a data (JSON) note. */
- createDataNote(parentNoteId: string, title: string, content: object): CreateNoteResult;
-
- /** Calendar helpers. */
- getDayNote(date: string, rootNote?: BNote): BNote;
- getTodayNote(rootNote?: BNote): BNote;
- getWeekNote(date: string, rootNote?: BNote): BNote;
- getMonthNote(month: string, rootNote?: BNote): BNote;
- getYearNote(year: string, rootNote?: BNote): BNote;
- getRootCalendarNote(): BNote;
-
- /** Reads an option value. */
- getOption(name: string): string;
- /** Reads all options. */
- getOptions(): Record<string, string>;
- /** Application info (version, build date, etc.). */
- getAppInfo(): Record<string, unknown>;
-
- /** Runs the given function inside a transaction. */
- transactional<T>(func: () => T): T;
- /** Runs the given function on the frontend of all connected clients. */
- runOnFrontend(func: (...args: unknown[]) => unknown, params?: unknown[]): Promise<unknown>;
- /** Triggers a full backup immediately. */
- backupNow(backupName: string): Promise<string>;
-
- /** Writes a line to the script log. */
- log(message: string): void;
- /** Generates a random alphanumeric string of the given length. */
- randomString(length: number): string;
- /** Escapes the given HTML string. */
- escapeHtml(html: string): string;
- /** Unescapes the given HTML string. */
- unescapeHtml(html: string): string;
-
- /** Low-level SQL access. */
- sql: {
- getRow<T>(query: string, params?: unknown[]): T;
- getRows<T>(query: string, params?: unknown[]): T[];
- getValue<T>(query: string, params?: unknown[]): T;
- execute(query: string, params?: unknown[]): unknown;
- };
-}
-
-declare const api: BackendApi;
-`;
diff --git a/packages/codemirror/src/type_completion/index.spec.ts b/packages/codemirror/src/type_completion/index.spec.ts
index b511f4cd25..33b467a0ca 100644
--- a/packages/codemirror/src/type_completion/index.spec.ts
+++ b/packages/codemirror/src/type_completion/index.spec.ts
@@ -1,12 +1,18 @@
import { describe, expect, it } from "vitest";
-import { getScriptDiagnosticCodes, SCRIPT_MIME_BACKEND, SCRIPT_MIME_FRONTEND, SCRIPT_MIME_JSX } from "./index.js";
+import { getScriptCompletions, getScriptDiagnosticCodes, SCRIPT_MIME_BACKEND, SCRIPT_MIME_FRONTEND, SCRIPT_MIME_JSX } from "./index.js";
+
+/** Returns completions at the `|` marker in `source` (the marker is stripped). */
+function completionsAtMarker(mime: string, source: string) {
+ const offset = source.indexOf("|");
+ return getScriptCompletions(mime, source.replace("|", ""), offset);
+}
/** "Property 'x' does not exist on type 'y'." */
const TS_UNKNOWN_PROPERTY = 2339;
/** "Argument of type 'x' is not assignable to parameter of type 'y'." */
const TS_ARGUMENT_NOT_ASSIGNABLE = 2345;
-/** "Type 'x' is not assignable to type 'y'." */
+/** "Type 'x' is not assignable to type 'y'." (also raised for a missing required JSX prop) */
const TS_TYPE_NOT_ASSIGNABLE = 2322;
/** "'await' expressions are only allowed at the top level of a file when that file is a module…" */
const TS_TOP_LEVEL_AWAIT = 1375;
@@ -161,3 +167,77 @@ describe("script note diagnostics", () => {
expect(codes).toContain(TS_UNKNOWN_PROPERTY);
}, TIMEOUT);
});
+
+describe("JSX autocompletion", () => {
+ it("offers intrinsic element names while typing a tag", async () => {
+ // A bare `<` is ambiguous (less-than operator); completing within an actual
+ // tag name puts the parser unambiguously in JSX-element context.
+ const names = await completionsAtMarker(SCRIPT_MIME_JSX, "const el = <div|></div>;");
+ expect(names).toContain("div");
+ expect(names).toContain("span");
+ expect(names).toContain("button");
+ }, TIMEOUT);
+
+ it("offers element attribute names inside an opening tag", async () => {
+ const names = await completionsAtMarker(SCRIPT_MIME_JSX, "const el = <div |></div>;");
+ expect(names).toContain("className");
+ expect(names).toContain("tabIndex");
+ expect(names).toContain("onClick");
+ }, TIMEOUT);
+
+ it("offers api members inside JSX expressions", async () => {
+ const names = await completionsAtMarker(
+ SCRIPT_MIME_JSX,
+ "const title = api.|;\nconst el = <div/>;"
+ );
+ expect(names).toContain("showMessage");
+ expect(names).toContain("getNote");
+ }, TIMEOUT);
+
+ it("offers a trilium:preact component's own prop names", async () => {
+ const names = await completionsAtMarker(
+ SCRIPT_MIME_JSX,
+ "import { Admonition } from \"trilium:preact\";\nconst el = <Admonition |>x</Admonition>;"
+ );
+ expect(names).toContain("type");
+ expect(names).toContain("className");
+ }, TIMEOUT);
+
+ it("offers a component prop's literal values", async () => {
+ // Admonition's `type` is a union — completing the value offers the members.
+ const names = await completionsAtMarker(
+ SCRIPT_MIME_JSX,
+ "import { Admonition } from \"trilium:preact\";\nconst el = <Admonition type=\"|\">x</Admonition>;"
+ );
+ expect(names).toContain("warning");
+ expect(names).toContain("note");
+ expect(names).toContain("caution");
+ }, TIMEOUT);
+});
+
+describe("JSX component typing", () => {
+ it("accepts valid component props", async () => {
+ const codes = await getScriptDiagnosticCodes(
+ SCRIPT_MIME_JSX,
+ "import { Admonition } from \"trilium:preact\";\nexport default () => <Admonition type=\"note\">hi</Admonition>;"
+ );
+ expect(codes).toEqual([]);
+ }, TIMEOUT);
+
+ it("rejects an invalid component prop value (real prop types, not any)", async () => {
+ const codes = await getScriptDiagnosticCodes(
+ SCRIPT_MIME_JSX,
+ "import { Admonition } from \"trilium:preact\";\nexport default () => <Admonition type=\"bogus\">hi</Admonition>;"
+ );
+ expect(codes).toContain(TS_TYPE_NOT_ASSIGNABLE);
+ }, TIMEOUT);
+
+ it("flags a missing required component prop", async () => {
+ // `Admonition` requires `type`; omitting it must error.
+ const codes = await getScriptDiagnosticCodes(
+ SCRIPT_MIME_JSX,
+ "import { Admonition } from \"trilium:preact\";\nexport default () => <Admonition>hi</Admonition>;"
+ );
+ expect(codes).toContain(TS_TYPE_NOT_ASSIGNABLE);
+ }, TIMEOUT);
+});
diff --git a/packages/codemirror/src/type_completion/index.ts b/packages/codemirror/src/type_completion/index.ts
index 29196dabab..a3d16a29d5 100644
--- a/packages/codemirror/src/type_completion/index.ts
+++ b/packages/codemirror/src/type_completion/index.ts
@@ -1,8 +1,6 @@
import type { CompletionSource } from "@codemirror/autocomplete";
import type { Extension } from "@codemirror/state";
-import backendApiDts from "./backend_api.js";
-
/**
* Full IntelliSense for backend/frontend script notes.
*
@@ -104,8 +102,12 @@ async function createEnv(mime: string) {
fsMap.set(JQUERY_DTS_PATH, jqueryGlobals);
rootFiles.push(JQUERY_DTS_PATH);
} else {
- // Backend still uses the curated stub (migrating to the shared module next).
- fsMap.set(API_GLOBALS_PATH, backendApiDts);
+ // Backend `api` types come from the same shared public surface in commons
+ // (single source of truth, drift-guarded). No jQuery/DOM server-side.
+ const apiTypes = (await import("../../../commons/src/lib/script_api.ts?raw")).default;
+ fsMap.set(API_TYPES_PATH, apiTypes);
+ fsMap.set(API_GLOBALS_PATH, `import type { BackendApi } from "./trilium-script-api";\ndeclare global {\n // eslint-disable-next-line no-var\n var api: BackendApi;\n}\n`);
+ rootFiles.push(API_TYPES_PATH);
}
if (mime === SCRIPT_MIME_JSX) {
@@ -221,3 +223,18 @@ export async function getScriptDiagnosticCodes(mime: string, code: string): Prom
.map((d) => d.code)
.filter((code) => !ignored.includes(code));
}
+
+/**
+ * Returns the completion entry names the language service offers at `offset` in
+ * `code` for the given script MIME type — the same `getCompletionsAtPosition`
+ * call that backs the editor's `tsAutocomplete()` source. Intended for tests
+ * asserting which completions (api members, JSX elements/attributes, …) are
+ * surfaced.
+ */
+export async function getScriptCompletions(mime: string, code: string, offset: number): Promise<string[]> {
+ const env = await createEnv(mime);
+ const path = scriptPath(mime);
+ env.updateFile(path, code.length ? code : " ");
+ const completions = env.languageService.getCompletionsAtPosition(path, offset, {});
+ return completions?.entries.map((entry) => entry.name) ?? [];
+}
diff --git a/packages/codemirror/src/type_completion/preact_types.ts b/packages/codemirror/src/type_completion/preact_types.ts
index 68bab5adb5..e0518aac2d 100644
--- a/packages/codemirror/src/type_completion/preact_types.ts
+++ b/packages/codemirror/src/type_completion/preact_types.ts
@@ -51,17 +51,24 @@ export const preactVfsFiles: Record<string, string> = {
*
* - `trilium:preact` mirrors the runtime `api.preact` surface: it re-exports
* Preact core + all hooks, plus Trilium's `defineWidget`/`defineLauncherWidget`
- * and the bundled UI components. The heavy components drag in the whole client
- * widget graph, so (matching `script_api.ts`'s philosophy) they're typed as a
- * loose `ComponentType<any>` rather than their real prop types.
+ * and the bundled UI components with curated prop types. Following
+ * `script_api.ts`'s philosophy, the genuinely useful props (enums, flags,
+ * callbacks) are typed precisely while references into the heavy client widget
+ * graph (editor instances, bootstrap options, note view scopes, …) are
+ * loosened to `unknown`/`Record` rather than dragging in their real types.
* - `trilium:api` exposes the same object as the `api` global.
*/
export const triliumModulesDts = `
declare module "trilium:preact" {
- import type { ComponentType, VNode } from "preact";
+ import type { ComponentChild, ComponentChildren, FunctionComponent, RefObject, VNode } from "preact";
export * from "preact";
export * from "preact/hooks";
+ /** A CSS style object (loose: property names are not validated). */
+ type Css = Record<string, string | number>;
+ /** A Trilium command name (loosened from the client's \`CommandNames\` union). */
+ type Cmd = string;
+
export interface WidgetDefinition {
parent: "right-pane";
render: () => VNode;
@@ -70,34 +77,344 @@ declare module "trilium:preact" {
export function defineWidget(definition: WidgetDefinition): WidgetDefinition & { type: "preact-widget" };
export function defineLauncherWidget(definition: { render: () => VNode }): { type: "preact-launcher-widget"; render: () => VNode };
- export const ActionButton: ComponentType<any>;
- export const Admonition: ComponentType<any>;
- export const Button: ComponentType<any>;
- export const CKEditor: ComponentType<any>;
- export const Collapsible: ComponentType<any>;
- export const Dropdown: ComponentType<any>;
- export const FormCheckbox: ComponentType<any>;
- export const FormDropdownList: ComponentType<any>;
- export const FormFileUploadButton: ComponentType<any>;
- export const FormFileUploadActionButton: ComponentType<any>;
- export const FormGroup: ComponentType<any>;
- export const FormListItem: ComponentType<any>;
- export const FormDropdownDivider: ComponentType<any>;
- export const FormDropdownSubmenu: ComponentType<any>;
- export const FormRadioGroup: ComponentType<any>;
- export const FormText: ComponentType<any>;
- export const FormTextArea: ComponentType<any>;
- export const FormTextBox: ComponentType<any>;
- export const FormToggle: ComponentType<any>;
- export const Icon: ComponentType<any>;
- export const LinkButton: ComponentType<any>;
- export const LoadingSpinner: ComponentType<any>;
- export const Modal: ComponentType<any>;
- export const NoteAutocomplete: ComponentType<any>;
- export const NoteLink: ComponentType<any>;
- export const RawHtml: ComponentType<any>;
- export const Slider: ComponentType<any>;
- export const RightPanelWidget: ComponentType<any>;
+ export interface ActionButtonProps {
+ text: string;
+ icon: string;
+ className?: string;
+ titlePosition?: "top" | "right" | "bottom" | "left";
+ triggerCommand?: Cmd;
+ noIconActionClass?: boolean;
+ frame?: boolean;
+ active?: boolean;
+ disabled?: boolean;
+ onClick?: (e: MouseEvent) => void;
+ onAuxClick?: (e: MouseEvent) => void;
+ onContextMenu?: (e: MouseEvent) => void;
+ style?: Css;
+ }
+ export const ActionButton: FunctionComponent<ActionButtonProps>;
+
+ export interface AdmonitionProps {
+ type: "warning" | "note" | "caution";
+ children?: ComponentChildren;
+ className?: string;
+ style?: Css;
+ }
+ export const Admonition: FunctionComponent<AdmonitionProps>;
+
+ export interface ButtonProps {
+ text: string;
+ name?: string;
+ buttonRef?: RefObject<HTMLButtonElement>;
+ className?: string;
+ icon?: string;
+ keyboardShortcut?: string;
+ onClick?: () => void;
+ kind?: "primary" | "secondary" | "lowProfile";
+ disabled?: boolean;
+ size?: "normal" | "small" | "micro";
+ style?: Css;
+ triggerCommand?: Cmd;
+ title?: string;
+ }
+ export const Button: FunctionComponent<ButtonProps>;
+
+ export interface CKEditorApi {
+ focus(): void;
+ setText(text: string): void;
+ }
+ export interface CKEditorProps {
+ apiRef: RefObject<CKEditorApi | undefined>;
+ currentValue?: string;
+ className: string;
+ tabIndex?: number;
+ config: unknown;
+ editor: unknown;
+ disableNewlines?: boolean;
+ disableSpellcheck?: boolean;
+ onChange?: (newValue?: string) => void;
+ onClick?: (e: MouseEvent, pos?: unknown) => void;
+ onKeyDown?: (e: KeyboardEvent) => void;
+ onBlur?: () => void;
+ onInitialized?: (editorInstance: unknown) => void;
+ }
+ export const CKEditor: FunctionComponent<CKEditorProps>;
+
+ export interface CollapsibleProps {
+ title: string;
+ children?: ComponentChildren;
+ initiallyExpanded?: boolean;
+ className?: string;
+ }
+ export const Collapsible: FunctionComponent<CollapsibleProps>;
+
+ export interface DropdownProps {
+ id?: string;
+ className?: string;
+ buttonClassName?: string;
+ buttonProps?: Record<string, unknown>;
+ isStatic?: boolean;
+ children?: ComponentChildren;
+ title?: string;
+ dropdownContainerStyle?: Css;
+ dropdownContainerClassName?: string;
+ dropdownContainerRef?: RefObject<HTMLDivElement | null>;
+ hideToggleArrow?: boolean;
+ iconAction?: boolean;
+ noSelectButtonStyle?: boolean;
+ noDropdownListStyle?: boolean;
+ disabled?: boolean;
+ text?: ComponentChildren;
+ forceShown?: boolean;
+ onShown?: () => void;
+ onHidden?: () => void;
+ dropdownOptions?: Record<string, unknown>;
+ dropdownRef?: RefObject<unknown>;
+ titlePosition?: "top" | "right" | "bottom" | "left";
+ titleOptions?: Record<string, unknown>;
+ mobileBackdrop?: boolean;
+ }
+ export const Dropdown: FunctionComponent<DropdownProps>;
+
+ export interface FormCheckboxProps {
+ name?: string;
+ label: ComponentChildren;
+ hint?: string;
+ currentValue: boolean;
+ disabled?: boolean;
+ onChange(newValue: boolean): void;
+ containerStyle?: Css;
+ }
+ export const FormCheckbox: FunctionComponent<FormCheckboxProps>;
+
+ export interface FormDropdownListProps<T> extends Omit<DropdownProps, "children"> {
+ values: T[];
+ keyProperty: keyof T;
+ titleProperty: keyof T;
+ titleSuffixProperty?: keyof T;
+ descriptionProperty?: keyof T;
+ currentValue: string;
+ onChange(newValue: string): void;
+ }
+ export function FormDropdownList<T>(props: FormDropdownListProps<T>): VNode<any>;
+
+ export const FormFileUploadButton: FunctionComponent<Omit<ButtonProps, "onClick"> & { onChange: (files: FileList | null) => void }>;
+ export const FormFileUploadActionButton: FunctionComponent<Omit<ActionButtonProps, "onClick"> & { onChange: (files: FileList | null) => void }>;
+
+ export interface FormGroupProps {
+ name: string;
+ labelRef?: RefObject<HTMLLabelElement>;
+ label?: string;
+ title?: string;
+ className?: string;
+ error?: string;
+ children: VNode<any>;
+ description?: ComponentChildren;
+ disabled?: boolean;
+ style?: Css;
+ }
+ export const FormGroup: FunctionComponent<FormGroupProps>;
+
+ export interface FormListItemProps {
+ children?: ComponentChildren;
+ icon?: string;
+ value?: string;
+ title?: string;
+ active?: boolean;
+ badges?: unknown[];
+ disabled?: boolean;
+ disabledTooltip?: string;
+ checked?: boolean | null;
+ selected?: boolean;
+ container?: boolean;
+ onClick?: (e: MouseEvent) => void;
+ triggerCommand?: Cmd;
+ description?: string;
+ className?: string;
+ rtl?: boolean;
+ postContent?: ComponentChildren;
+ itemRef?: RefObject<HTMLLIElement>;
+ }
+ export const FormListItem: FunctionComponent<FormListItemProps>;
+
+ export const FormDropdownDivider: FunctionComponent<{}>;
+
+ export interface FormDropdownSubmenuProps {
+ icon: string;
+ title: ComponentChildren;
+ children?: ComponentChildren;
+ onDropdownToggleClicked?: () => void;
+ dropStart?: boolean;
+ }
+ export const FormDropdownSubmenu: FunctionComponent<FormDropdownSubmenuProps>;
+
+ export interface FormRadioGroupProps {
+ name: string;
+ currentValue?: string;
+ values: ({ value: string; label: ComponentChildren; inlineDescription?: ComponentChildren } | false)[];
+ onChange(newValue: string): void;
+ }
+ export const FormRadioGroup: FunctionComponent<FormRadioGroupProps>;
+
+ export const FormText: FunctionComponent<{ children?: ComponentChildren }>;
+
+ export interface FormTextAreaProps {
+ id?: string;
+ currentValue: string;
+ onChange?(newValue: string): void;
+ onBlur?(newValue: string): void;
+ inputRef?: RefObject<HTMLTextAreaElement>;
+ className?: string;
+ placeholder?: string;
+ rows?: number;
+ disabled?: boolean;
+ readOnly?: boolean;
+ }
+ export const FormTextArea: FunctionComponent<FormTextAreaProps>;
+
+ export interface FormTextBoxProps {
+ id?: string;
+ currentValue?: string;
+ onChange?(newValue: string, validity: ValidityState): void;
+ onBlur?(newValue: string): void;
+ inputRef?: RefObject<HTMLInputElement>;
+ type?: string;
+ className?: string;
+ placeholder?: string;
+ disabled?: boolean;
+ readOnly?: boolean;
+ autoFocus?: boolean;
+ name?: string;
+ }
+ export const FormTextBox: FunctionComponent<FormTextBoxProps>;
+
+ export interface FormToggleProps {
+ currentValue: boolean | null;
+ onChange(newValue: boolean): void;
+ switchOnName?: string;
+ switchOnTooltip?: string;
+ switchOffName?: string;
+ switchOffTooltip?: string;
+ helpPage?: string;
+ disabled?: boolean;
+ afterName?: ComponentChildren;
+ id?: string;
+ }
+ export const FormToggle: FunctionComponent<FormToggleProps>;
+
+ export interface IconProps {
+ icon?: string;
+ className?: string;
+ onClick?: (e: MouseEvent) => void;
+ title?: string;
+ style?: Css;
+ }
+ export const Icon: FunctionComponent<IconProps>;
+
+ export interface LinkButtonProps {
+ onClick?: () => void;
+ text: ComponentChild;
+ triggerCommand?: Cmd;
+ }
+ export const LinkButton: FunctionComponent<LinkButtonProps>;
+
+ export const LoadingSpinner: FunctionComponent<{}>;
+
+ export interface ModalProps {
+ className: string;
+ title?: ComponentChildren;
+ customTitleBarButtons?: ({ title: string; iconClassName: string; onClick: (e: MouseEvent) => void } | null)[];
+ size: "xl" | "lg" | "md" | "sm";
+ children?: ComponentChildren;
+ header?: ComponentChildren;
+ footer?: ComponentChildren;
+ footerStyle?: Css;
+ footerAlignment?: "right" | "between";
+ minWidth?: string;
+ maxWidth?: number;
+ zIndex?: number;
+ scrollable?: boolean;
+ onSubmit?: () => void;
+ onShown?: () => void;
+ onHidden: () => void;
+ helpPageId?: string;
+ modalRef?: RefObject<HTMLDivElement>;
+ formRef?: RefObject<HTMLFormElement>;
+ bodyStyle?: Css;
+ show: boolean;
+ stackable?: boolean;
+ keepInDom?: boolean;
+ noFocus?: boolean;
+ sidebar?: ComponentChildren;
+ isFullPageOnMobile?: boolean;
+ }
+ export const Modal: FunctionComponent<ModalProps>;
+
+ export interface NoteAutocompleteProps {
+ id?: string;
+ inputRef?: RefObject<HTMLInputElement>;
+ text?: string;
+ placeholder?: string;
+ container?: RefObject<HTMLElement | null | undefined>;
+ containerStyle?: Css;
+ opts?: Record<string, unknown>;
+ onChange?: (suggestion: unknown) => void;
+ onTextChange?: (text: string) => void;
+ onKeyDown?: (e: KeyboardEvent) => void;
+ onBlur?: (newValue: string) => void;
+ noteIdChanged?: (noteId: string) => void;
+ noteId?: string;
+ }
+ export const NoteAutocomplete: FunctionComponent<NoteAutocompleteProps>;
+
+ export interface NoteLinkProps {
+ className?: string;
+ containerClassName?: string;
+ notePath: string | string[];
+ showNotePath?: boolean;
+ showNoteIcon?: boolean;
+ style?: Css;
+ noPreview?: boolean;
+ noTnLink?: boolean;
+ highlightedTokens?: string[] | null;
+ title?: string;
+ viewScope?: unknown;
+ noContextMenu?: boolean;
+ onContextMenu?: (e: MouseEvent) => void;
+ }
+ export const NoteLink: FunctionComponent<NoteLinkProps>;
+
+ export interface RawHtmlProps {
+ className?: string;
+ html?: string | HTMLElement;
+ style?: Css;
+ onClick?: (e: MouseEvent) => void;
+ tabindex?: number;
+ dir?: string;
+ containerRef?: RefObject<HTMLSpanElement>;
+ }
+ export const RawHtml: FunctionComponent<RawHtmlProps>;
+
+ export interface SliderProps {
+ value: number;
+ onChange(newValue: number): void;
+ min?: number;
+ max?: number;
+ step?: number;
+ title?: string;
+ }
+ export const Slider: FunctionComponent<SliderProps>;
+
+ export interface RightPanelWidgetProps {
+ id: string;
+ title: string;
+ children?: ComponentChildren;
+ buttons?: ComponentChildren;
+ containerRef?: RefObject<HTMLDivElement>;
+ contextMenuItems?: unknown[];
+ grow?: boolean;
+ }
+ export const RightPanelWidget: FunctionComponent<RightPanelWidgetProps>;
}
declare module "trilium:api" {
diff --git a/packages/commons/src/lib/script_api.ts b/packages/commons/src/lib/script_api.ts
index c1dcb6fa2d..82c99c5b40 100644
--- a/packages/commons/src/lib/script_api.ts
+++ b/packages/commons/src/lib/script_api.ts
@@ -222,3 +222,195 @@ export interface FrontendApi {
/** The Preact API surface (components, hooks) for render scripts. */
preact: unknown;
}
+
+/** A branch (note→parent placement) as seen by backend scripts (subset of `BBranch`). */
+export interface ScriptBBranch {
+ branchId: string;
+ noteId: string;
+ parentNoteId: string;
+ prefix: string | null;
+ notePosition: number;
+ isExpanded: boolean;
+ getNote(): ScriptBNote;
+ getParentNote(): ScriptBNote | null;
+}
+
+/** A note as seen by backend scripts (subset of trilium-core's `BNote`). */
+export interface ScriptBNote {
+ noteId: string;
+ title: string;
+ type: string;
+ mime: string;
+ isProtected: boolean;
+
+ getContent(): string | Uint8Array;
+ setContent(content: string | Uint8Array, opts?: { forceFrontendReload?: boolean }): void;
+ getJsonContent<T = unknown>(): T | null;
+
+ getParentNotes(): ScriptBNote[];
+ getChildNotes(): ScriptBNote[];
+ getParentBranches(): ScriptBBranch[];
+ getChildBranches(): ScriptBBranch[];
+
+ getAttributes(type?: string, name?: string): ScriptAttribute[];
+ getOwnedAttributes(type?: string, name?: string): ScriptAttribute[];
+ getAttribute(type: string, name: string): ScriptAttribute | null;
+ hasAttribute(type: string, name: string): boolean;
+ getLabel(name: string): ScriptAttribute | null;
+ getLabels(name?: string): ScriptAttribute[];
+ getLabelValue(name: string): string | null;
+ hasLabel(name: string): boolean;
+ addLabel(name: string, value?: string, isInheritable?: boolean): ScriptAttribute;
+ getRelation(name: string): ScriptAttribute | null;
+ getRelations(name?: string): ScriptAttribute[];
+ getRelationValue(name: string): string | null;
+ getRelationTarget(name: string): ScriptBNote | null;
+ addRelation(name: string, targetNoteId: string, isInheritable?: boolean): ScriptAttribute;
+ addAttribute(type: string, name: string, value?: string, isInheritable?: boolean): ScriptAttribute;
+ isFolder(): boolean;
+}
+
+/** Result of the backend note-creation helpers. */
+export interface ScriptNoteAndBranch {
+ note: ScriptBNote;
+ branch: ScriptBBranch;
+}
+
+/**
+ * The `api` global available inside **backend** script notes
+ * (`application/javascript;env=backend`). Runs server-side: no DOM, no jQuery.
+ */
+export interface BackendApi {
+ /** Note where the script started executing (the entrypoint). */
+ startNote?: ScriptBNote | null;
+ /** Note where the script is currently executing. */
+ currentNote: ScriptBNote;
+ /** Entity whose event triggered this execution. */
+ originEntity?: unknown | null;
+
+ /** day.js library for date manipulation. */
+ dayjs: ScriptDayjs;
+ /** xml2js library for XML parsing. */
+ xml2js: unknown;
+ /** @deprecated use htmlParser instead */
+ cheerio: unknown;
+ /** node-html-parser for HTML parsing. */
+ htmlParser: unknown;
+
+ /** The name identifying this particular Trilium instance, or null. */
+ getInstanceName(): string | null;
+
+ /** Returns a note by its ID, or null. */
+ getNote(noteId: string): ScriptBNote | null;
+ /** Returns a branch by its ID, or null. */
+ getBranch(branchId: string): ScriptBBranch | null;
+ /** Returns an attribute by its ID, or null. */
+ getAttribute(attributeId: string): ScriptAttribute | null;
+ /** Returns an attachment by its ID, or null. */
+ getAttachment(attachmentId: string): unknown | null;
+ /** Returns a revision by its ID, or null. */
+ getRevision(revisionId: string): unknown | null;
+ /** Returns an ETAPI token by its ID, or null. */
+ getEtapiToken(etapiTokenId: string): unknown | null;
+ /** Returns all ETAPI tokens. */
+ getEtapiTokens(): unknown[];
+ /** Returns an option by name, or null. */
+ getOption(optionName: string): unknown | null;
+ /** Returns all options. */
+ getOptions(): unknown[];
+
+ /** Powerful attribute/value search, e.g. "#dateModified =* MONTH AND #log". */
+ searchForNotes(query: string, searchParams?: Record<string, unknown>): ScriptBNote[];
+ /** Returns the first note matching the search, or null. */
+ searchForNote(query: string, searchParams?: Record<string, unknown>): ScriptBNote | null;
+ /** Returns all notes carrying the given label. */
+ getNotesWithLabel(name: string, value?: string): ScriptBNote[];
+ /** Returns the first note carrying the given label, or null. */
+ getNoteWithLabel(name: string, value?: string): ScriptBNote | null;
+
+ /** Ensures a branch exists between note and parent (creating it if needed). */
+ ensureNoteIsPresentInParent(noteId: string, parentNoteId: string, prefix?: string): { branch: ScriptBBranch | null };
+ /** Ensures no branch exists between note and parent (removing it if present). */
+ ensureNoteIsAbsentFromParent(noteId: string, parentNoteId: string): void;
+ /** Creates or removes the branch between note and parent based on `present`. */
+ toggleNoteInParent(present: boolean, noteId: string, parentNoteId: string, prefix?: string): void;
+
+ /** Creates a text note under the given parent. */
+ createTextNote(parentNoteId: string, title: string, content: string): ScriptNoteAndBranch;
+ /** Creates a data (JSON) note under the given parent. */
+ createDataNote(parentNoteId: string, title: string, content: object): ScriptNoteAndBranch;
+ /** Creates a new note with full control over its parameters. */
+ createNewNote(params: {
+ parentNoteId: string;
+ title: string;
+ content: string | Uint8Array;
+ type: string;
+ mime?: string;
+ [key: string]: unknown;
+ }): ScriptNoteAndBranch;
+
+ /** Per-note log message buffers shown in the UI log pane. */
+ logMessages: Record<string, string[]>;
+ /** Per-note spaced-update handlers for the log pane. */
+ logSpacedUpdates: Record<string, unknown>;
+ /** Logs a message to the Trilium log and the UI log pane. */
+ log(...args: unknown[]): void;
+
+ /** Returns the root note of the calendar. */
+ getRootCalendarNote(): ScriptBNote | null;
+ /** Returns (creating if needed) the day-note for the given "YYYY-MM-DD" date. */
+ getDayNote(date: string, rootNote?: ScriptBNote): ScriptBNote | null;
+ /** Returns (creating if needed) today's day-note. */
+ getTodayNote(rootNote?: ScriptBNote): ScriptBNote | null;
+ /** Returns (creating if needed) the week's first day-note for the given date. */
+ getWeekFirstDayNote(date: string, rootNote?: ScriptBNote): ScriptBNote | null;
+ /** Returns (creating if needed) the week-note for the given date, or null if unsupported. */
+ getWeekNote(date: string, rootNote?: ScriptBNote): ScriptBNote | null;
+ /** Returns (creating if needed) the month-note for the given "YYYY-MM" month. */
+ getMonthNote(date: string, rootNote?: ScriptBNote): ScriptBNote | null;
+ /** Returns (creating if needed) the quarter-note for the given date. */
+ getQuarterNote(date: string, rootNote?: ScriptBNote): ScriptBNote | null;
+ /** Returns (creating if needed) the year-note for the given "YYYY" year. */
+ getYearNote(year: string, rootNote?: ScriptBNote): ScriptBNote | null;
+
+ /** Sorts the child notes of the given note. */
+ sortNotes(parentNoteId: string, sortConfig: { sortBy?: string; reverse?: boolean; foldersFirst?: boolean }): void;
+ /** Sets or removes a note's branch under a parent, looked up by prefix. */
+ setNoteToParent(noteId: string, prefix: string, parentNoteId: string | null): void;
+ /** Runs the given function inside a transaction (reusing an existing one if present). */
+ transactional<T>(func: () => T): T;
+
+ /** Returns a random (non-cryptographic) alphanumeric string of the given length. */
+ randomString(length: number): string;
+ /** Escapes the given HTML string. */
+ escapeHtml(str: string): string;
+ /** Unescapes the given HTML string. */
+ unescapeHtml(str: string): string;
+ /** Low-level SQL access. */
+ sql: unknown;
+ /** Application info (version, build date, etc.). */
+ getAppInfo(): unknown;
+
+ /** Creates or updates a launchbar launcher. */
+ createOrUpdateLauncher(opts: {
+ id: string;
+ type: "note" | "script" | "customWidget";
+ title: string;
+ isVisible: boolean;
+ icon: string;
+ keyboardShortcut: string;
+ targetNoteId?: string;
+ scriptNoteId?: string;
+ widgetNoteId?: string;
+ }): { note: ScriptBNote };
+ /** Exports a subtree to a zip file in the given format. */
+ exportSubtreeToZipFile(noteId: string, format: "markdown" | "html", zipFilePath: string): Promise<void>;
+ /** Executes the given function on all connected frontend instances. */
+ runOnFrontend(script: (() => void) | string, params?: unknown[]): void;
+ /** Runs the callback while no sync process is running. */
+ runOutsideOfSync(callback: () => void): Promise<void>;
+ /** Triggers a backup immediately, returning the backup file path. */
+ backupNow(backupName: string): Promise<string>;
+ /** Duplicates a subtree under a new parent. */
+ duplicateSubtree(origNoteId: string, newParentNoteId: string): ScriptNoteAndBranch;
+}
diff --git a/packages/trilium-core/src/services/backend_script_api.ts b/packages/trilium-core/src/services/backend_script_api.ts
index d724107a65..bfeb78f100 100644
--- a/packages/trilium-core/src/services/backend_script_api.ts
+++ b/packages/trilium-core/src/services/backend_script_api.ts
@@ -1,4 +1,5 @@
import { type AttributeRow, dayjs, formatLogMessage } from "@triliumnext/commons";
+import type { BackendApi as PublicBackendApi, ScriptBNote as PublicScriptBNote } from "@triliumnext/commons/src/lib/script_api.js";
import AbstractBeccaEntity from "../becca/entities/abstract_becca_entity";
import Becca from "../becca/becca-interface";
import * as cheerio from "cheerio";
@@ -729,3 +730,16 @@ function BackendScriptApi(this: Api, currentNote: BNote, apiParams: ApiParams) {
export default BackendScriptApi as any as {
new(currentNote: BNote, apiParams: ApiParams): Api;
};
+
+// --- Drift guards -----------------------------------------------------------
+// The public backend script API surface lives in @triliumnext/commons (self-
+// contained so it can feed the in-editor language service and the script-
+// deployer). These checks fail to compile — naming the offending member — if
+// that public surface claims an `api`/`BNote` member that has since been renamed
+// or removed here.
+type _MissingBackendApiMembers = Exclude<keyof PublicBackendApi, keyof Api>;
+type _MissingBNoteMembers = Exclude<keyof PublicScriptBNote, keyof BNote>;
+// eslint-disable-next-line @typescript-eslint/no-unused-vars
+const _backendApiDriftGuard: [_MissingBackendApiMembers] extends [never] ? true : _MissingBackendApiMembers = true;
+// eslint-disable-next-line @typescript-eslint/no-unused-vars
+const _bnoteDriftGuard: [_MissingBNoteMembers] extends [never] ? true : _MissingBNoteMembers = true;