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(share): share escapeHtml, enabled languages and the highlight limit
Elian Doran21211c438c6b
diff --git a/apps/client/src/services/mime_types.ts b/apps/client/src/services/mime_types.tsindex 96f62fbff0..81afd6152c 100644--- a/apps/client/src/services/mime_types.ts+++ b/apps/client/src/services/mime_types.ts@@ -1,4 +1,8 @@-import { normalizeMimeTypeForCKEditor, type MimeType, MIME_TYPE_AUTO, MIME_TYPE_TRILIUM_LOG, MIME_TYPES_DICT } from "@triliumnext/commons";+import {+ type MimeType, MIME_TYPE_AUTO, MIME_TYPE_TRILIUM_LOG, normalizeMimeTypeForCKEditor,+ resolveEnabledMimeTypes+} from "@triliumnext/commons";+import { t } from "./i18n.js";import options from "./options.js";@@ -11,13 +15,9 @@ const TRANSLATED_TITLES: Record<string, string> = {let mimeTypes: MimeType[] | null = null;function loadMimeTypes() {- mimeTypes = JSON.parse(JSON.stringify(MIME_TYPES_DICT)) as MimeType[]; // clone-- const enabledMimeTypes = options.getJson("codeNotesMimeTypes") || MIME_TYPES_DICT.filter((mt) => mt.default).map((mt) => mt.mime);+ mimeTypes = resolveEnabledMimeTypes(options.getJson("codeNotesMimeTypes"));for (const mt of mimeTypes) {- mt.enabled = enabledMimeTypes.includes(mt.mime) || mt.mime === "text/plain"; // text/plain is always enabled-const titleKey = TRANSLATED_TITLES[mt.mime];if (titleKey) {mt.title = t(titleKey);diff --git a/apps/client/src/services/syntax_highlight.spec.ts b/apps/client/src/services/syntax_highlight.spec.tsindex c79eb7ca99..07b9c2f874 100644--- a/apps/client/src/services/syntax_highlight.spec.ts+++ b/apps/client/src/services/syntax_highlight.spec.ts@@ -274,6 +274,20 @@ describe("syntax_highlight", () => {expect($a.html()).toBe("noresult");});+ it("leaves code beyond the size cutoff plain", async () => {+ const mod = await freshModule();+ const longCode = Array(501).fill("x").join("\n");+ const $a = $codeBlock(longCode, "text-x-csrc");+ await mod.applySingleBlockSyntaxHighlight($a, "text-x-csrc");+ const $b = $codeBlock(longCode, "text-x-trilium-auto");+ await mod.applySingleBlockSyntaxHighlight($b, "text-x-trilium-auto");++ expect(hl.highlight).not.toHaveBeenCalled();+ expect(hl.highlightAuto).not.toHaveBeenCalled();+ expect($a.text()).toBe(longCode);+ expect($b.text()).toBe(longCode);+ });+it("does not highlight when the mime type is empty", async () => {const mod = await freshModule();const $a = $codeBlock("nolang");diff --git a/apps/client/src/services/syntax_highlight.ts b/apps/client/src/services/syntax_highlight.tsindex e6b4ba228a..8b0355c85f 100644--- a/apps/client/src/services/syntax_highlight.ts+++ b/apps/client/src/services/syntax_highlight.ts@@ -1,4 +1,4 @@-import { MimeType } from "@triliumnext/commons";+import { MimeType, shouldSyntaxHighlight } from "@triliumnext/commons";// highlight.js is heavy and this module is reachable from the startup graph (note tooltips →// content renderer), so the library itself is only imported dynamically when highlighting runs.import type { AutoHighlightResult, HighlightResult, Theme } from "@triliumnext/highlightjs";@@ -130,6 +130,9 @@ export function applyInlineCodeCopy($inlineCode: JQuery<HTMLElement>) {export async function applySingleBlockSyntaxHighlight($codeBlock: JQuery<HTMLElement>, normalizedMimeType: string) {$codeBlock.parent().toggleClass("hljs");const text = $codeBlock.text();+ if (!shouldSyntaxHighlight(text)) {+ return;+ }const cached = getCachedHighlight(normalizedMimeType, text);if (cached !== undefined) {diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Developer-specific formatting/Code blocks.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Developer-specific formatting/Code blocks.htmlindex f464d9ac63..3bc2c06c61 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Developer-specific formatting/Code blocks.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Developer-specific formatting/Code blocks.html@@ -64,10 +64,11 @@highlighting.</li></ul><p>Note that when editing a text note, syntax highlighting is automatically- disabled if the code block is too big (somewhere around 500 lines). This- value is currently not configurable. For <a class="reference-link"- href="#root/_help_CoFPLs3dRlXc">Read-Only Notes</a>, this limitation is- not applied.</p>+ disabled if the code block is too big (somewhere around 500 lines). In <a+ class="reference-link" href="#root/_help_CoFPLs3dRlXc">Read-Only Notes</a>,+ in print and on a <a href="#root/_help_R9pX4DGra2Vt">shared page</a>, a+ code block of more than 500 lines or 50,000 characters is shown without+ syntax highlighting. These limits are not configurable.</p><p>In order to configure this new feature, a section has been added in <aclass="reference-link" href="#root/_help_4TIF1oA4VQRO">Options</a> → <em>Appearance</em> tocontrol the syntax highlighting. There the color scheme can be chosen,diff --git a/docs/User Guide/User Guide/Note Types/Text/Developer-specific formatting/Code blocks.md b/docs/User Guide/User Guide/Note Types/Text/Developer-specific formatting/Code blocks.mdindex c12402a4e3..baf8d45d9d 100644--- a/docs/User Guide/User Guide/Note Types/Text/Developer-specific formatting/Code blocks.md+++ b/docs/User Guide/User Guide/Note Types/Text/Developer-specific formatting/Code blocks.md@@ -36,7 +36,7 @@ Interaction:* When the language is set to _Auto-detected_ (by default), Trilium will try to identify the programming language (or similar) that corresponds to the given snippet of text and highlight it. Only the languages enabled in <a class="reference-link" href="../../../Basic%20Concepts%20and%20Features/UI%20Elements/Options.md">Options</a> → _Code Notes_ → _Available MIME types in the dropdown_ are considered. If this is problematic, consider changing the language of the code block manually.* When the language is set to _Plain text_, there will be no syntax highlighting.-Note that when editing a text note, syntax highlighting is automatically disabled if the code block is too big (somewhere around 500 lines). This value is currently not configurable. For <a class="reference-link" href="../../../Basic%20Concepts%20and%20Features/Notes/Read-Only%20Notes.md">Read-Only Notes</a>, this limitation is not applied.+Note that when editing a text note, syntax highlighting is automatically disabled if the code block is too big (somewhere around 500 lines). In <a class="reference-link" href="../../../Basic%20Concepts%20and%20Features/Notes/Read-Only%20Notes.md">Read-Only Notes</a>, in print and on a [shared page](../../../Advanced%20Usage/Sharing.md), a code block of more than 500 lines or 50,000 characters is shown without syntax highlighting. These limits are not configurable.In order to configure this new feature, a section has been added in <a class="reference-link" href="../../../Basic%20Concepts%20and%20Features/UI%20Elements/Options.md">Options</a> → _Appearance_ to control the syntax highlighting. There the color scheme can be chosen, from a builtin selection of themes from Highlight.js. _VS Code (Light)_ and _VS Code (Dark)_ use the same colors as the default themes of <a class="reference-link" href="../../Code.md">Code</a> notes, so a code block and a code note color the same code alike.diff --git a/packages/commons/src/lib/link_embed_markup.ts b/packages/commons/src/lib/link_embed_markup.tsindex b73febabde..3387642a38 100644--- a/packages/commons/src/lib/link_embed_markup.ts+++ b/packages/commons/src/lib/link_embed_markup.ts@@ -1,6 +1,7 @@import {extractYouTubeVideoId, safeHostname, safeLinkPreviewHref, safeLinkPreviewImageSrc} from "./link_embed.js";+import { escapeHtml } from "./utils.js";/** A link preview as the note stores it, in the `data-*` attributes of its element. */export interface LinkPreviewData {@@ -126,12 +127,3 @@ function renderPicture(src: string | null | undefined, className: string, size?:return `<img class="${className}" src="${escapeHtml(safeSrc)}" alt="" loading="lazy"`+ ` draggable="false"${sizeAttributes}>`;}--function escapeHtml(value: string) {- return value- .replaceAll("&", "&")- .replaceAll("<", "<")- .replaceAll(">", ">")- .replaceAll("\"", """)- .replaceAll("'", "'");-}diff --git a/packages/commons/src/lib/markdown_renderer.ts b/packages/commons/src/lib/markdown_renderer.tsindex 9ca8ec90e0..bfbc6f089f 100644--- a/packages/commons/src/lib/markdown_renderer.ts+++ b/packages/commons/src/lib/markdown_renderer.ts@@ -2,6 +2,7 @@ import { Marked, type MarkedOptions, Renderer, type Token, type Tokens } from "mimport markedFootnote from "marked-footnote";import { DEFAULT_TASK_STATES, type TaskStateDef } from "./task_states.js";+import { escapeHtml } from "./utils.js";type TaskListItem = Tokens.ListItem & { _taskState?: string };@@ -195,15 +196,6 @@ export interface RenderToHtmlOptions {obsidian?: boolean;}-function escapeHtml(str: string): string {- return str- .replace(/&/g, "&")- .replace(/</g, "<")- .replace(/>/g, ">")- .replace(/"/g, """)- .replace(/'/g, "'");-}-const NAMED_ENTITIES: Record<string, string> = {amp: "&",lt: "<",diff --git a/packages/commons/src/lib/marked_extensions.ts b/packages/commons/src/lib/marked_extensions.tsindex 0a827570f0..80959cca8d 100644--- a/packages/commons/src/lib/marked_extensions.ts+++ b/packages/commons/src/lib/marked_extensions.ts@@ -1,17 +1,6 @@import type { Token, TokenizerAndRendererExtension } from "marked";-/**- * Escapes HTML special characters to prevent XSS attacks.- * Used for both attribute values and text content.- */-function escapeHtml(str: string): string {- return str- .replace(/&/g, "&")- .replace(/</g, "<")- .replace(/>/g, ">")- .replace(/"/g, """)- .replace(/'/g, "'");-}+import { escapeHtml } from "./utils.js";export interface WikiLinkOptions {/** Format the href for the link. Defaults to `/${noteId}` */diff --git a/packages/commons/src/lib/mime_type.spec.ts b/packages/commons/src/lib/mime_type.spec.tsindex 9ca29bcd17..b2ad04bc79 100644--- a/packages/commons/src/lib/mime_type.spec.ts+++ b/packages/commons/src/lib/mime_type.spec.ts@@ -2,7 +2,7 @@ import { describe, expect, it } from "vitest";import {getMimeTypeFromFileName, getMimeTypeFromMarkdownName, MIME_TYPE_AUTO, MIME_TYPES_DICT,- normalizeMimeTypeForCKEditor+ normalizeMimeTypeForCKEditor, resolveEnabledMimeTypes, shouldSyntaxHighlight} from "./mime_type.js";describe("normalizeMimeTypeForCKEditor", () => {@@ -98,3 +98,37 @@ describe("getMimeTypeFromFileName", () => {.map(getMimeTypeFromFileName)).toEqual(Array(5).fill(undefined));});});++describe("resolveEnabledMimeTypes", () => {+ const enabledMimes = (enabled: readonly (string | null)[] | null | undefined) =>+ resolveEnabledMimeTypes(enabled).filter((mt) => mt.enabled).map((mt) => mt.mime);++ it("enables the listed MIME types plus text/plain, on copies of the dictionary", () => {+ expect(enabledMimes([ "text/x-python", null ])).toStrictEqual([ "text/plain", "text/x-python" ]);+ expect(enabledMimes([])).toStrictEqual([ "text/plain" ]);++ const mimeTypes = resolveEnabledMimeTypes([]);+ expect(mimeTypes).toHaveLength(MIME_TYPES_DICT.length);+ expect(mimeTypes[0]).not.toBe(MIME_TYPES_DICT[0]);+ });++ it("falls back to the default MIME types when nothing is configured", () => {+ for (const enabled of [ enabledMimes(null), enabledMimes(undefined) ]) {+ expect(enabled).toContain("text/x-python");+ expect(enabled).not.toContain("text/x-cobol");+ }+ });+});++describe("shouldSyntaxHighlight", () => {+ it("allows code up to 500 lines", () => {+ expect(shouldSyntaxHighlight("")).toBe(true);+ expect(shouldSyntaxHighlight(Array(500).fill("x").join("\n"))).toBe(true);+ expect(shouldSyntaxHighlight(Array(501).fill("x").join("\n"))).toBe(false);+ });++ it("allows code up to 50,000 characters, however few lines it has", () => {+ expect(shouldSyntaxHighlight("x".repeat(50_000))).toBe(true);+ expect(shouldSyntaxHighlight("x".repeat(50_001))).toBe(false);+ });+});diff --git a/packages/commons/src/lib/mime_type.ts b/packages/commons/src/lib/mime_type.tsindex 1c1b28c1bf..85f7c2d2d3 100644--- a/packages/commons/src/lib/mime_type.ts+++ b/packages/commons/src/lib/mime_type.ts@@ -221,6 +221,48 @@ const MIME_TYPES_DICT_RAW = [] as const satisfies readonly MimeTypeDefinition[];export const MIME_TYPES_DICT = Object.freeze(MIME_TYPES_DICT_RAW as readonly MimeTypeDefinition[]);+/**+ * Returns a copy of every entry in {@link MIME_TYPES_DICT}, enabled when `enabledMimes` lists it.+ * `enabledMimes` is the parsed `codeNotesMimeTypes` option; without it, the entries marked+ * `default` are enabled. `text/plain` is always enabled.+ */+export function resolveEnabledMimeTypes(+ enabledMimes: readonly (string | null)[] | null | undefined+): MimeType[] {+ const enabled = enabledMimes ?? MIME_TYPES_DICT.filter((mt) => mt.default).map((mt) => mt.mime);+ return MIME_TYPES_DICT.map((mt) => ({+ ...mt,+ enabled: enabled.includes(mt.mime) || mt.mime === "text/plain"+ }));+}++/** Code longer than this many lines is not syntax-highlighted. */+const HIGHLIGHT_MAX_LINE_COUNT = 500;++/** Code longer than this many characters is not syntax-highlighted, such as one minified line. */+const HIGHLIGHT_MAX_CHAR_COUNT = 50_000;++/**+ * Whether code is small enough to syntax-highlight when it is rendered. Highlighting, and+ * `highlightAuto()` most of all, grows with the size of the code and blocks the thread it runs+ * on, so code beyond {@link HIGHLIGHT_MAX_LINE_COUNT} lines or {@link HIGHLIGHT_MAX_CHAR_COUNT}+ * characters stays plain.+ */+export function shouldSyntaxHighlight(code: string) {+ if (code.length > HIGHLIGHT_MAX_CHAR_COUNT) {+ return false;+ }++ let lineCount = 1;+ let index = -1;+ while ((index = code.indexOf("\n", index + 1)) !== -1) {+ if (++lineCount > HIGHLIGHT_MAX_LINE_COUNT) {+ return false;+ }+ }+ return true;+}+let byMarkdownNameMappings: Record<string, MimeTypeDefinition> | null = null;export type MermaidMimeType = "text/vnd.mermaid" | "text/mermaid";diff --git a/packages/commons/src/lib/spreadsheet/render_to_html.ts b/packages/commons/src/lib/spreadsheet/render_to_html.tsindex 24234d1e6a..aa053418d3 100644--- a/packages/commons/src/lib/spreadsheet/render_to_html.ts+++ b/packages/commons/src/lib/spreadsheet/render_to_html.ts@@ -12,7 +12,7 @@import { format as formatNumfmt, formatColor as formatNumfmtColor } from "numfmt";-import { fnv1a } from "../utils.js";+import { escapeHtml, fnv1a } from "../utils.js";import {BorderStyle,type CellDocumentSegment,@@ -1271,17 +1271,4 @@ function resolvePatternColor(style: IStyleData | null, cell: ICellData | undefin}}-function escapeHtml(text: string): string {- if (!ESCAPABLE.test(text)) return text;-- return text- .replace(/&/g, "&")- .replace(/</g, "<")- .replace(/>/g, ">")- .replace(/"/g, """)- .replace(/'/g, "'");-}--const ESCAPABLE = /[&<>"']/;-// #endregiondiff --git a/packages/commons/src/lib/utils.spec.ts b/packages/commons/src/lib/utils.spec.tsindex 5ca0f58751..ac89ee5ecf 100644--- a/packages/commons/src/lib/utils.spec.ts+++ b/packages/commons/src/lib/utils.spec.ts@@ -1,4 +1,4 @@-import { deferred, fnv1a, formatLogMessage } from "./utils.js";+import { deferred, escapeHtml, fnv1a, formatLogMessage } from "./utils.js";import { describe, expect, it } from "vitest";describe("#deferred", () => {@@ -103,3 +103,12 @@ describe("#fnv1a", () => {}});});++describe("#escapeHtml", () => {+ it("escapes the characters that end text or a quoted attribute, ampersands first", () => {+ expect(escapeHtml(`<a href="x">Tom & 'Jerry' &</a>`))+ .toBe("<a href="x">Tom & 'Jerry' &amp;</a>");+ expect(escapeHtml("plain text = 1/2")).toBe("plain text = 1/2");+ expect(escapeHtml("")).toBe("");+ });+});diff --git a/packages/commons/src/lib/utils.ts b/packages/commons/src/lib/utils.tsindex 32dfcbb5b3..4494d55b9d 100644--- a/packages/commons/src/lib/utils.ts+++ b/packages/commons/src/lib/utils.ts@@ -78,3 +78,16 @@ export function fnv1a(value: string): number {return hash >>> 0;}++/**+ * Escapes `&`, `<`, `>`, `"` and `'`, so that the value can go into HTML text or a quoted+ * attribute.+ */+export function escapeHtml(value: string): string {+ return value+ .replaceAll("&", "&")+ .replaceAll("<", "<")+ .replaceAll(">", ">")+ .replaceAll("\"", """)+ .replaceAll("'", "'");+}diff --git a/packages/share-theme/src/page/search.spec.ts b/packages/share-theme/src/page/search.spec.tsindex 3f026e6ff4..cb83eda9da 100644--- a/packages/share-theme/src/page/search.spec.ts+++ b/packages/share-theme/src/page/search.spec.ts@@ -1,27 +1,7 @@import type { FuseResultMatch } from "fuse.js";import { describe, expect, it } from "vitest";-import { buildStaticSnippet, escapeHtml } from "./search.js";--describe("escapeHtml", () => {- it("escapes the five HTML special characters", () => {- expect(escapeHtml("&")).toBe("&");- expect(escapeHtml("<")).toBe("<");- expect(escapeHtml(">")).toBe(">");- expect(escapeHtml("\"")).toBe(""");- expect(escapeHtml("'")).toBe("'");- });-- it("escapes every occurrence in a mixed string", () => {- expect(escapeHtml(`<script>alert("x & 'y'")</script>`))- .toBe("<script>alert("x & 'y'")</script>");- });-- it("returns the input unchanged when nothing needs escaping", () => {- expect(escapeHtml("just plain text 123")).toBe("just plain text 123");- expect(escapeHtml("")).toBe("");- });-});+import { buildStaticSnippet } from "./search.js";describe("buildStaticSnippet", () => {const contentMatch = (...indices: [number, number][]): FuseResultMatch => ({diff --git a/packages/share-theme/src/page/search.ts b/packages/share-theme/src/page/search.tsindex 41bb3c4879..00a1d44b23 100644--- a/packages/share-theme/src/page/search.ts+++ b/packages/share-theme/src/page/search.ts@@ -1,7 +1,9 @@+import { escapeHtml } from "@triliumnext/commons/src/lib/utils.js";+import type { default as Fuse, FuseResultMatch } from "fuse.js";+import debounce from "../common/debounce.js";import parents from "../common/parents.js";import parseHTML from "../common/parsehtml.js";-import type { default as Fuse, FuseResultMatch } from "fuse.js";import "./search.css";let fuseInstance: Fuse<SearchResult> | null = null;@@ -76,19 +78,6 @@ export default function setupSearch() {});}-const HTML_ESCAPE_MAP: Record<string, string> = {- "&": "&",- "<": "<",- ">": ">",- "\"": """,- "'": "'"-};--/** Escape user-supplied/match text before injecting into innerHTML. */-export function escapeHtml(s: string): string {- return s.replace(/[&<>"']/g, (c) => HTML_ESCAPE_MAP[c]);-}-/*** Build a content snippet around the first Fuse match for the static-export search index.* Returns an HTML string with the matched ranges wrapped in <b>...</b>.diff --git a/packages/trilium-core/src/share/content_renderer.spec.ts b/packages/trilium-core/src/share/content_renderer.spec.tsindex 8ea4172fb3..6215a65cc9 100644--- a/packages/trilium-core/src/share/content_renderer.spec.ts+++ b/packages/trilium-core/src/share/content_renderer.spec.ts@@ -8,8 +8,8 @@ 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+ ensureShareHighlighting, getContent, readShareTemplate, renderCode, renderNoteContent,+ type Result} from "./content_renderer.js";import type SNote from "./shaca/entities/snote.js";import shaca from "./shaca/shaca.js";@@ -857,24 +857,6 @@ describe("content_renderer", () => {});});- describe("shouldSyntaxHighlight", () => {- it("allows small code blocks", () => {- expect(shouldSyntaxHighlight("a\nb\nc")).toBe(true);- expect(shouldSyntaxHighlight("")).toBe(true);- });-- it("rejects code blocks beyond the line limit", () => {- expect(shouldSyntaxHighlight(Array(500).fill("x").join("\n"))).toBe(true);- expect(shouldSyntaxHighlight(Array(501).fill("x").join("\n"))).toBe(false);- });-- it("rejects a single huge line that stays under the line limit", () => {- // No newlines, so the line check never trips — the character ceiling must catch it.- expect(shouldSyntaxHighlight("x".repeat(50_000))).toBe(true);- expect(shouldSyntaxHighlight("x".repeat(50_001))).toBe(false);- });- });-describe("ensureShareHighlighting", () => {it("registers once per option value and drops a disabled language", async () => {const getOption = vi.spyOn(options, "getOptionOrNull");@@ -899,23 +881,6 @@ describe("content_renderer", () => {});});- describe("getMimeTypesForOption", () => {- const enabledMimes = (optionValue: string | null) => getMimeTypesForOption(optionValue)- .filter((mt) => mt.enabled)- .map((mt) => mt.mime);-- it("enables the listed MIME types plus text/plain", () => {- expect(enabledMimes(JSON.stringify([ "text/x-python", null ])))- .toStrictEqual([ "text/plain", "text/x-python" ]);- });-- it("falls back to the default MIME types when the option is missing", () => {- const enabled = enabledMimes(null);- expect(enabled).toContain("text/x-python");- expect(enabled).not.toContain("text/x-cobol");- });- });-describe("Share index", () => {it("points each index entry at the child's shareId, whatever characters it carries", () => {buildShareNote({diff --git a/packages/trilium-core/src/share/content_renderer.ts b/packages/trilium-core/src/share/content_renderer.tsindex 44b5344bc5..657f3fd855 100644--- a/packages/trilium-core/src/share/content_renderer.ts+++ b/packages/trilium-core/src/share/content_renderer.ts@@ -1,8 +1,8 @@import {getAttachmentEmbedHref, getEmbedKey, getNestedEmbedOptions, getNoteEmbedHref, isHttpUrl,- isImageAttachmentRole, MIME_TYPE_AUTO, type MimeType, MIME_TYPES_DICT,- normalizeMimeTypeForCKEditor, readLinkPreviewData, renderLinkEmbedHtml, renderLinkMentionHtml,- resolveContentEmbed, sliceToBlockReference+ isImageAttachmentRole, MIME_TYPE_AUTO, normalizeMimeTypeForCKEditor, readLinkPreviewData,+ renderLinkEmbedHtml, renderLinkMentionHtml, resolveContentEmbed, resolveEnabledMimeTypes,+ shouldSyntaxHighlight, sliceToBlockReference} 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";@@ -35,21 +35,6 @@ import shareRoot from "./share_root.js";*/export const assetUrlFragment = `assets/v${appInfo.appVersion}`;-/**- * Maximum number of lines a code block may have before server-side syntax highlighting is skipped.- * Mirrors the editor's per-block cutoff (HIGHLIGHT_MAX_BLOCK_COUNT in the ckeditor5 syntax- * highlighting plugin); beyond it `highlightAuto` is too slow and would block the event loop on- * large shared/embedded code notes (#9717).- */-const HIGHLIGHT_MAX_LINE_COUNT = 500;--/**- * Maximum number of characters a code block may have before server-side syntax highlighting is- * skipped. The line-count cutoff alone does not protect against a single very long line (e.g.- * minified code), so a separate character ceiling guards `highlightAuto`'s size-driven cost.- */-const HIGHLIGHT_MAX_CHAR_COUNT = 50_000;-const PLAIN_TEXT_LANGUAGE = normalizeMimeTypeForCKEditor("text/plain");/**@@ -649,27 +634,6 @@ function renderMarkdown(result: Result, note: SNote | BNote) {result.content = document.innerHTML;}-/**- * Whether a code block is small enough to syntax-highlight server-side. Highlighting (especially- * `highlightAuto`, which probes every registered language) scales with content size and would block- * the single Node event loop on very large code, so blocks beyond {@link HIGHLIGHT_MAX_LINE_COUNT}- * lines or {@link HIGHLIGHT_MAX_CHAR_COUNT} characters are left unhighlighted.- */-export function shouldSyntaxHighlight(code: string) {- if (code.length > HIGHLIGHT_MAX_CHAR_COUNT) {- return false;- }-- let lineCount = 1;- let index = -1;- while ((index = code.indexOf("\n", index + 1)) !== -1) {- if (++lineCount > HIGHLIGHT_MAX_LINE_COUNT) {- return false;- }- }- return true;-}-/*** Highlights a `<pre><code>` block in place, in the language its `language-*` class names. A block* without one, or set to auto-detect, goes through `highlightAuto`. Plain text and a language that@@ -713,7 +677,10 @@ export function ensureShareHighlighting(): Promise<void> {registeredMimeTypesOption = optionValue;pendingRegistration = Promise.resolve()- .then(() => syncMimeTypes(getMimeTypesForOption(optionValue)))+ .then(() => {+ const enabledMimes = optionValue ? JSON.parse(optionValue) : null;+ return syncMimeTypes(resolveEnabledMimeTypes(enabledMimes));+ }).catch((e: unknown) => {getLog().error(`Unable to register the languages for syntax highlighting: ${e}`);pendingRegistration = null;@@ -721,22 +688,6 @@ export function ensureShareHighlighting(): Promise<void> {return pendingRegistration;}-/**- * Returns every MIME type in `MIME_TYPES_DICT`, enabled when the `codeNotesMimeTypes` option value- * lists it. Mirrors `getMimeTypes()` in the client: a missing option falls back to the defaults,- * and `text/plain` is always enabled.- */-export function getMimeTypesForOption(optionValue: string | null): MimeType[] {- const enabledMimes: (string | null)[] = optionValue- ? JSON.parse(optionValue)- : MIME_TYPES_DICT.filter((mt) => mt.default).map((mt) => mt.mime);-- return MIME_TYPES_DICT.map((mt) => ({- ...mt,- enabled: enabledMimes.includes(mt.mime) || mt.mime === "text/plain"- }));-}-/*** Renders a code note.*/