Skip to content

Build your personal knowledge base with Trilium Notes

fix(share): unregister disabled languages, load them only for pages

Elian Doran78be186211a7
diff --git a/apps/server/src/share/routes.spec.ts b/apps/server/src/share/routes.spec.ts
index 5964a17c68..d16bedf906 100644
--- a/apps/server/src/share/routes.spec.ts
+++ b/apps/server/src/share/routes.spec.ts
@@ -33,6 +33,20 @@ describe("Share API test", () => {
cannotSetHeadersCount = 0;
});
+ it("registers the highlighter's languages only for the routes that render a page", async () => {
+ const getOption = vi.spyOn(options, "getOptionOrNull");
+ const readsMimeTypes = () => getOption.mock.calls.some(([ name ]) => name === "codeNotesMimeTypes");
+ try {
+ await supertest(app).get("/share/api/images/missingNote/image.png");
+ expect(readsMimeTypes()).toBe(false);
+
+ await supertest(app).get("/share/").expect(200);
+ expect(readsMimeTypes()).toBe(true);
+ } finally {
+ getOption.mockRestore();
+ }
+ });
+
it("requests password for password-protected share", async () => {
await supertest(app)
.get("/share/YjlPRj2E9fOV")
diff --git a/apps/server/src/share/routes.ts b/apps/server/src/share/routes.ts
index 745f12607d..07c38c4444 100644
--- a/apps/server/src/share/routes.ts
+++ b/apps/server/src/share/routes.ts
@@ -1,4 +1,7 @@
-import { ensureShareHighlighting, getShareRoutes, handleShareRequest, type ShareReply, type ShareRequest } from "@triliumnext/core/src/share/index.js";
+import {
+ ensureShareHighlighting, getShareRoutes, handleShareRequest, SHARE_PAGE_PATHS, type ShareReply,
+ type ShareRequest
+} from "@triliumnext/core/src/share/index.js";
import type { Request, Response, Router } from "express";
import { registerShareProvider } from "./share_provider.js";
@@ -9,7 +12,9 @@ function register(router: Router) {
for (const route of getShareRoutes()) {
router.get(route.path, async (req, res) => {
- await ensureShareHighlighting();
+ if (SHARE_PAGE_PATHS.has(route.path)) {
+ await ensureShareHighlighting();
+ }
send(res, handleShareRequest(route, toShareRequest(req)));
});
}
diff --git a/apps/standalone/src/lightweight/browser_routes.ts b/apps/standalone/src/lightweight/browser_routes.ts
index 38e68744b7..4ef158b6b4 100644
--- a/apps/standalone/src/lightweight/browser_routes.ts
+++ b/apps/standalone/src/lightweight/browser_routes.ts
@@ -430,7 +430,9 @@ async function dispatchShare(path: ShareRoutePath, req: BrowserRequest) {
]);
registerShareProvider();
- await share.ensureShareHighlighting();
+ if (share.SHARE_PAGE_PATHS.has(path)) {
+ await share.ensureShareHighlighting();
+ }
/* v8 ignore next -- @preserve: BrowserRouter.dispatch always sets req.headers, so the ?? fallback is unreachable. */
const headers = req.headers ?? {};
diff --git a/packages/highlightjs/src/index.spec.ts b/packages/highlightjs/src/index.spec.ts
index c4a3617fc7..d2ec2be74c 100644
--- a/packages/highlightjs/src/index.spec.ts
+++ b/packages/highlightjs/src/index.spec.ts
@@ -56,6 +56,19 @@ describe("ensureMimeTypes", () => {
expect(highlightAuto(python).language).toBe("text-x-python");
});
+ it("syncMimeTypes unregisters a mime type that was disabled", async () => {
+ const { syncMimeTypes, getLanguage } = await freshModule();
+
+ await syncMimeTypes([ mime("text/x-python"), mime("application/json") ]);
+ await syncMimeTypes([ mime("text/x-python", false), mime("application/json") ]);
+
+ expect(getLanguage("text-x-python")).toBeUndefined();
+ expect(getLanguage("application-json")).toBeDefined();
+
+ await syncMimeTypes([ mime("text/x-python") ]);
+ expect(getLanguage("text-x-python")).toBeDefined();
+ });
+
it("remembers a mime type with no highlight.js definition as unsupported", async () => {
const { ensureMimeTypes, highlight } = await freshModule();
const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined);
diff --git a/packages/highlightjs/src/index.ts b/packages/highlightjs/src/index.ts
index 4d4e038c1f..8ffa63e02d 100644
--- a/packages/highlightjs/src/index.ts
+++ b/packages/highlightjs/src/index.ts
@@ -34,6 +34,22 @@ export async function ensureMimeTypes(mimeTypes: MimeType[]) {
}
}
+/**
+ * Makes the registered languages match `mimeTypes`: registers the enabled ones, like
+ * {@link ensureMimeTypes}, and unregisters the disabled ones that are registered.
+ */
+export async function syncMimeTypes(mimeTypes: MimeType[]) {
+ for (const mimeType of mimeTypes) {
+ const mime = normalizeMimeTypeForCKEditor(mimeType.mime);
+ if (!mimeType.enabled && registeredMimeTypes.has(mime)) {
+ hljs.unregisterLanguage(mime);
+ registeredMimeTypes.delete(mime);
+ }
+ }
+
+ await ensureMimeTypes(mimeTypes);
+}
+
export function highlight(code: string, options: HighlightOptions) {
if (unsupportedMimeTypes.has(options.language)) {
return null;
diff --git a/packages/trilium-core/src/share/content_renderer.spec.ts b/packages/trilium-core/src/share/content_renderer.spec.ts
index 44fc053ef0..3b078773ac 100644
--- a/packages/trilium-core/src/share/content_renderer.spec.ts
+++ b/packages/trilium-core/src/share/content_renderer.spec.ts
@@ -7,7 +7,10 @@ import options from "../services/options.js";
import * as sanitize from "../services/sanitizer.js";
import * as utils from "../services/utils/index.js";
import { buildShareNote, buildShareNotes } from "../test/shaca_mocking.js";
-import { ensureShareHighlighting, getContent, getMimeTypesForOption, readShareTemplate, renderCode, renderNoteContent, type Result, shouldSyntaxHighlight } from "./content_renderer.js";
+import {
+ ensureShareHighlighting, getContent, getMimeTypesForOption, readShareTemplate, renderCode,
+ renderNoteContent, type Result, shouldSyntaxHighlight
+} from "./content_renderer.js";
import type SNote from "./shaca/entities/snote.js";
import shaca from "./shaca/shaca.js";
import shareRoot from "./share_root.js";
@@ -286,14 +289,19 @@ describe("content_renderer", () => {
await ensureShareHighlighting();
const xml = "<t t-name="x"></t>";
// text-x-cobol is not enabled by default, so it is never registered.
- const languages = [ "text-x-python", "text-plain", "text-x-cobol", "text-x-trilium-auto" ];
+ const languages = [
+ "text-x-python", "text-plain", "text-x-cobol", "text-x-trilium-auto"
+ ];
const note = buildShareNote({
- content: languages.map((language) => `<pre><code class="language-${language}">${xml}</code></pre>`).join("")
+ content: languages
+ .map((lang) => `<pre><code class="language-${lang}">${xml}</code></pre>`)
+ .join("")
});
const result = getContent(note);
if (typeof result.content !== "string") throw new Error("expected string content");
- const [ python, plain, cobol, auto ] = parse(result.content, { blockTextElements: {} }).querySelectorAll("code");
+ const [ python, plain, cobol, auto ] = parse(result.content, { blockTextElements: {} })
+ .querySelectorAll("code");
expect(python.classList.contains("hljs")).toBe(true);
expect(python.innerHTML).toContain("hljs-string");
expect(python.innerHTML).not.toContain("hljs-tag");
@@ -308,7 +316,8 @@ describe("content_renderer", () => {
{ id: "pycode", type: "code", mime: "text/x-python", content: `<t t-name="x"></t>` }
]);
const note = buildShareNote({
- content: `<section class="include-note" data-note-id="pycode" data-box-size="medium">&nbsp;</section>`
+ content: '<section class="include-note" data-note-id="pycode" '
+ + 'data-box-size="medium">&nbsp;</section>'
});
const result = getContent(note);
@@ -729,18 +738,26 @@ describe("content_renderer", () => {
});
describe("ensureShareHighlighting", () => {
- it("registers once per value of codeNotesMimeTypes", async () => {
+ it("registers once per option value and drops a disabled language", async () => {
const getOption = vi.spyOn(options, "getOptionOrNull");
+ const pythonBlock = () => buildShareNote({
+ content: `<pre><code class="language-text-x-python">def x(): pass</code></pre>`
+ });
getOption.mockReturnValue(JSON.stringify([ "text/x-python" ]));
const first = ensureShareHighlighting();
expect(ensureShareHighlighting()).toBe(first);
await first;
+ expect(getContent(pythonBlock()).content).toContain("hljs-keyword");
getOption.mockReturnValue(JSON.stringify([ "text/x-go" ]));
- expect(ensureShareHighlighting()).not.toBe(first);
+ const second = ensureShareHighlighting();
+ expect(second).not.toBe(first);
+ await second;
+ expect(getContent(pythonBlock()).content).not.toContain("hljs");
getOption.mockRestore();
+ await ensureShareHighlighting();
});
});
diff --git a/packages/trilium-core/src/share/content_renderer.ts b/packages/trilium-core/src/share/content_renderer.ts
index 374bd02d5c..f2ebb3ee29 100644
--- a/packages/trilium-core/src/share/content_renderer.ts
+++ b/packages/trilium-core/src/share/content_renderer.ts
@@ -1,7 +1,10 @@
-import { extractYouTubeVideoId, isHttpUrl, MIME_TYPE_AUTO, type MimeType, MIME_TYPES_DICT, normalizeMimeTypeForCKEditor, safeLinkPreviewHref, safeLinkPreviewImageSrc } from "@triliumnext/commons";
+import {
+ extractYouTubeVideoId, isHttpUrl, MIME_TYPE_AUTO, type MimeType, MIME_TYPES_DICT,
+ normalizeMimeTypeForCKEditor, safeLinkPreviewHref, safeLinkPreviewImageSrc
+} from "@triliumnext/commons";
import { renderToHtml as renderMarkdownToHtml } from "@triliumnext/commons/src/lib/markdown_renderer.js";
import { renderSpreadsheetToHtml } from "@triliumnext/commons/src/lib/spreadsheet/render_to_html.js";
-import { ensureMimeTypes, getLanguage, highlight, highlightAuto } from "@triliumnext/highlightjs";
+import { getLanguage, highlight, highlightAuto, syncMimeTypes } from "@triliumnext/highlightjs";
import ejs from "ejs";
import escapeHtml from "escape-html";
import { t } from "i18next";
@@ -720,9 +723,9 @@ let registeredMimeTypesOption: string | null = null;
let pendingRegistration: Promise<void> | null = null;
/**
- * Registers the highlight.js languages enabled in the `codeNotesMimeTypes` option, which are the
- * only ones `highlightAuto` considers. The renderer is synchronous, so callers await this before
- * rendering a share page or a share-theme export.
+ * Registers the highlight.js languages enabled in the `codeNotesMimeTypes` option and unregisters
+ * the disabled ones, so `highlightAuto` considers only the enabled ones. The renderer is
+ * synchronous, so callers await this before rendering a share page or a share-theme export.
*/
export function ensureShareHighlighting(): Promise<void> {
const optionValue = options.getOptionOrNull("codeNotesMimeTypes");
@@ -732,7 +735,7 @@ export function ensureShareHighlighting(): Promise<void> {
registeredMimeTypesOption = optionValue;
pendingRegistration = Promise.resolve()
- .then(() => ensureMimeTypes(getMimeTypesForOption(optionValue)))
+ .then(() => syncMimeTypes(getMimeTypesForOption(optionValue)))
.catch((e: unknown) => {
getLog().error(`Unable to register the languages for syntax highlighting: ${e}`);
pendingRegistration = null;
@@ -769,7 +772,9 @@ export function renderCode(result: Result, mime?: string) {
// code note would explode into a pathological node-html-parser tree and hang the event
// loop (#9717). The <code> wrapper and its `language-*` class additionally let renderText
// apply syntax highlighting, bounded by shouldSyntaxHighlight().
- const languageClass = mime ? ` class="language-${escapeHtml(normalizeMimeTypeForCKEditor(mime))}"` : "";
+ const languageClass = mime
+ ? ` class="language-${escapeHtml(normalizeMimeTypeForCKEditor(mime))}"`
+ : "";
result.content = `<pre><code${languageClass}>${escapeHtml(result.content)}</code></pre>`;
}
}
diff --git a/packages/trilium-core/src/share/index.ts b/packages/trilium-core/src/share/index.ts
index 381124819e..a598e44046 100644
--- a/packages/trilium-core/src/share/index.ts
+++ b/packages/trilium-core/src/share/index.ts
@@ -6,9 +6,12 @@
* dynamic import, which only defers its cost — EJS, the share theme and the syntax highlighter —
* while nothing in the eager graph imports it.
*/
-export { assetUrlFragment, ensureShareHighlighting, readShareTemplate, renderNoteContent, renderNoteForExport } from "./content_renderer.js";
+export {
+ assetUrlFragment, ensureShareHighlighting, readShareTemplate, renderNoteContent,
+ renderNoteForExport
+} from "./content_renderer.js";
export { getShareRoute, getShareRoutes, handleShareRequest, isVisibleInShareTree, type ShareReply, type ShareRequest, type ShareRoute } from "./handlers.js";
-export { SHARE_ROUTE_PATHS, type ShareRoutePath } from "./route_paths.js";
+export { SHARE_PAGE_PATHS, SHARE_ROUTE_PATHS, type ShareRoutePath } from "./route_paths.js";
export { initShare, isShareReady, type ShareProvider, type ShareSql } from "./share_provider.js";
export { default as shareRoot } from "./share_root.js";
export { default as shaca } from "./shaca/shaca.js";
diff --git a/packages/trilium-core/src/share/route_paths.ts b/packages/trilium-core/src/share/route_paths.ts
index cf917697ab..3b51bd7ad0 100644
--- a/packages/trilium-core/src/share/route_paths.ts
+++ b/packages/trilium-core/src/share/route_paths.ts
@@ -20,3 +20,9 @@ export const SHARE_ROUTE_PATHS = [
] as const;
export type ShareRoutePath = (typeof SHARE_ROUTE_PATHS)[number];
+
+/** The share paths that can render a text or Markdown note, the only notes that highlight code. */
+export const SHARE_PAGE_PATHS: ReadonlySet<ShareRoutePath> = new Set([
+ "/share/",
+ "/share/:shareId"
+]);