From 5db71b4a76788fb5e12d9b4c886483a93df645e9 Mon Sep 17 00:00:00 2001 From: eleith Date: Fri, 4 Dec 2026 14:42:29 -0800 Subject: [PATCH 1/6] Add a demo word piece for Mermaid diagrams --- .../words/from-notebook-to-garden.words.md | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 apps/web/demo/archive/words/from-notebook-to-garden.words.md diff --git a/apps/web/demo/archive/words/from-notebook-to-garden.words.md b/apps/web/demo/archive/words/from-notebook-to-garden.words.md new file mode 100644 index 00000000..cee1750e --- /dev/null +++ b/apps/web/demo/archive/words/from-notebook-to-garden.words.md @@ -0,0 +1,29 @@ +--- +title: From Notebook to Garden +summary: Two diagrams show how to revise a draft and take a notebook idea to a public page. +date_published: 2026-11-30 +keywords: writing, diagrams, mermaid +--- + +## Revise a note + +```mermaid +flowchart TD +accTitle: A short revision pass +accDescr: Write a draft, read it aloud, and revise it. +A[Draft] --> B[Read aloud] --> C[Revise] +``` + +## Publish a note + +```mermaid +flowchart LR +accTitle: From notebook to public page +accDescr: Collect notebook ideas, choose one useful thread, arrange the paragraphs, write a draft, read it aloud, review the saved preview, then publish to the garden. +A[Collect notebook ideas] --> B[Select one useful thread] +B --> C[Arrange the paragraphs] +C --> D[Write a first draft] +D --> E[Read the draft aloud] +E --> F[Review the saved preview] +F --> G[Publish to the garden] +``` -- 2.54.1 From eec64f927341057b228311c54c022017afa9f2cf Mon Sep 17 00:00:00 2001 From: eleith Date: Fri, 4 Dec 2026 14:53:26 -0800 Subject: [PATCH 2/6] Add a bounded Pele render adapter to the worker --- packages/web/worker/package.json | 1 + .../markdown/mermaid/render.test.ts | 73 +++++++++++++++++++ .../src/transforms/markdown/mermaid/render.ts | 51 +++++++++++++ pnpm-lock.yaml | 9 +++ 4 files changed, 134 insertions(+) create mode 100644 packages/web/worker/src/transforms/markdown/mermaid/render.test.ts create mode 100644 packages/web/worker/src/transforms/markdown/mermaid/render.ts diff --git a/packages/web/worker/package.json b/packages/web/worker/package.json index 7ed6a61f..fdd8b76d 100644 --- a/packages/web/worker/package.json +++ b/packages/web/worker/package.json @@ -80,6 +80,7 @@ "micromark-util-types": "2.0.2", "mime-types": "3.0.2", "openworkflow": "0.11.0", + "pele": "1.13.0", "rehype-autolink-headings": "7.1.0", "rehype-katex": "7.0.1", "rehype-pretty-code": "0.14.1", diff --git a/packages/web/worker/src/transforms/markdown/mermaid/render.test.ts b/packages/web/worker/src/transforms/markdown/mermaid/render.test.ts new file mode 100644 index 00000000..1e955ba7 --- /dev/null +++ b/packages/web/worker/src/transforms/markdown/mermaid/render.test.ts @@ -0,0 +1,73 @@ +import { expect, test, vi } from 'vitest' +import { render } from 'pele' +import type * as Pele from 'pele' +import { renderMermaid } from './render.js' + +vi.mock('pele', async (importOriginal) => { + const pele = await importOriginal() + return { ...pele, render: vi.fn(pele.render) } +}) + +const idPrefix = 'luzzle-mermaid-test-body-1' + +test('renders a left-to-right flowchart with prefixed accessible metadata', () => { + const result = renderMermaid( + 'flowchart LR\naccTitle: Publishing\naccDescr: Review the draft, then publish it.\nA[Review] --> B[Publish]', + idPrefix + ) + + if (!result.ok) throw new Error(`Diagram failed: ${result.reason}`) + expect(result.type).toBe('flowchart') + expect(result.width).toBeGreaterThan(result.height) + expect(result.uncheckedSvg).toContain(`aria-labelledby="${idPrefix}-title"`) + expect(result.uncheckedSvg).toContain(`Publishing`) + expect(result.uncheckedSvg).toContain(`aria-describedby="${idPrefix}-desc"`) + expect(result.uncheckedSvg).toContain( + `Review the draft, then publish it.` + ) +}) + +test('renders without emitting links or image resources', () => { + const result = renderMermaid( + [ + 'flowchart TD', + 'A[Read more] --> B@{ img: "https://example.test/picture.png", label: "Picture" }', + 'click A href "https://example.test/read-more"', + ].join('\n'), + idPrefix + ) + + if (!result.ok) throw new Error(`Diagram failed: ${result.reason}`) + expect(result.uncheckedSvg).toContain('Read more') + expect(result.uncheckedSvg).not.toMatch(/ { + expect(renderMermaid('flowchart LR\nA --> [', idPrefix)).toEqual({ ok: false, reason: 'syntax' }) +}) + +test('limits source by UTF-8 bytes before calling Pele', () => { + vi.mocked(render).mockClear() + const source = `flowchart LR\n%% ${'界'.repeat(6000)}\nA --> B` + expect(renderMermaid(source, idPrefix)).toEqual({ ok: false, reason: 'limit' }) + expect(render).not.toHaveBeenCalled() +}) + +test.each([ + ['oversized UTF-8 output', { svg: `${'界'.repeat(90_000)}` }], + ['oversized width', { width: 9000 }], + ['zero height', { height: 0 }], + ['non-finite height', { height: Infinity }], +])('rejects %s even when Pele returns successfully', (_name, override) => { + vi.mocked(render).mockReturnValueOnce({ + svg: '', + width: 100, + height: 50, + type: 'flowchart', + mermaidType: 'flowchart-v2', + links: [], + ...override, + }) + + expect(renderMermaid('flowchart LR\nA --> B', idPrefix)).toEqual({ ok: false, reason: 'limit' }) +}) diff --git a/packages/web/worker/src/transforms/markdown/mermaid/render.ts b/packages/web/worker/src/transforms/markdown/mermaid/render.ts new file mode 100644 index 00000000..1e663c93 --- /dev/null +++ b/packages/web/worker/src/transforms/markdown/mermaid/render.ts @@ -0,0 +1,51 @@ +import { PeleError, render } from 'pele' +import type { DiagramType, PeleErrorCode } from 'pele' + +const maxSourceBytes = 16 * 1024 +const maxSvgBytes = 256 * 1024 +const maxDimension = 8192 +const maxEdges = 200 + +type RenderedDiagram = { + ok: true + uncheckedSvg: string + width: number + height: number + type: DiagramType +} + +type RenderFailure = { + ok: false + reason: PeleErrorCode | 'render-error' +} + +type RenderResult = RenderedDiagram | RenderFailure + +// Synchronous Pele boundary. The returned SVG still needs validation before HTML insertion. +export function renderMermaid(source: string, idPrefix: string): RenderResult { + if (Buffer.byteLength(source) > maxSourceBytes) return { ok: false, reason: 'limit' } + + try { + const { svg, width, height, type } = render(source, { + idPrefix, + responsive: false, + autoDirection: false, + links: false, + images: false, + limit: maxSourceBytes, + outputLimit: maxSvgBytes, + maxEdges, + }) + if (Buffer.byteLength(svg) > maxSvgBytes || !validDimension(width) || !validDimension(height)) { + return { ok: false, reason: 'limit' } + } + return { ok: true, uncheckedSvg: svg, width, height, type } + } catch (error) { + // Pele's error text may contain excerpts from the diagram. + return { ok: false, reason: error instanceof PeleError ? error.code : 'render-error' } + } +} + +function validDimension(size: number): boolean { + return Number.isFinite(size) && size > 0 && size <= maxDimension +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index a2984243..cd178a85 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -879,6 +879,9 @@ importers: openworkflow: specifier: 0.11.0 version: 0.11.0 + pele: + specifier: 1.13.0 + version: 1.13.0 rehype-autolink-headings: specifier: 7.1.0 version: 7.1.0 @@ -3592,6 +3595,10 @@ packages: pathe@2.0.3: resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==} + pele@1.13.0: + resolution: {integrity: sha512-Ie8UKY9x00MsuR3jO6AzUwzK2Z6MIV3Tf4EDdITiuk8Uaz8K7g0R082WqsqNaSU8DdgkrRvZThzhit83mi/uiw==} + engines: {node: '>=20'} + picocolors@1.1.1: resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} @@ -7398,6 +7405,8 @@ snapshots: pathe@2.0.3: {} + pele@1.13.0: {} + picocolors@1.1.1: {} picomatch@4.0.4: {} -- 2.54.1 From 4ed10ac29ef0fd32311d70c36ddc2c23f9fffc5a Mon Sep 17 00:00:00 2001 From: eleith Date: Fri, 4 Dec 2026 15:09:24 -0800 Subject: [PATCH 3/6] =?UTF-8?q?Use=20Pele=E2=80=99s=20native=20limits=20an?= =?UTF-8?q?d=20trust=20its=20SVG=20output?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../markdown/mermaid/render.test.ts | 52 +++++-------------- .../src/transforms/markdown/mermaid/render.ts | 24 +++------ 2 files changed, 21 insertions(+), 55 deletions(-) diff --git a/packages/web/worker/src/transforms/markdown/mermaid/render.test.ts b/packages/web/worker/src/transforms/markdown/mermaid/render.test.ts index 1e955ba7..71630964 100644 --- a/packages/web/worker/src/transforms/markdown/mermaid/render.test.ts +++ b/packages/web/worker/src/transforms/markdown/mermaid/render.test.ts @@ -1,13 +1,6 @@ -import { expect, test, vi } from 'vitest' -import { render } from 'pele' -import type * as Pele from 'pele' +import { expect, test } from 'vitest' import { renderMermaid } from './render.js' -vi.mock('pele', async (importOriginal) => { - const pele = await importOriginal() - return { ...pele, render: vi.fn(pele.render) } -}) - const idPrefix = 'luzzle-mermaid-test-body-1' test('renders a left-to-right flowchart with prefixed accessible metadata', () => { @@ -19,12 +12,10 @@ test('renders a left-to-right flowchart with prefixed accessible metadata', () = if (!result.ok) throw new Error(`Diagram failed: ${result.reason}`) expect(result.type).toBe('flowchart') expect(result.width).toBeGreaterThan(result.height) - expect(result.uncheckedSvg).toContain(`aria-labelledby="${idPrefix}-title"`) - expect(result.uncheckedSvg).toContain(`Publishing`) - expect(result.uncheckedSvg).toContain(`aria-describedby="${idPrefix}-desc"`) - expect(result.uncheckedSvg).toContain( - `Review the draft, then publish it.` - ) + expect(result.svg).toContain(`aria-labelledby="${idPrefix}-title"`) + expect(result.svg).toContain(`Publishing`) + expect(result.svg).toContain(`aria-describedby="${idPrefix}-desc"`) + expect(result.svg).toContain(`Review the draft, then publish it.`) }) test('renders without emitting links or image resources', () => { @@ -38,36 +29,21 @@ test('renders without emitting links or image resources', () => { ) if (!result.ok) throw new Error(`Diagram failed: ${result.reason}`) - expect(result.uncheckedSvg).toContain('Read more') - expect(result.uncheckedSvg).not.toMatch(/ { expect(renderMermaid('flowchart LR\nA --> [', idPrefix)).toEqual({ ok: false, reason: 'syntax' }) }) -test('limits source by UTF-8 bytes before calling Pele', () => { - vi.mocked(render).mockClear() - const source = `flowchart LR\n%% ${'界'.repeat(6000)}\nA --> B` - expect(renderMermaid(source, idPrefix)).toEqual({ ok: false, reason: 'limit' }) - expect(render).not.toHaveBeenCalled() -}) +test('uses Pele’s character limit rather than an additional byte limit', () => { + const withComment = (comment: string) => `flowchart LR\n%% ${comment}\nA --> B` -test.each([ - ['oversized UTF-8 output', { svg: `${'界'.repeat(90_000)}` }], - ['oversized width', { width: 9000 }], - ['zero height', { height: 0 }], - ['non-finite height', { height: Infinity }], -])('rejects %s even when Pele returns successfully', (_name, override) => { - vi.mocked(render).mockReturnValueOnce({ - svg: '', - width: 100, - height: 50, - type: 'flowchart', - mermaidType: 'flowchart-v2', - links: [], - ...override, + // Fewer than 16,384 characters, but more than 16,384 UTF-8 bytes. + expect(renderMermaid(withComment('界'.repeat(6_000)), idPrefix)).toMatchObject({ ok: true }) + expect(renderMermaid(withComment('x'.repeat(17_000)), idPrefix)).toEqual({ + ok: false, + reason: 'limit', }) - - expect(renderMermaid('flowchart LR\nA --> B', idPrefix)).toEqual({ ok: false, reason: 'limit' }) }) diff --git a/packages/web/worker/src/transforms/markdown/mermaid/render.ts b/packages/web/worker/src/transforms/markdown/mermaid/render.ts index 1e663c93..de071dd4 100644 --- a/packages/web/worker/src/transforms/markdown/mermaid/render.ts +++ b/packages/web/worker/src/transforms/markdown/mermaid/render.ts @@ -1,14 +1,13 @@ import { PeleError, render } from 'pele' import type { DiagramType, PeleErrorCode } from 'pele' -const maxSourceBytes = 16 * 1024 -const maxSvgBytes = 256 * 1024 -const maxDimension = 8192 +const maxSourceLength = 16 * 1024 +const maxSvgLength = 256 * 1024 const maxEdges = 200 type RenderedDiagram = { ok: true - uncheckedSvg: string + svg: string width: number height: number type: DiagramType @@ -21,10 +20,8 @@ type RenderFailure = { type RenderResult = RenderedDiagram | RenderFailure -// Synchronous Pele boundary. The returned SVG still needs validation before HTML insertion. +// Treat Pele’s SVG like author-supplied Markdown HTML. export function renderMermaid(source: string, idPrefix: string): RenderResult { - if (Buffer.byteLength(source) > maxSourceBytes) return { ok: false, reason: 'limit' } - try { const { svg, width, height, type } = render(source, { idPrefix, @@ -32,20 +29,13 @@ export function renderMermaid(source: string, idPrefix: string): RenderResult { autoDirection: false, links: false, images: false, - limit: maxSourceBytes, - outputLimit: maxSvgBytes, + limit: maxSourceLength, + outputLimit: maxSvgLength, maxEdges, }) - if (Buffer.byteLength(svg) > maxSvgBytes || !validDimension(width) || !validDimension(height)) { - return { ok: false, reason: 'limit' } - } - return { ok: true, uncheckedSvg: svg, width, height, type } + return { ok: true, svg, width, height, type } } catch (error) { // Pele's error text may contain excerpts from the diagram. return { ok: false, reason: error instanceof PeleError ? error.code : 'render-error' } } } - -function validDimension(size: number): boolean { - return Number.isFinite(size) && size > 0 && size <= maxDimension -} -- 2.54.1 From c0696ffc9213712240897bed61ad48424274685d Mon Sep 17 00:00:00 2001 From: eleith Date: Fri, 4 Dec 2026 15:41:48 -0800 Subject: [PATCH 4/6] Add Mermaid fence plugins to the Markdown engine --- .../worker/src/transforms/markdown/engine.ts | 13 ++- .../worker/src/transforms/markdown/index.ts | 2 +- .../markdown/mermaid/markdown.test.ts | 104 ++++++++++++++++++ .../transforms/markdown/mermaid/markdown.ts | 97 ++++++++++++++++ 4 files changed, 213 insertions(+), 3 deletions(-) create mode 100644 packages/web/worker/src/transforms/markdown/mermaid/markdown.test.ts create mode 100644 packages/web/worker/src/transforms/markdown/mermaid/markdown.ts diff --git a/packages/web/worker/src/transforms/markdown/engine.ts b/packages/web/worker/src/transforms/markdown/engine.ts index fa6877e2..1673ca8b 100644 --- a/packages/web/worker/src/transforms/markdown/engine.ts +++ b/packages/web/worker/src/transforms/markdown/engine.ts @@ -9,6 +9,8 @@ import { remarkKeepInlineMathOutOfCodeHighlighting, type MathWarning, } from './math.js' +import { rehypeRenderMermaid, remarkMarkMermaidFences } from './mermaid/markdown.js' +import type { MermaidMarkdownOptions } from './mermaid/markdown.js' import remarkGfm from './remark-gfm.js' import { remarkSidenoteSyntax, remarkResolveSidenotes } from './remark-sidenotes.js' import { sidenoteHandler, rehypePlaceSidenotes, rehypePresentSidenotes } from './sidenotes/html.js' @@ -26,11 +28,16 @@ import type { Config } from '@luzzle/web.config' export type CodeThemes = Config['theme']['markdown']['code'] +type MarkdownOptions = { + assets?: AssetUrls + warnMath?: (warning: MathWarning) => void + mermaid?: MermaidMarkdownOptions +} + export async function processMarkdown( markdown: string, themes: CodeThemes, - assets?: AssetUrls, - warnMath?: (warning: MathWarning) => void + { assets, warnMath, mermaid }: MarkdownOptions = {} ): Promise { const processor = unified() .use(remarkGfm, { plugins: { footnote: false } }) @@ -41,6 +48,7 @@ export async function processMarkdown( .use(remarkResolveSidenotes) .use(remarkGemoji) .use(remarkDirective) + .use(remarkMarkMermaidFences, mermaid) .use(remarkRehype, { allowDangerousHtml: true, handlers: { @@ -58,6 +66,7 @@ export async function processMarkdown( .use(rehypeAutolinkHeadings) .use(rehypeTypesetMarkdownMath) .use(rehypeReportMathWarnings, warnMath) + .use(rehypeRenderMermaid, mermaid) .use(rehypeWrapMarkdown) .use(rehypeStringify, { allowDangerousHtml: true }) diff --git a/packages/web/worker/src/transforms/markdown/index.ts b/packages/web/worker/src/transforms/markdown/index.ts index 648b1f94..5ad79c32 100644 --- a/packages/web/worker/src/transforms/markdown/index.ts +++ b/packages/web/worker/src/transforms/markdown/index.ts @@ -13,7 +13,7 @@ export async function run(input: TransformInput): Promise { const assets = createMarkdownAssets(input) const render = (markdown: string, fieldPath?: string) => { const warnMath = createMathWarningHandler(input, fieldPath) - return processMarkdown(markdown, config.theme.markdown.code, assets, warnMath) + return processMarkdown(markdown, config.theme.markdown.code, { assets, warnMath }) } const records: AssetRecord[] = [] diff --git a/packages/web/worker/src/transforms/markdown/mermaid/markdown.test.ts b/packages/web/worker/src/transforms/markdown/mermaid/markdown.test.ts new file mode 100644 index 00000000..9d7da512 --- /dev/null +++ b/packages/web/worker/src/transforms/markdown/mermaid/markdown.test.ts @@ -0,0 +1,104 @@ +import { expect, test, vi } from 'vitest' +import { validateConfig } from '@luzzle/web.config' +import rehypeRaw from 'rehype-raw' +import { unified } from 'unified' +import { visit } from 'unist-util-visit' +import { processMarkdown } from '../engine.js' +import type { MermaidMarkdownOptions } from './markdown.js' + +const themes = validateConfig({}).theme.markdown.code +const idPrefix = 'luzzle-mermaid-test' +const flowchart = 'flowchart LR\naccTitle: Publishing flow\nA[Draft] --> B[Publish]' +const fence = ['```mermaid', flowchart, '```'].join('\n') + +function render(markdown: string, warn?: MermaidMarkdownOptions['warn']) { + return processMarkdown(markdown, themes, { mermaid: { idPrefix, warn } }) +} + +test('keeps Mermaid as highlighted source when no Mermaid context is supplied', async () => { + const html = await processMarkdown(fence, themes) + + expect(html).toContain('data-rehype-pretty-code-figure') + expect(html).toContain('data-language="mermaid"') + expect(html).not.toMatch(/ { + const markdown = ['Before $x^2$.', fence, 'After.', '```js\nconst value = 1\n```'].join('\n\n') + const html = await render(markdown) + + expect(html).toMatch(/
Publishing flow`) + expect(html.indexOf('
')).toBeLessThan(html.indexOf('

After.

')) + expect(html).not.toContain('flowchart LR') + expect(html).not.toContain('data-luzzle-mermaid-fence') + expect(html).toContain('class="katex-mathml"') + expect(html.match(/data-rehype-pretty-code-figure/g)).toHaveLength(1) +}) + +test('renders tilde fences nested in a blockquote', async () => { + const markdown = ['~~~mermaid', ...flowchart.split('\n'), '~~~'] + .map((line) => `> ${line}`) + .join('\n') + const html = await render(markdown) + + expect(html).toMatch(/
\s*
{ + const definition = fence.split('\n').map((line) => ` ${line}`).join('\n') + const markdown = `First[^shared] and again[^shared].\n\n[^shared]: A publishing diagram.\n\n${definition}` + const html = await render(markdown) + + const titleRefs = [...html.matchAll(/aria-labelledby="(luzzle-mermaid-test-[^"]+)"/g)] + .map(([, id]) => id) + expect(titleRefs).toEqual([`${idPrefix}-1-title`, `${idPrefix}-2-title`]) + expect(await render(markdown)).toBe(html) +}) + +test('leaves author HTML and inline code alone and scrubs inert template markers', async () => { + const raw = '
Raw code
' + const template = [''].join('\n\n') + const warn = vi.fn() + const html = await render([raw, '`mermaid`', template].join('\n\n'), warn) + + expect(html).toContain(raw) + expect(html).toContain('mermaid') + expect(html).toContain('