Skip to content

AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.

fix(shared): parse long Markdown notes without blocking the server

tianma-if314d3109176a
diff --git a/packages/shared/src/content.ts b/packages/shared/src/content.ts
index 60c94aa0..174ba3be 100644
--- a/packages/shared/src/content.ts
+++ b/packages/shared/src/content.ts
@@ -17,6 +17,7 @@ import { NEW_IMAGE_WIDTH_PERCENT, parseImageWidth } from "./image-display";
import { IMAGE_GALLERY_NODE_TYPE, groupConsecutiveImagesIntoGalleries, normalizeImageGalleries } from "./image-gallery";
import { EMPTY_EXTERNAL_LINK_NODE_TYPE } from "./empty-external-link";
import { FRONT_MATTER_LANGUAGE, createFrontMatterNode, getFrontMatterSource, splitMarkdownFrontMatter } from "./front-matter";
+import { splitMarkdownParseChunks } from "./markdown-block-start";
export { PluginEmbed, PLUGIN_EMBED_NODE_TYPE, pluginEmbedToMarkdown, normalizePluginEmbedAttributes } from "./plugin-embed";
export type { PluginEmbedAttributes } from "./plugin-embed";
@@ -146,6 +147,16 @@ const withDefaultImageWidths = (node: TiptapNode): TiptapNode => {
return { ...next, attrs: { ...next.attrs, width: NEW_IMAGE_WIDTH_PERCENT } };
};
+// Long notes are split into pieces. marked otherwise copies the rest of the
+// note after every paragraph, and that copy blocks the single-threaded server.
+const parseMarkdownBody = (markdown: string): TiptapNode[] => {
+ const chunks = splitMarkdownParseChunks(markdown);
+ if (chunks.length <= 1) {
+ return (markdownManager.parse(markdown) as TiptapDoc).content ?? [];
+ }
+ return chunks.flatMap((chunk) => (markdownManager.parse(chunk) as TiptapDoc).content ?? []);
+};
+
export const markdownToDoc = (markdown: string): TiptapDoc => {
const normalized = markdown.replace(/\r\n?/g, "\n");
if (!normalized) {
@@ -153,12 +164,12 @@ export const markdownToDoc = (markdown: string): TiptapDoc => {
}
const header = splitMarkdownFrontMatter(normalized);
- const parsed = markdownManager.parse(expandExtraBlankLinesForParse(header?.body ?? normalized)) as TiptapDoc;
+ const content = parseMarkdownBody(expandExtraBlankLinesForParse(header?.body ?? normalized));
return {
- ...parsed,
+ type: "doc",
content: [...(header ? [createFrontMatterNode(header.source)] : []),
- ...groupConsecutiveImagesIntoGalleries(parsed.content.map(withDefaultImageWidths)),
- ...(header && !parsed.content.length ? [{ type: "paragraph" }] : [])],
+ ...groupConsecutiveImagesIntoGalleries(content.map(withDefaultImageWidths)),
+ ...(header && !content.length ? [{ type: "paragraph" }] : [])],
};
};
diff --git a/packages/shared/src/details.ts b/packages/shared/src/details.ts
index 421124fa..a9eed081 100644
--- a/packages/shared/src/details.ts
+++ b/packages/shared/src/details.ts
@@ -1,6 +1,7 @@
import type { JSONContent, MarkdownParseHelpers, MarkdownRendererHelpers, MarkdownToken } from "@tiptap/core";
import { Details, DetailsContent, DetailsSummary } from "@tiptap/extension-details";
import { resolveAttachmentKind, resolveVideoMimeType } from "./attachment-kind";
+import { openBlockSource } from "./markdown-block-start";
import { FILE_ATTACHMENT_NODE_TYPE } from "./file-attachment";
import { parseImageWidth } from "./image-display";
import { alignedImageToHtml, parseImageAlignment, type ImageAlignment } from "./image-alignment";
@@ -525,7 +526,7 @@ export const EdgeEverDetails = Details.extend({
name: DETAILS_NODE_TYPE,
level: "block",
start(source: string) {
- const match = /<details\b/i.exec(source);
+ const match = /<details\b/i.exec(openBlockSource(source));
return match ? match.index : -1;
},
tokenize(source: string, _tokens, lexer) {
diff --git a/packages/shared/src/image-alignment.ts b/packages/shared/src/image-alignment.ts
index a0c83f17..b9398af9 100644
--- a/packages/shared/src/image-alignment.ts
+++ b/packages/shared/src/image-alignment.ts
@@ -1,6 +1,7 @@
import { Extension, type JSONContent } from "@tiptap/core";
import Image from "@tiptap/extension-image";
import { parseImageWidth } from "./image-display";
+import { openBlockSource } from "./markdown-block-start";
export const IMAGE_ALIGNMENTS = ["left", "center", "right"] as const;
export type ImageAlignment = (typeof IMAGE_ALIGNMENTS)[number];
@@ -104,7 +105,7 @@ export const EdgeEverImage = Image.extend({
markdownTokenizer: {
name: "image",
level: "block",
- start: (source) => source.search(/<img\b/i),
+ start: (source) => openBlockSource(source).search(/<img\b/i),
tokenize(source) {
const match = /^<img\b(?:[^"'>]|"[^"]*"|'[^']*')*\/?>[ \t]*(?:\n|$)/i.exec(source);
if (!match) return undefined;
diff --git a/packages/shared/src/image-gallery.ts b/packages/shared/src/image-gallery.ts
index 80776813..8af7b6fd 100644
--- a/packages/shared/src/image-gallery.ts
+++ b/packages/shared/src/image-gallery.ts
@@ -1,4 +1,5 @@
import { mergeAttributes, Node } from "@tiptap/core";
+import { openBlockSource } from "./markdown-block-start";
import type { TiptapDoc, TiptapNode, TiptapTextNode } from "./content";
import { parseImageAlignment } from "./image-alignment";
@@ -92,7 +93,7 @@ export const ImageGallery = Node.create({
name: IMAGE_GALLERY_NODE_TYPE,
level: "block",
start(source: string) {
- return source.indexOf("<!-- edgeever:image-gallery ");
+ return openBlockSource(source).indexOf("<!-- edgeever:image-gallery ");
},
tokenize(source: string, _tokens, lexer) {
const match = /^<!-- edgeever:image-gallery fit=(width|height) layout=(auto|1|2|3) -->\s*\n([\s\S]*?)\n<!-- \/edgeever:image-gallery -->/.exec(source);
diff --git a/packages/shared/src/markdown-block-start.test.mjs b/packages/shared/src/markdown-block-start.test.mjs
new file mode 100644
index 00000000..259b8447
--- /dev/null
+++ b/packages/shared/src/markdown-block-start.test.mjs
@@ -0,0 +1,79 @@
+import { describe, expect, test } from "bun:test";
+import { markdownToDoc } from "./content.ts";
+import { openBlockSource, splitMarkdownParseChunks } from "./markdown-block-start.ts";
+
+const paragraph = "分析 `code span` 与 [link](https://example.com/a) 以及 $x_1$ 价格 $12.50 的段落,"
+ + "附数组写法 arr[0] 与 arr[1] 的说明。";
+
+describe("open block marker scan", () => {
+ test("keeps a marker in the current paragraph and ignores the next block", () => {
+ expect(openBlockSource("See $$\nx^2\n$$")).toBe("See $$\nx^2\n$$");
+ expect(openBlockSource("See\n\n$$\nx^2\n$$").includes("$$")).toBe(false);
+ expect(openBlockSource("See\n \n$$\nx^2")).toBe("See");
+ });
+
+ test("display math on the next line still interrupts the paragraph", () => {
+ const doc = markdownToDoc("See\n$$\nx^2\n$$");
+ expect(doc.content.map((node) => node.type)).toEqual(["paragraph", "blockMath"]);
+ expect(doc.content[1]).toEqual({ type: "blockMath", attrs: { latex: "x^2" } });
+ });
+
+ test("splits plain paragraphs and keeps containers intact", () => {
+ expect(splitMarkdownParseChunks("Alpha.\n\nBeta.", 1)).toEqual(["Alpha.", "\nBeta."]);
+ expect(splitMarkdownParseChunks("Alpha.\n \nBeta.", 1)).toEqual(["Alpha.", " \nBeta."]);
+ expect(splitMarkdownParseChunks("Alpha.\n\n\n\nBeta.", 1)).toEqual(["Alpha.", "\n\n\nBeta."]);
+ expect(splitMarkdownParseChunks("See [name][id]\n\n[id]: https://example.com", 1)).toEqual([
+ "See [name][id]\n\n[id]: https://example.com",
+ ]);
+ expect(splitMarkdownParseChunks("- a\n\n- b", 1)).toEqual(["- a\n\n- b"]);
+ expect(splitMarkdownParseChunks("> a\n>\n> b", 1)).toEqual(["> a\n>\n> b"]);
+ expect(splitMarkdownParseChunks("```js\nconst a = 1;\n\nconst b = 2;\n```", 1)).toEqual([
+ "```js\nconst a = 1;\n\nconst b = 2;\n```",
+ ]);
+ expect(splitMarkdownParseChunks("$$\nx\n\ny\n$$", 1)).toEqual(["$$\nx\n\ny\n$$"]);
+ expect(splitMarkdownParseChunks("<details>\n<summary>T</summary>\n\nbody\n\n</details>", 1)).toEqual([
+ "<details>\n<summary>T</summary>\n\nbody\n\n</details>",
+ ]);
+ });
+
+ test("keeps empty paragraphs when a long note is parsed in pieces", () => {
+ const count = 500;
+ const doc = markdownToDoc("Alpha.\n\n\n\n".repeat(count));
+ const empties = (count - 1) * 2 + 3;
+ expect(doc.content.filter((node) => node.content?.[0]?.text === "Alpha.")).toHaveLength(count);
+ expect(doc.content.filter((node) => node.type === "paragraph" && !node.content?.length)).toHaveLength(empties);
+ });
+
+ test("a long loose list stays one list", () => {
+ const items = Array.from({ length: 80 }, (_, index) => `- item ${index} ${"word ".repeat(8)}`.trimEnd());
+ const doc = markdownToDoc(items.join("\n\n"));
+ expect(doc.content).toHaveLength(1);
+ expect(doc.content[0]?.type).toBe("bulletList");
+ expect(doc.content[0]?.content).toHaveLength(80);
+ });
+
+ test("a fence and display math keep internal blank lines after a long preface", () => {
+ const preface = `${paragraph}\n\n`.repeat(80);
+ const doc = markdownToDoc(`${preface}\`\`\`js\nconst a = 1;\n\nconst b = 2;\n\`\`\`\n\nAfter.\n\n$$\nx\n\ny\n$$`);
+ const code = doc.content.find((node) => node.type === "codeBlock");
+ expect(code?.content?.[0]).toMatchObject({ type: "text", text: "const a = 1;\n\nconst b = 2;" });
+ expect(doc.content.at(-1)).toEqual({ type: "blockMath", attrs: { latex: "x\n\ny" } });
+ expect(doc.content.at(-2)?.content?.[0]).toMatchObject({ type: "text", text: "After." });
+ });
+
+ test("parses a long note of short paragraphs in linear time", () => {
+ let body = "";
+ while (Buffer.byteLength(body) < 256 * 1024) body += `${paragraph}\n\n`;
+ body += "$$\nx^2\n$$";
+
+ const started = performance.now();
+ const doc = markdownToDoc(body);
+ const elapsed = performance.now() - started;
+
+ expect(elapsed).toBeLessThan(2000);
+ expect(doc.content.at(-1)).toEqual({ type: "blockMath", attrs: { latex: "x^2" } });
+ expect(doc.content[0]?.content?.some((node) => node.type === "inlineMath")).toBe(true);
+ expect(JSON.stringify(doc.content[0])).toContain("12.50");
+ expect(doc.content.filter((node) => node.type === "paragraph").length).toBeGreaterThan(1000);
+ });
+});
diff --git a/packages/shared/src/markdown-block-start.ts b/packages/shared/src/markdown-block-start.ts
new file mode 100644
index 00000000..4157365f
--- /dev/null
+++ b/packages/shared/src/markdown-block-start.ts
@@ -0,0 +1,167 @@
+/**
+ * marked copies the entire remaining note after every paragraph when a block
+ * tokenizer registers `start`. Searching only the open paragraph keeps an
+ * interrupt inside that paragraph from walking the rest of the note.
+ */
+const OPEN_PARAGRAPH_END = /\n[ ]*\n/;
+
+export const openBlockSource = (source: string): string => {
+ const boundary = OPEN_PARAGRAPH_END.exec(source);
+ if (!boundary) return source;
+ return source.slice(0, boundary.index);
+};
+
+/**
+ * Plain paragraphs above this size are parsed separately. marked's copy of the
+ * remaining note then stays inside one piece instead of growing with the note.
+ */
+const PARSE_CHUNK_CHAR_LIMIT = 4096;
+
+const FENCE_LINE = /^[ ]{0,3}(`{3,}|~{3,})(.*)$/;
+const FENCE_CLOSE = /^[ ]{0,3}(`{3,}|~{3,})[ ]*$/;
+const LIST_LINE = /^[ ]{0,3}(?:[-*+]|\d{1,9}[.)])([ \t]|$)/;
+const QUOTE_LINE = /^[ ]{0,3}>/;
+const INDENTED_LINE = /^(?:[ ]{4}|\t)\S/;
+const TABLE_LINE = /^[ ]{0,3}\|/;
+const REFERENCE_DEFINITION = /^[ ]{0,3}\[[^\]\n]+\]:/;
+
+type FenceState = { char: string; length: number };
+type LineSpan = { text: string; newline: number };
+type ChunkBoundary = { omitStart: number; resume: number };
+
+const isBlankLine = (line: string) => line.trim() === "";
+
+/** A line that can sit on either side of a chunk boundary without joining a container. */
+const isChunkAnchor = (line: string) =>
+ !isBlankLine(line)
+ && !LIST_LINE.test(line)
+ && !QUOTE_LINE.test(line)
+ && !INDENTED_LINE.test(line)
+ && !TABLE_LINE.test(line)
+ && !REFERENCE_DEFINITION.test(line);
+
+const lineSpans = (markdown: string): LineSpan[] => {
+ const lines: LineSpan[] = [];
+ let start = 0;
+ for (let index = 0; index <= markdown.length; index += 1) {
+ if (index !== markdown.length && markdown[index] !== "\n") continue;
+ lines.push({ text: markdown.slice(start, index), newline: index });
+ start = index + 1;
+ }
+ return lines;
+};
+
+const dollarPairs = (line: string) => line.split("$$").length - 1;
+
+/**
+ * Indexes of paragraph separators (`\n\n`) that can be omitted between parse
+ * chunks. Lists, quotes, tables, fences, display math, galleries, and details
+ * stay in one piece.
+ */
+const paragraphChunkBoundaries = (markdown: string): ChunkBoundary[] => {
+ const lines = lineSpans(markdown);
+ const boundaries: ChunkBoundary[] = [];
+ let fence: FenceState | null = null;
+ let math = false;
+ let gallery = false;
+ let details = 0;
+
+ for (let index = 0; index < lines.length; index += 1) {
+ const line = lines[index]?.text ?? "";
+ const protectedRegion = Boolean(fence || math || gallery || details > 0);
+
+ if (!protectedRegion && index > 0 && isBlankLine(line)) {
+ const previous = lines[index - 1]?.text ?? "";
+ if (!isBlankLine(previous) && isChunkAnchor(previous)) {
+ let runEnd = index;
+ while (runEnd + 1 < lines.length && isBlankLine(lines[runEnd + 1]?.text ?? "")) runEnd += 1;
+ const next = lines[runEnd + 1]?.text ?? "";
+ const omitStart = lines[index - 1]?.newline ?? -1;
+ if (isChunkAnchor(next) && omitStart >= 0) {
+ // Drop the first newline. The rest of the run stays with the next
+ // piece, which keeps the same empty paragraphs as one parse.
+ boundaries.push({ omitStart, resume: omitStart + 1 });
+ }
+ index = runEnd;
+ }
+ }
+
+ if (fence) {
+ const close = FENCE_CLOSE.exec(line);
+ if (close?.[1] && close[1][0] === fence.char && close[1].length >= fence.length) fence = null;
+ continue;
+ }
+ if (math) {
+ if (dollarPairs(line) % 2 === 1) math = false;
+ continue;
+ }
+ if (gallery) {
+ if (line.includes("<!-- /edgeever:image-gallery -->")) gallery = false;
+ continue;
+ }
+ if (isBlankLine(line)) continue;
+
+ const openedFence = FENCE_LINE.exec(line);
+ if (openedFence?.[1]) {
+ fence = { char: openedFence[1][0] ?? "`", length: openedFence[1].length };
+ continue;
+ }
+ if (dollarPairs(line) % 2 === 1) {
+ math = true;
+ continue;
+ }
+ if (line.includes("<!-- edgeever:image-gallery ") && !line.includes("<!-- /edgeever:image-gallery -->")) {
+ gallery = true;
+ }
+ const opened = line.match(/<details\b/gi)?.length ?? 0;
+ const closed = line.match(/<\/details\b/gi)?.length ?? 0;
+ details = Math.max(0, details + opened - closed);
+ }
+
+ return boundaries;
+};
+
+/** Split a long note into parse pieces. Short notes and unsplittable blocks stay intact. */
+export const splitMarkdownParseChunks = (
+ markdown: string,
+ maxChars = PARSE_CHUNK_CHAR_LIMIT,
+): string[] => {
+ if (markdown.length <= maxChars) return [markdown];
+
+ const boundaries = paragraphChunkBoundaries(markdown);
+ if (boundaries.length === 0) return [markdown];
+
+ const pieces: Array<{ start: number; end: number }> = [];
+ let cursor = 0;
+ for (const boundary of boundaries) {
+ pieces.push({ start: cursor, end: boundary.omitStart });
+ cursor = boundary.resume;
+ }
+ pieces.push({ start: cursor, end: markdown.length });
+
+ const chunks: string[] = [];
+ let groupStart = pieces[0]?.start ?? 0;
+ let groupEnd = pieces[0]?.end ?? 0;
+ let groupSize = groupEnd - groupStart;
+
+ const flush = () => {
+ if (groupEnd <= groupStart && chunks.length > 0) return;
+ chunks.push(markdown.slice(groupStart, groupEnd));
+ };
+
+ for (let index = 1; index < pieces.length; index += 1) {
+ const piece = pieces[index];
+ if (!piece) continue;
+ if (groupSize > 0 && piece.end - groupStart > maxChars) {
+ flush();
+ groupStart = piece.start;
+ groupEnd = piece.end;
+ groupSize = piece.end - piece.start;
+ continue;
+ }
+ groupEnd = piece.end;
+ groupSize = groupEnd - groupStart;
+ }
+ flush();
+ return chunks.filter((chunk) => chunk.length > 0);
+};
diff --git a/packages/shared/src/mathematics-markdown.ts b/packages/shared/src/mathematics-markdown.ts
index b457e5cc..79cb8b4b 100644
--- a/packages/shared/src/mathematics-markdown.ts
+++ b/packages/shared/src/mathematics-markdown.ts
@@ -1,4 +1,5 @@
import { Extension, mergeAttributes, Node } from "@tiptap/core";
+import { openBlockSource } from "./markdown-block-start";
export const BLOCK_MATH_NODE_TYPE = "blockMath" as const;
export const INLINE_MATH_NODE_TYPE = "inlineMath" as const;
@@ -152,7 +153,7 @@ export const edgeEverInlineMathMarkdownTokenizer = {
export const edgeEverBlockMathMarkdownTokenizer = {
name: BLOCK_MATH_NODE_TYPE,
level: "block" as const,
- start: (source: string) => source.indexOf("$$"),
+ start: (source: string) => openBlockSource(source).indexOf("$$"),
tokenize: (source: string) => {
if (!source.startsWith("$$") || source.startsWith("$$$")) {
return undefined;
diff --git a/packages/shared/src/merge-divider.ts b/packages/shared/src/merge-divider.ts
index 6546f97f..20babd04 100644
--- a/packages/shared/src/merge-divider.ts
+++ b/packages/shared/src/merge-divider.ts
@@ -1,4 +1,5 @@
import { mergeAttributes, Node } from "@tiptap/core";
+import { openBlockSource } from "./markdown-block-start";
import type { TiptapDoc, TiptapNode } from "./content";
/** TipTap / ProseMirror node type for note-merge section boundaries. */
@@ -48,7 +49,7 @@ export const MergeDivider = Node.create({
name: MERGE_DIVIDER_NODE_TYPE,
level: "block",
start(src: string) {
- return src.indexOf("<!-- edgeever:merge-divider -->");
+ return openBlockSource(src).indexOf("<!-- edgeever:merge-divider -->");
},
tokenize(src: string) {
const match = MERGE_DIVIDER_TOKENIZER.exec(src);
diff --git a/packages/shared/src/plugin-embed.ts b/packages/shared/src/plugin-embed.ts
index b33a0eda..0779eb03 100644
--- a/packages/shared/src/plugin-embed.ts
+++ b/packages/shared/src/plugin-embed.ts
@@ -1,4 +1,5 @@
import { mergeAttributes, Node } from "@tiptap/core";
+import { openBlockSource } from "./markdown-block-start";
export const PLUGIN_EMBED_NODE_TYPE = "edgeeverPluginEmbed" as const;
export const PLUGIN_EMBED_MARKDOWN_LANGUAGE = "edgeever-plugin-embed" as const;
@@ -98,7 +99,7 @@ export const PluginEmbed = Node.create({
name: PLUGIN_EMBED_NODE_TYPE,
level: "block",
start(source: string) {
- return source.indexOf(`\`\`\`${PLUGIN_EMBED_MARKDOWN_LANGUAGE}`);
+ return openBlockSource(source).indexOf(`\`\`\`${PLUGIN_EMBED_MARKDOWN_LANGUAGE}`);
},
tokenize(source: string) {
const match = FENCE_PATTERN.exec(source);