Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(share): load the client's mermaid instead of bundling a copy
Elian Doranb801f5eb6d58
diff --git a/apps/build-docs/src/build-docs.ts b/apps/build-docs/src/build-docs.tsindex 038c9adb16..cfe7710193 100644--- a/apps/build-docs/src/build-docs.ts+++ b/apps/build-docs/src/build-docs.ts@@ -289,11 +289,8 @@ export async function buildDocsFromConfig(configPath?: string, gitRootDir?: striconst config = await loadConfig(configPath);if (gitRootDir) {- // Build the share theme if we have a gitRootDir (for Trilium project)- execSync(`pnpm run --filter share-theme dist`, {- stdio: "inherit",- cwd: gitRootDir- });+ // Only a Trilium checkout (a gitRootDir) has the share theme and the client to build.+ buildShareThemeAssets(gitRootDir);}// Initialize the build environment before using cls@@ -310,11 +307,7 @@ export async function buildDocsFromConfig(configPath?: string, gitRootDir?: stri}export default async function buildDocs({ gitRootDir }: BuildContext) {- // Build the share theme.- execSync(`pnpm run --filter share-theme dist`, {- stdio: "inherit",- cwd: gitRootDir- });+ buildShareThemeAssets(gitRootDir);// Initialize the build environment before using clsawait initializeBuildEnvironment();@@ -328,3 +321,12 @@ export default async function buildDocs({ gitRootDir }: BuildContext) {});});}++/**+ * Builds the share theme and the client, whose mermaid the export copies next to the theme for+ * the pages that have a diagram.+ */+function buildShareThemeAssets(gitRootDir: string) {+ execSync("pnpm run --filter share-theme dist", { stdio: "inherit", cwd: gitRootDir });+ execSync("pnpm run --filter client build", { stdio: "inherit", cwd: gitRootDir });+}diff --git a/apps/client/src/share_mermaid.ts b/apps/client/src/share_mermaid.tsnew file mode 100644index 0000000000..0268e0b962--- /dev/null+++ b/apps/client/src/share_mermaid.ts@@ -0,0 +1,5 @@+/**+ * The mermaid the share theme renders diagrams with. Shared pages load it through the manifest+ * `shareMermaidManifest()` writes, so an installation ships one copy of mermaid, not two.+ */+export { default } from "mermaid";diff --git a/apps/client/vite-plugins.mts b/apps/client/vite-plugins.mtsindex dc3ef25221..21564f975d 100644--- a/apps/client/vite-plugins.mts+++ b/apps/client/vite-plugins.mts@@ -1,5 +1,7 @@+import { posix } from "node:path";import { fileURLToPath } from "node:url";+import type { ShareMermaidManifest } from "@triliumnext/commons";import type { Plugin } from "vite";/**@@ -48,3 +50,94 @@ export const LANGUAGE_DETECTOR_PACKAGE = "franc-min";function stubPath(name: string): string {return fileURLToPath(new URL(`./src/stubs/${name}.ts`, import.meta.url));}++/** The name of the entry the share theme loads mermaid through, `src/share_mermaid.ts`. */+export const SHARE_MERMAID_ENTRY = "share_mermaid";++/**+ * Adds `src/share_mermaid.ts` as the `share_mermaid` entry and writes its+ * {@link ShareMermaidManifest} to `manifestPath`. Shared pages read the manifest to import the+ * entry, and the share-theme export reads it to copy the files.+ *+ * The entry is emitted here rather than listed in `input` because an app build drops the exports+ * of its entries, and shared pages import the entry's default export.+ */+export function shareMermaidManifest(manifestPath: string): Plugin {+ return {+ name: "share-mermaid-manifest",+ apply: "build",+ buildStart() {+ this.emitFile({+ type: "chunk",+ id: fileURLToPath(new URL("./src/share_mermaid.ts", import.meta.url)),+ name: SHARE_MERMAID_ENTRY,+ preserveSignature: "exports-only"+ });+ },+ generateBundle(_, bundle) {+ this.emitFile({+ type: "asset",+ fileName: manifestPath,+ source: JSON.stringify(buildShareMermaidManifest(bundle, manifestPath))+ });+ }+ };+}++type BundleOutput =+ | { type: "asset"; fileName: string }+ | {+ type: "chunk";+ fileName: string;+ name: string;+ isEntry: boolean;+ imports: string[];+ dynamicImports: string[];+ viteMetadata?: { importedCss: Set<string>; importedAssets: Set<string> };+ };++/**+ * Collects the `share_mermaid` entry and everything it imports, statically or dynamically,+ * including the CSS and assets Vite preloads alongside a chunk.+ */+export function buildShareMermaidManifest(+ bundle: Record<string, BundleOutput>,+ manifestPath: string+): ShareMermaidManifest {+ const entry = Object.values(bundle).find((output) =>+ output.type === "chunk" && output.isEntry && output.name === SHARE_MERMAID_ENTRY);+ if (!entry) {+ throw new Error(`The bundle has no '${SHARE_MERMAID_ENTRY}' entry.`);+ }++ const files = new Set<string>();+ const pending = [ entry.fileName ];+ for (let fileName = pending.pop(); fileName !== undefined; fileName = pending.pop()) {+ const output = bundle[fileName];+ if (!output || files.has(fileName)) {+ continue;+ }++ files.add(fileName);+ if (output.type === "chunk") {+ pending.push(+ ...output.imports,+ ...output.dynamicImports,+ ...(output.viteMetadata?.importedCss ?? []),+ ...(output.viteMetadata?.importedAssets ?? [])+ );+ }+ }++ const directories = new Set([ ...files ].map((fileName) => posix.dirname(fileName)));+ if (directories.size !== 1) {+ const list = [ ...directories ].join(", ");+ throw new Error(`The '${SHARE_MERMAID_ENTRY}' files span several directories: ${list}.`);+ }++ const manifestDir = posix.dirname(manifestPath);+ return {+ entry: posix.relative(manifestDir, entry.fileName),+ files: [ ...files ].sort().map((fileName) => posix.relative(manifestDir, fileName))+ };+}diff --git a/apps/client/vite-plugins.spec.ts b/apps/client/vite-plugins.spec.tsindex 8256ac2ded..6006e1ab16 100644--- a/apps/client/vite-plugins.spec.ts+++ b/apps/client/vite-plugins.spec.ts@@ -3,7 +3,12 @@ import { createRequire } from "module";import { dirname, join } from "path";import { describe, expect, it } from "vitest";-import { ENGINE_RENDER_ENTRY, LANGUAGE_DETECTOR_PACKAGE, resolveUniverHyphenationStub } from "./vite-plugins.mjs";+import {+ buildShareMermaidManifest,+ ENGINE_RENDER_ENTRY,+ LANGUAGE_DETECTOR_PACKAGE,+ resolveUniverHyphenationStub+} from "./vite-plugins.mjs";const entryPath = createRequire(import.meta.url).resolve("@univerjs/engine-render/lib/es/index.js");const entrySource = readFileSync(entryPath, "utf8");@@ -70,6 +75,62 @@ describe("stripUniverHyphenation", () => {});});+describe("buildShareMermaidManifest", () => {+ const chunk = (fileName: string, extra: { name?: string; isEntry?: boolean; imports?: string[];+ dynamicImports?: string[]; css?: string[] } = {}) => ({+ type: "chunk" as const,+ fileName,+ name: extra.name ?? fileName,+ isEntry: extra.isEntry ?? false,+ imports: extra.imports ?? [],+ dynamicImports: extra.dynamicImports ?? [],+ viteMetadata: { importedCss: new Set(extra.css ?? []), importedAssets: new Set<string>() }+ });+ const bundle = Object.fromEntries([+ chunk("src/share_mermaid-a.js", {+ name: "share_mermaid",+ isEntry: true,+ imports: [ "src/core-b.js" ]+ }),+ chunk("src/core-b.js", {+ dynamicImports: [ "src/flowchart-c.js", "src/elk-d.js" ],+ css: [ "src/core-e.css" ]+ }),+ chunk("src/flowchart-c.js", { imports: [ "src/core-b.js" ] }),+ chunk("src/elk-d.js"),+ { type: "asset" as const, fileName: "src/core-e.css" },+ chunk("src/index-f.js", { name: "index", isEntry: true, imports: [ "src/core-b.js" ] })+ ].map((output) => [ output.fileName, output ]));++ it("lists the entry and everything it loads, relative to the manifest", () => {+ const files = [+ "core-b.js", "core-e.css", "elk-d.js", "flowchart-c.js", "share_mermaid-a.js"+ ];++ expect(buildShareMermaidManifest(bundle, "src/share_mermaid.json"))+ .toEqual({ entry: "share_mermaid-a.js", files });+ const standaloneManifest = "share/assets/client/share_mermaid.json";+ expect(buildShareMermaidManifest(bundle, standaloneManifest)).toEqual({+ entry: "../../../src/share_mermaid-a.js",+ files: files.map((file) => `../../../src/${file}`)+ });+ });++ it("rejects a bundle without the entry or with files outside one directory", () => {+ const MANIFEST = "src/share_mermaid.json";+ const { "src/share_mermaid-a.js": _, ...withoutEntry } = bundle;+ expect(() => buildShareMermaidManifest(withoutEntry, MANIFEST))+ .toThrow("no 'share_mermaid' entry");++ const nested = {+ ...bundle,+ "src/elk-d.js": chunk("src/elk-d.js", { imports: [ "src/nested/g.js" ] }),+ "src/nested/g.js": chunk("src/nested/g.js")+ };+ expect(() => buildShareMermaidManifest(nested, MANIFEST)).toThrow("several directories");+ });+});+/** Reads the generated `PATTERN_LOADERS` map, whose keys are the locales Univer hyphenates. */function patternLoaders(): { locale: string; source: string }[] {const entries = entrySource.matchAll(/\["([a-z0-9-]+)"\]\s*:\s*\(\)\s*=>\s*import\("(\.[^"]*)"\)/g);diff --git a/apps/client/vite.config.mts b/apps/client/vite.config.mtsindex 0ec0238dd5..10ebd41cfb 100644--- a/apps/client/vite.config.mts+++ b/apps/client/vite.config.mts@@ -5,7 +5,7 @@ import { join } from 'path';import { defineConfig } from 'vite';import { viteStaticCopy } from 'vite-plugin-static-copy'-import { stripUniverHyphenation } from './vite-plugins.mjs';+import { shareMermaidManifest, stripUniverHyphenation } from './vite-plugins.mjs';const assets = [ "assets", "stylesheets", "fonts", "translations" ];@@ -23,6 +23,7 @@ if (isDev) {} else {plugins = [stripUniverHyphenation(),+ shareMermaidManifest("src/share_mermaid.json"),viteStaticCopy({targets: assets.map((asset) => ({src: `src/${asset}/**/*`,diff --git a/apps/server/src/routes/assets.ts b/apps/server/src/routes/assets.tsindex 9cba96bcbf..8dd3ee2e51 100644--- a/apps/server/src/routes/assets.ts+++ b/apps/server/src/routes/assets.ts@@ -80,6 +80,9 @@ async function register(app: express.Application) {vite.middlewares(req, res, next);});app.use(`/node_modules/@excalidraw/excalidraw/dist/prod`, persistentCacheStatic(path.join(srcRoot, "../../node_modules/@excalidraw/excalidraw/dist/prod")));+ app.get(`/share/assets/client/share_mermaid.json`, (_req, res) => {+ res.json({ entry: `/${assetUrlFragment}/src/share_mermaid.ts`, files: [] });+ });} else {const publicDir = path.join(resourceDir, "public");if (!existsSync(publicDir)) {@@ -100,6 +103,9 @@ async function register(app: express.Application) {app.use(`/${assetUrlFragment}/fonts`, persistentCacheStatic(path.join(publicDir, "fonts")));app.use(`/${assetUrlFragment}/translations/`, persistentCacheStatic(path.join(publicDir, "translations")));app.use(`/node_modules/`, persistentCacheStatic(path.join(publicDir, "node_modules")));+ // The share theme loads the client's mermaid through `src/share_mermaid.json`.+ const clientSrc = express.static(path.join(publicDir, "src"), STATIC_OPTIONS);+ app.use(`/share/assets/client/`, clientSrc);}app.use(`/share/assets/fonts/`, express.static(path.join(getClientDir(), "fonts"), STATIC_OPTIONS));app.use(`/share/assets/`, express.static(getShareThemeAssetDir(), STATIC_OPTIONS));@@ -124,6 +130,15 @@ export function getShareThemeAssetDir() {return path.join(resourceDir, "share-theme/assets");}+/** The client's build output: `public/` in a packaged app, `apps/client/dist` in development. */+export function getClientBuildDir() {+ if (process.env.NODE_ENV === "development") {+ const srcRoot = path.join(__dirname, "..", "..");+ return path.join(srcRoot, "../client/dist");+ }+ return path.join(getResourceDir(), "public");+}+export function getPdfjsAssetDir() {if (process.env.NODE_ENV === "development") {const srcRoot = path.join(__dirname, "..", "..");diff --git a/apps/server/src/services/export/zip/share_theme.spec.ts b/apps/server/src/services/export/zip/share_theme.spec.tsindex 2a673bb3c2..5cf1354b2f 100644--- a/apps/server/src/services/export/zip/share_theme.spec.ts+++ b/apps/server/src/services/export/zip/share_theme.spec.ts@@ -1,12 +1,25 @@-import { describe, expect, it, vi } from "vitest";+import { beforeEach, describe, expect, it, vi } from "vitest";++const MANIFEST = vi.hoisted(() => ({+ entry: "share_mermaid-a.js",+ files: [ "share_mermaid-a.js", "core-b.js" ]+}));const mockFs = vi.hoisted(() => ({+ existsSync: vi.fn((_path: string) => true),readdirSync: vi.fn(() => [ "styles.css", "scripts.js" ]),- readFileSync: vi.fn((path: string) => new TextEncoder().encode(`content of ${path.split("\\").join("/")}`))+ readFileSync: vi.fn((path: string) => {+ const normalized = path.split("\\").join("/");+ if (normalized.endsWith("share_mermaid.json")) {+ return JSON.stringify(MANIFEST);+ }+ return new TextEncoder().encode(`content of ${normalized}`);+ })}));vi.mock("fs", () => ({ default: mockFs, ...mockFs }));vi.mock("../../../routes/assets", () => ({+ getClientBuildDir: () => "/client-build",getClientDir: () => "/client",getShareThemeAssetDir: () => "/share-assets"}));@@ -15,16 +28,19 @@ vi.mock("../../resource_dir", () => ({ RESOURCE_DIR: "/resource" }));const registerShareProvider = vi.hoisted(() => vi.fn());vi.mock("../../../share/share_provider.js", () => ({ registerShareProvider }));+const mockLog = vi.hoisted(() => ({ info: vi.fn() }));+vi.mock("@triliumnext/core/src/services/log.js", () => ({ getLog: () => mockLog }));+const { createShareThemeExportProvider } = await import("./share_theme.js");describe("createShareThemeExportProvider", () => {+ beforeEach(() => {+ mockFs.existsSync.mockReturnValue(true);+ mockLog.info.mockClear();+ });+it("reads the share theme's files and the built-in fonts from disk", () => {- const provider = createShareThemeExportProvider({ branch: {} } as never);- const { files, readBuiltinFont } = (provider as unknown as { assets: {- files: Map<string, Uint8Array>;- readBuiltinFont(fileName: string): Uint8Array | undefined;- } }).assets;- const decode = (data: Uint8Array | undefined) => new TextDecoder().decode(data);+ const { files, readBuiltinFont } = createAssets("<p>No diagrams.</p>");expect(registerShareProvider).toHaveBeenCalled();expect([ ...files.keys() ]).toEqual([ "icon-color.svg", "assets/styles.css", "assets/scripts.js" ]);@@ -32,4 +48,42 @@ describe("createShareThemeExportProvider", () => {expect(decode(files.get("assets/scripts.js"))).toBe("content of /share-assets/scripts.js");expect(decode(readBuiltinFont("boxicons.woff2"))).toBe("content of /client/fonts/boxicons.woff2");});++ it("copies the client's mermaid from its manifest when a note has a diagram", () => {+ const { files } = createAssets(MERMAID_BLOCK);++ expect(JSON.parse(String(files.get("assets/client/share_mermaid.json")))).toEqual(MANIFEST);+ for (const file of MANIFEST.files) {+ expect(decode(files.get(`assets/client/${file}`)))+ .toBe(`content of /client-build/src/${file}`);+ }+ });++ it("exports without mermaid when the client build has no manifest", () => {+ mockFs.existsSync.mockReturnValue(false);+ const { files } = createAssets(MERMAID_BLOCK);++ expect([ ...files.keys() ].filter((name) => name.startsWith("assets/client/"))).toEqual([]);+ expect(mockLog.info)+ .toHaveBeenCalledWith(expect.stringContaining("share_mermaid.json is missing"));+ });});++const MERMAID_BLOCK = `<pre><code class="language-mermaid">graph TD;</code></pre>`;++function createAssets(content: string) {+ const note = {+ getSubtree: () => ({+ notes: [ { type: "text", isContentAvailable: () => true, getContent: () => content } ]+ })+ };+ const provider = createShareThemeExportProvider({ branch: { getNote: () => note } } as never);+ return (provider as unknown as { assets: {+ files: Map<string, string | Uint8Array>;+ readBuiltinFont(fileName: string): Uint8Array | undefined;+ } }).assets;+}++function decode(data: string | Uint8Array | undefined) {+ return typeof data === "string" ? data : new TextDecoder().decode(data);+}diff --git a/apps/server/src/services/export/zip/share_theme.ts b/apps/server/src/services/export/zip/share_theme.tsindex fb24b3ffcf..c108d2c177 100644--- a/apps/server/src/services/export/zip/share_theme.ts+++ b/apps/server/src/services/export/zip/share_theme.ts@@ -1,17 +1,31 @@+import type { ShareMermaidManifest } from "@triliumnext/commons";import type { ZipExportProviderData } from "@triliumnext/core";-import ShareThemeExportProvider, { type ShareThemeExportAssets } from "@triliumnext/core/src/services/export/zip/share_theme.js";-import { readdirSync, readFileSync } from "fs";+import ShareThemeExportProvider, {+ hasMermaidDiagrams,+ mapMermaidExportFiles,+ type ShareThemeExportAssets+} from "@triliumnext/core/src/services/export/zip/share_theme.js";+import { getLog } from "@triliumnext/core/src/services/log.js";+import { existsSync, readdirSync, readFileSync } from "fs";import { join } from "path";-import { getClientDir, getShareThemeAssetDir } from "../../../routes/assets";+import { getClientBuildDir, getClientDir, getShareThemeAssetDir } from "../../../routes/assets";import { registerShareProvider } from "../../../share/share_provider.js";import { RESOURCE_DIR } from "../../resource_dir";-/** Builds a share-theme export over the theme's built files and the client's fonts on disk. */+/**+ * Builds a share-theme export over the theme's built files, the client's fonts and, when a note+ * has a diagram, the client's mermaid, all read from disk.+ */export function createShareThemeExportProvider(data: ZipExportProviderData) {registerShareProvider();- return new ShareThemeExportProvider(data, readShareThemeExportAssets());+ const assets = readShareThemeExportAssets();+ if (hasMermaidDiagrams(data.branch.getNote())) {+ addMermaidFiles(assets.files);+ }++ return new ShareThemeExportProvider(data, assets);}function readShareThemeExportAssets(): ShareThemeExportAssets {@@ -29,3 +43,23 @@ function readShareThemeExportAssets(): ShareThemeExportAssets {readBuiltinFont: (fileName) => readFileSync(join(getClientDir(), "fonts", fileName))};}++/**+ * Copies the client's mermaid into the export. Without a client build to copy from, which a+ * development server might lack, the exported pages show diagrams as code blocks.+ */+function addMermaidFiles(files: Map<string, string | Uint8Array>) {+ const manifestDir = join(getClientBuildDir(), "src");+ const manifestPath = join(manifestDir, "share_mermaid.json");+ if (!existsSync(manifestPath)) {+ getLog().info(`Exporting without mermaid, since ${manifestPath} is missing.`);+ return;+ }++ const manifest = JSON.parse(readFileSync(manifestPath, "utf-8")) as ShareMermaidManifest;+ const mapped = mapMermaidExportFiles(manifest);+ files.set(mapped.manifest.path, mapped.manifest.content);+ for (const { source, target } of mapped.files) {+ files.set(target, readFileSync(join(manifestDir, source)));+ }+}diff --git a/apps/standalone/src/lightweight/zip_export_provider_factory.spec.ts b/apps/standalone/src/lightweight/zip_export_provider_factory.spec.tsindex 4c2574ba60..8abdbdae74 100644--- a/apps/standalone/src/lightweight/zip_export_provider_factory.spec.ts+++ b/apps/standalone/src/lightweight/zip_export_provider_factory.spec.ts@@ -6,9 +6,14 @@ import { standaloneZipExportProviderFactory } from "./zip_export_provider_factorvi.mock("virtual:share-theme-assets", () => ({ default: [ "styles.css", "scripts.js" ] }));-function makeData(): ZipExportProviderData {+function makeData(content = "<p>No diagrams.</p>"): ZipExportProviderData {+ const note = {+ getSubtree: () => ({+ notes: [ { type: "text", isContentAvailable: () => true, getContent: () => content } ]+ })+ };return {- branch: { branchId: "test" },+ branch: { branchId: "test", getNote: () => note },getNoteTargetUrl: () => null,archive: new BrowserZipProvider().createZipArchive(),zipExportOptions: undefined,@@ -52,6 +57,25 @@ describe("standaloneZipExportProviderFactory", () => {.toBe("content of /share/assets/fonts/boxicons.woff2");});+ it("adds the client's mermaid through its manifest when a note has a diagram", async () => {+ const manifest = { entry: "../../../src/entry-a.js", files: [ "../../../src/entry-a.js" ] };+ vi.stubGlobal("fetch", vi.fn(async (url: string) => new Response(+ url.endsWith("share_mermaid.json")+ ? JSON.stringify(manifest)+ : `content of ${new URL(url, location.href).pathname}`+ )));++ const provider = await standaloneZipExportProviderFactory("share",+ makeData(`<pre><code class="language-mermaid">graph TD;</code></pre>`));++ type WithAssets = { assets: { files: Map<string, string | Uint8Array> } };+ const { files } = (provider as unknown as WithAssets).assets;+ expect(JSON.parse(files.get("assets/client/share_mermaid.json") as string))+ .toEqual({ entry: "entry-a.js", files: [ "entry-a.js" ] });+ expect(new TextDecoder().decode(files.get("assets/client/entry-a.js") as Uint8Array))+ .toBe("content of /src/entry-a.js");+ });+it("fails the share-theme export when a theme file cannot be fetched", async () => {vi.stubGlobal("fetch", vi.fn(async () => new Response("", { status: 404 })));diff --git a/apps/standalone/src/lightweight/zip_export_provider_factory.ts b/apps/standalone/src/lightweight/zip_export_provider_factory.tsindex 56614b3f2a..88e79c003e 100644--- a/apps/standalone/src/lightweight/zip_export_provider_factory.ts+++ b/apps/standalone/src/lightweight/zip_export_provider_factory.ts@@ -1,5 +1,15 @@-import { type ExportFormat, icon_packs, type ZipExportProviderData, ZipExportProvider } from "@triliumnext/core";-import type { ShareThemeExportAssets } from "@triliumnext/core/src/services/export/zip/share_theme.js";+import type { ShareMermaidManifest } from "@triliumnext/commons";+import {+ binary_utils,+ type ExportFormat,+ icon_packs,+ type ZipExportProviderData,+ ZipExportProvider+} from "@triliumnext/core";+import type {+ mapMermaidExportFiles,+ ShareThemeExportAssets+} from "@triliumnext/core/src/services/export/zip/share_theme.js";import contentCss from "@triliumnext/ckeditor5/src/theme/ck-content.css?raw";@@ -14,13 +24,16 @@ export async function standaloneZipExportProviderFactory(format: ExportFormat, dreturn new MarkdownExportProvider(data);}case "share": {- const [ { default: ShareThemeExportProvider }, { registerShareProvider }, assets ] = await Promise.all([+ const [ shareTheme, { registerShareProvider }, assets ] = await Promise.all([import("@triliumnext/core/src/services/export/zip/share_theme.js"),import("./share_provider.js"),loadShareThemeExportAssets()]);+ if (shareTheme.hasMermaidDiagrams(data.branch.getNote())) {+ await addMermaidFiles(assets.files, shareTheme.mapMermaidExportFiles);+ }registerShareProvider();- return new ShareThemeExportProvider(data, assets);+ return new shareTheme.default(data, assets);}default:throw new Error(`Unsupported export format: '${format}'`);@@ -58,6 +71,26 @@ async function loadShareThemeExportAssets(): Promise<ShareThemeExportAssets> {};}+/** Fetches the client's mermaid through the manifest the build writes next to the share theme. */+async function addMermaidFiles(+ files: Map<string, string | Uint8Array>,+ mapFiles: typeof mapMermaidExportFiles+) {+ const manifestUrl = new URL(SHARE_MERMAID_MANIFEST, location.href);+ const manifestBytes = await fetchAsset(manifestUrl.href);+ const manifest = JSON.parse(binary_utils.decodeUtf8(manifestBytes)) as ShareMermaidManifest;+ const mapped = mapFiles(manifest);+ const contents = await Promise.all(mapped.files.map(({ source }) =>+ fetchAsset(new URL(source, manifestUrl).href)));++ files.set(mapped.manifest.path, mapped.manifest.content);+ for (const [ index, { target } ] of mapped.files.entries()) {+ files.set(target, contents[index]);+ }+}++const SHARE_MERMAID_MANIFEST = "/share/assets/client/share_mermaid.json";+async function fetchAsset(url: string) {const response = await fetch(url);if (!response.ok) {diff --git a/apps/standalone/vite.config.mts b/apps/standalone/vite.config.mtsindex c4ce4b23e7..2384697258 100644--- a/apps/standalone/vite.config.mts+++ b/apps/standalone/vite.config.mts@@ -6,12 +6,15 @@ import prefresh from "@prefresh/vite";import { defineConfig, type Plugin } from "vite";import { viteStaticCopy } from "vite-plugin-static-copy";-import { stripUniverHyphenation } from "../client/vite-plugins.mjs";+import { shareMermaidManifest, stripUniverHyphenation } from "../client/vite-plugins.mjs";const clientAssets = ["assets", "stylesheets", "fonts", "translations"];const isDev = process.env.NODE_ENV === "development";+// Next to the share theme's own files, where `scripts.js` looks for it.+const SHARE_MERMAID_MANIFEST = "share/assets/client/share_mermaid.json";+// The share pages resolve built-in assets against `assets/v<version>`, the same prefix the server// serves them under. Read from trilium-core because that is the version `assetUrlFragment` is// built from; `chore:update-version` keeps every package.json in step.@@ -58,6 +61,19 @@ const clientWatchPlugin = () => ({}});+// Points the share pages at the client's mermaid entry, which the build lists in its manifest.+const shareMermaidDevPlugin = (): Plugin => ({+ name: "share-mermaid-dev",+ configureServer(server) {+ const entry = join(__dirname, "../client/src/share_mermaid.ts").replace(/\\/g, "/");++ server.middlewares.use(`/${SHARE_MERMAID_MANIFEST}`, (_req, res) => {+ res.setHeader("Content-Type", "application/json");+ res.end(JSON.stringify({ entry: `/@fs/${entry.replace(/^\//, "")}`, files: [] }));+ });+ }+});+// Serve PDF.js files directly in dev mode to bypass SPA fallbackconst pdfjsServePlugin = (): Plugin => ({name: "pdfjs-serve",@@ -214,8 +230,11 @@ let plugins: any = [...(isDev ? [prefresh(),clientWatchPlugin(),- pdfjsServePlugin()- ] : [])+ pdfjsServePlugin(),+ shareMermaidDevPlugin()+ ] : [+ shareMermaidManifest(SHARE_MERMAID_MANIFEST)+ ])];if (!isDev) {diff --git a/packages/commons/src/lib/shared_types.ts b/packages/commons/src/lib/shared_types.tsindex 17b701eca2..92d50107c4 100644--- a/packages/commons/src/lib/shared_types.ts+++ b/packages/commons/src/lib/shared_types.ts@@ -7,4 +7,13 @@ export interface Contributor {fullName?: string;url: string;role?: "lead-dev" | "original-dev";-}\ No newline at end of file+}+/**+ * Where the client's `share_mermaid` entry and every file it can load are, each path relative to+ * the manifest. The client build writes it; shared pages read it to import mermaid, and the+ * share-theme export reads it to copy the files. All the files sit in one directory.+ */+export interface ShareMermaidManifest {+ entry: string;+ files: string[];+}diff --git a/packages/share-theme/package.json b/packages/share-theme/package.jsonindex 80974d6c31..bcdfb23112 100644--- a/packages/share-theme/package.json+++ b/packages/share-theme/package.json@@ -26,8 +26,7 @@"dependencies": {"@triliumnext/commons": "workspace:*","fuse.js": "7.5.0",- "katex": "0.18.7",- "mermaid": "12.0.0"+ "katex": "0.18.7"},"devDependencies": {"@digitak/esrun": "3.2.26",diff --git a/packages/share-theme/src/scripts/modules/mermaid.spec.ts b/packages/share-theme/src/scripts/modules/mermaid.spec.tsnew file mode 100644index 0000000000..55a5f6ec12--- /dev/null+++ b/packages/share-theme/src/scripts/modules/mermaid.spec.ts@@ -0,0 +1,27 @@+import { afterEach, describe, expect, it, vi } from "vitest";++import { loadMermaid } from "./mermaid.js";++describe("loadMermaid", () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it("imports the entry the manifest next to the script names", async () => {+ const fetchMock = vi.fn(async (_url: URL) => new Response(JSON.stringify({+ entry: `data:text/javascript,export default { name: "client mermaid" };`,+ files: []+ })));+ vi.stubGlobal("fetch", fetchMock);++ expect(await loadMermaid()).toEqual({ name: "client mermaid" });+ expect(fetchMock.mock.calls[0][0].href)+ .toBe(new URL("client/share_mermaid.json", import.meta.url).href);+ });++ it("fails when the manifest is missing", async () => {+ vi.stubGlobal("fetch", vi.fn(async () => new Response("", { status: 404 })));++ await expect(loadMermaid()).rejects.toThrow("HTTP 404");+ });+});diff --git a/packages/share-theme/src/scripts/modules/mermaid.ts b/packages/share-theme/src/scripts/modules/mermaid.tsindex 1b6257840a..e02e014df4 100644--- a/packages/share-theme/src/scripts/modules/mermaid.ts+++ b/packages/share-theme/src/scripts/modules/mermaid.ts@@ -4,7 +4,7 @@ export default async function setupMermaid() {return;}- const mermaid = (await import("mermaid")).default;+ const mermaid = await loadMermaid();for (const codeBlock of mermaidEls) {const parentPre = codeBlock.parentElement;@@ -24,3 +24,24 @@ export default async function setupMermaid() {mermaid.initialize({ theme: "default", layout: "dagre", look: "classic" });mermaid.init();}++interface Mermaid {+ initialize(config: Record<string, unknown>): void;+ init(): void;+}++/**+ * Imports the client's mermaid, which the server, the standalone build and the share-theme export+ * each place at `client/` next to this script, described by `share_mermaid.json`.+ */+export async function loadMermaid(): Promise<Mermaid> {+ const manifestUrl = new URL("client/share_mermaid.json", import.meta.url);+ const response = await fetch(manifestUrl);+ if (!response.ok) {+ throw new Error(`Failed to load ${manifestUrl.href}: HTTP ${response.status}.`);+ }++ const { entry } = await response.json() as { entry: string };+ const module = await import(new URL(entry, manifestUrl).href) as { default: Mermaid };+ return module.default;+}diff --git a/packages/trilium-core/src/services/export/zip/share_theme.spec.ts b/packages/trilium-core/src/services/export/zip/share_theme.spec.tsindex f7a96cb9aa..fce33a20f8 100644--- a/packages/trilium-core/src/services/export/zip/share_theme.spec.ts+++ b/packages/trilium-core/src/services/export/zip/share_theme.spec.ts@@ -26,7 +26,11 @@ vi.mock("../../../becca/becca.js", () => ({ default: mockBecca }));const mockLog = { error: vi.fn(), info: vi.fn() };vi.mock("../../log.js", () => ({ getLog: () => mockLog }));-const { default: ShareThemeExportProvider } = await import("./share_theme.js");+const {+ default: ShareThemeExportProvider,+ hasMermaidDiagrams,+ mapMermaidExportFiles+} = await import("./share_theme.js");// --- Test scaffolding -------------------------------------------------------@@ -310,3 +314,64 @@ describe("ShareThemeExportProvider", () => {});});});++describe("hasMermaidDiagrams", () => {+ type FakeNote = { type: string; mime?: string; available?: boolean; content: string };++ function subtreeOf(...notes: FakeNote[]) {+ return {+ getSubtree: () => ({+ notes: notes.map(({ type, mime = "text/html", available = true, content }) => ({+ type,+ mime,+ isContentAvailable: () => available,+ getContent: () => content+ }))+ })+ } as any;+ }++ it("finds a mermaid block only in a readable text note", () => {+ const mermaid = `<pre><code class="language-mermaid">graph TD;</code></pre>`;++ expect(hasMermaidDiagrams(subtreeOf(+ { type: "text", content: "<p>root</p>" },+ { type: "text", content: mermaid }+ ))).toBe(true);+ expect(hasMermaidDiagrams(subtreeOf(+ { type: "code", content: mermaid },+ { type: "text", available: false, content: mermaid },+ { type: "text", content: `<pre><code class="language-javascript">x</code></pre>` }+ ))).toBe(false);+ });++ it("finds a fenced mermaid block only in a Markdown note", () => {+ const markdown = { type: "code", mime: "text/x-markdown" };++ const fenced = "# Title\n\n~~~ mermaid\ngraph TD;\n~~~";++ expect(hasMermaidDiagrams(subtreeOf({ ...markdown, content: fenced }))).toBe(true);+ expect(hasMermaidDiagrams(subtreeOf(+ { ...markdown, content: "Inline ```mermaid is not a fence.\n\n```js\nmermaid();\n```" },+ { type: "code", mime: "application/javascript", content: "```mermaid" }+ ))).toBe(false);+ });+});++describe("mapMermaidExportFiles", () => {+ it("flattens the listed files into assets/client and rewrites the manifest to match", () => {+ const entry = "../../../src/share_mermaid-abc.js";+ const core = "../../../src/mermaid.core-def.js";+ const mapped = mapMermaidExportFiles({ entry, files: [ entry, core ] });++ expect(mapped.files).toEqual([+ { source: entry, target: "assets/client/share_mermaid-abc.js" },+ { source: core, target: "assets/client/mermaid.core-def.js" }+ ]);+ expect(mapped.manifest.path).toBe("assets/client/share_mermaid.json");+ expect(JSON.parse(mapped.manifest.content)).toEqual({+ entry: "share_mermaid-abc.js",+ files: [ "share_mermaid-abc.js", "mermaid.core-def.js" ]+ });+ });+});diff --git a/packages/trilium-core/src/services/export/zip/share_theme.ts b/packages/trilium-core/src/services/export/zip/share_theme.tsindex ebbff75ba5..0bc388402a 100644--- a/packages/trilium-core/src/services/export/zip/share_theme.ts+++ b/packages/trilium-core/src/services/export/zip/share_theme.ts@@ -1,6 +1,7 @@+import type { ShareMermaidManifest } from "@triliumnext/commons";+import ejs from "ejs";import { convert as convertToText } from "html-to-text";import { t } from "i18next";-import ejs from "ejs";import becca from "../../../becca/becca.js";import type BBranch from "../../../becca/entities/bbranch.js";@@ -9,11 +10,16 @@ import type { ExportFormat, NoteMeta, NoteMetaFile } from "../../../meta.js";import { readShareTemplate, renderNoteForExport } from "../../../share/index.js";import * as iconPackService from "../../icon_packs.js";import { getLog } from "../../log.js";+import { basename } from "../../utils/path.js";import { ZipExportProvider, type ZipExportProviderData } from "./abstract_provider.js";/** The static files a share-theme export copies into the archive, read by each platform its own way. */export interface ShareThemeExportAssets {- /** The share theme's files, keyed by their path in the archive: `icon-color.svg` and `assets/<file>`. */+ /**+ * The share theme's files, keyed by their path in the archive: `icon-color.svg`,+ * `assets/<file>`, and the client's mermaid under `assets/client/` when+ * {@link hasMermaidDiagrams} finds a diagram.+ */files: Map<string, string | Uint8Array>;/** Returns the font of a built-in icon pack, such as `boxicons.woff2`. */readBuiltinFont(fileName: string): Uint8Array | undefined;@@ -177,3 +183,48 @@ export default class ShareThemeExportProvider extends ZipExportProvider {}}++/** Where the exported pages find the client's mermaid: `client/` next to `assets/scripts.js`. */+const MERMAID_ARCHIVE_DIR = "assets/client";++/**+ * Whether `note` or a note below it has a mermaid code block the shared page renders: a text note's+ * `language-mermaid` block or a Markdown note's fenced one. Only then does the export carry the+ * client's mermaid, several megabytes the pages load on demand.+ */+export function hasMermaidDiagrams(note: BNote) {+ return note.getSubtree().notes.some((subtreeNote) => {+ if (!subtreeNote.isContentAvailable()) {+ return false;+ }++ if (subtreeNote.type === "text") {+ return String(subtreeNote.getContent()).includes("language-mermaid");+ }++ return subtreeNote.type === "code" && subtreeNote.mime === "text/x-markdown"+ && MARKDOWN_MERMAID_FENCE.test(String(subtreeNote.getContent()));+ });+}++const MARKDOWN_MERMAID_FENCE = /^ {0,3}(`{3,}|~{3,})\s*mermaid\b/m;++/**+ * Maps the files `manifest` lists to their place in the archive, flattened into `assets/client/`,+ * and returns the manifest the exported pages read there.+ */+export function mapMermaidExportFiles(manifest: ShareMermaidManifest) {+ return {+ manifest: {+ path: `${MERMAID_ARCHIVE_DIR}/share_mermaid.json`,+ content: JSON.stringify({+ entry: basename(manifest.entry),+ files: manifest.files.map(basename)+ })+ },+ files: manifest.files.map((source) => ({+ source,+ target: `${MERMAID_ARCHIVE_DIR}/${basename(source)}`+ }))+ };+}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 0c2256751b..36bac09756 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1358,9 +1358,6 @@ importers:katex:specifier: 0.18.7version: 0.18.7- mermaid:- specifier: 12.0.0- version: 12.0.0devDependencies:'@digitak/esrun':specifier: 3.2.26