From e0416097e106f97a9d0d27af485c5855311bfac5 Mon Sep 17 00:00:00 2001 From: Elian Doran Date: Sat, 20 Dec 2025 22:23:25 +0200 Subject: [PATCH] feat(script/jsx): support import syntax for api --- apps/server/src/services/script.spec.ts | 14 +++++++++++++- apps/server/src/services/script.ts | 6 ++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/apps/server/src/services/script.spec.ts b/apps/server/src/services/script.spec.ts index 608ce94a2..9a239688f 100644 --- a/apps/server/src/services/script.spec.ts +++ b/apps/server/src/services/script.spec.ts @@ -146,7 +146,7 @@ describe("JSX building", () => { expect(buildJsx(script).code).toStrictEqual(expected); }); - it("rewrite React API imports", () => { + it("rewrites React API imports", () => { const script = trimIndentation`\ import { defineWidget, RightPanelWidget} from "trilium:preact"; defineWidget({ @@ -163,6 +163,18 @@ describe("JSX building", () => { } }); `; + expect(buildJsx(script).code).toStrictEqual(expected); + }); + + it("rewrites internal API imports", () => { + const script = trimIndentation`\ + import { log } from "trilium:api"; + log("Hi"); + `; + const expected = trimIndentation`\ + "use strict";const _triliumapi = api; + _triliumapi.log.call(void 0, "Hi"); + `; console.log(buildJsx(script).code); expect(buildJsx(script).code).toStrictEqual(expected); }); diff --git a/apps/server/src/services/script.ts b/apps/server/src/services/script.ts index 4b742c0e7..65dfe752f 100644 --- a/apps/server/src/services/script.ts +++ b/apps/server/src/services/script.ts @@ -240,6 +240,12 @@ export function buildJsx(contentRaw: string | Buffer) { 'const $1 = api.preact;' ); + // Rewrite ESM-like imports to internal API, to `const { foo } = api.preact` + code = code.replaceAll( + /var\s+(\w+)\s*=\s*require\(['"]trilium:api['"]\);?/g, + 'const $1 = api;' + ); + output.code = code; return output; }