markdotserver 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,516 @@
1
+ # SPDX-FileCopyrightText: 2026 Alexey Agafonov
2
+ # SPDX-License-Identifier: MIT
3
+ """Safe Markdown rendering with heading anchors, rewritten links and DOT fences."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import base64
8
+ import html
9
+ import posixpath
10
+ import re
11
+ import time
12
+ from dataclasses import dataclass
13
+ from pathlib import PurePosixPath
14
+ from typing import Any, Protocol
15
+ from urllib.parse import quote, unquote, urlsplit
16
+
17
+ from markdown_it import MarkdownIt
18
+ from markdown_it.token import Token
19
+ from mdit_py_plugins.tasklists import tasklists_plugin
20
+ from pygments import highlight
21
+ from pygments.formatters import HtmlFormatter
22
+ from pygments.lexers import get_lexer_by_name
23
+ from pygments.util import ClassNotFound
24
+
25
+ from markdotserver.filesystem import FileKind, kind_for_name
26
+ from markdotserver.graphviz_renderer import GraphvizError, GraphvizRenderer
27
+
28
+ __all__ = [
29
+ "CachingSvgRenderer",
30
+ "Heading",
31
+ "MarkdownRenderer",
32
+ "MarkdownResult",
33
+ "SvgRenderer",
34
+ ]
35
+
36
+ _EXTERNAL_SCHEMES = frozenset({"http", "https"})
37
+ _LINK_SCHEMES = _EXTERNAL_SCHEMES | {"mailto"}
38
+ _DOT_LANGUAGES = frozenset({"dot", "graphviz"})
39
+
40
+ _SCHEME_RE = re.compile(r"^([a-z][a-z0-9+.-]*):")
41
+ _SCHEME_NOISE_RE = re.compile(r"[\x00-\x20\x7f]")
42
+ _SLUG_PUNCTUATION_RE = re.compile(r"[^\w\s-]", re.UNICODE)
43
+ _SLUG_WHITESPACE_RE = re.compile(r"\s+")
44
+ _SLUG_DASHES_RE = re.compile(r"-{2,}")
45
+
46
+ _FORMATTER = HtmlFormatter(nowrap=True)
47
+
48
+ _DEFAULT_MAX_EMBEDDED_DIAGRAMS = 32
49
+ _DEFAULT_RENDER_DEADLINE = 30.0
50
+
51
+
52
+ class SvgRenderer(Protocol):
53
+ """The slice of the Graphviz renderer used for embedded fences."""
54
+
55
+ def render_svg(self, source: str) -> bytes: ...
56
+
57
+
58
+ class CachingSvgRenderer(SvgRenderer, Protocol):
59
+ """An :class:`SvgRenderer` that can name its cache entries.
60
+
61
+ The ``/api/svg`` route uses the digest as an ETag, so injected doubles in
62
+ route tests must provide it; embedded-fence doubles need only
63
+ ``render_svg``.
64
+ """
65
+
66
+ def cache_key(self, source: str) -> str: ...
67
+
68
+
69
+ @dataclass(frozen=True, slots=True)
70
+ class Heading:
71
+ """One entry in the document table of contents."""
72
+
73
+ level: int
74
+ text: str
75
+ id: str
76
+ children: tuple[Heading, ...] = ()
77
+
78
+ def to_dict(self) -> dict[str, Any]:
79
+ """Return a JSON-safe nested representation."""
80
+ return {
81
+ "level": self.level,
82
+ "text": self.text,
83
+ "id": self.id,
84
+ "children": [child.to_dict() for child in self.children],
85
+ }
86
+
87
+
88
+ @dataclass(frozen=True, slots=True)
89
+ class MarkdownResult:
90
+ """Rendered Markdown HTML and its nested heading outline."""
91
+
92
+ html: str
93
+ headings: tuple[Heading, ...]
94
+
95
+
96
+ @dataclass(frozen=True, slots=True)
97
+ class _Decision:
98
+ url: str | None = None
99
+ fragment: bool = False
100
+ external: bool = False
101
+ unsafe: bool = False
102
+
103
+
104
+ @dataclass(frozen=True, slots=True)
105
+ class _Target:
106
+ path: str = ""
107
+ query: str = ""
108
+ fragment: str = ""
109
+ external: bool = False
110
+ fragment_only: bool = False
111
+ unsafe: bool = False
112
+
113
+
114
+ #: Inline tokens that separate words. Without them a multi-line setext heading
115
+ #: such as ``Hello`` / ``world`` would produce the anchor ``helloworld`` while
116
+ #: the rendered heading reads "Hello world".
117
+ _BREAK_TOKENS = frozenset({"softbreak", "hardbreak"})
118
+
119
+ #: Element IDs the page shell already uses. A heading that slugified to one of
120
+ #: these would render a duplicate DOM id, and the client treats ``#content`` as
121
+ #: the skip-link anchor rather than a heading deep link, so generated heading
122
+ #: anchors must never claim them.
123
+ _RESERVED_HEADING_IDS = frozenset(
124
+ {
125
+ "app-layout",
126
+ "content",
127
+ "diagram-image",
128
+ "diagram-viewport",
129
+ "directory-tree",
130
+ "headings",
131
+ "panel-files",
132
+ "panel-headings",
133
+ "sidebar",
134
+ "sidebar-resizer",
135
+ "sidebar-toggle",
136
+ "tab-files",
137
+ "tab-headings",
138
+ "theme-toggle",
139
+ "toolbar",
140
+ "tree-refresh",
141
+ }
142
+ )
143
+
144
+
145
+ def _inline_text(token: Token | None) -> str:
146
+ if token is None:
147
+ return ""
148
+ if token.type in ("text", "code_inline", "image"):
149
+ return token.content
150
+ if token.type in _BREAK_TOKENS:
151
+ return " "
152
+ if not token.children:
153
+ return ""
154
+ return "".join(_inline_text(child) for child in token.children)
155
+
156
+
157
+ def _slugify(text: str) -> str:
158
+ value = _SLUG_PUNCTUATION_RE.sub("", text.strip().lower())
159
+ value = _SLUG_WHITESPACE_RE.sub("-", value)
160
+ value = _SLUG_DASHES_RE.sub("-", value).strip("-")
161
+ return value or "section"
162
+
163
+
164
+ def _heading_rule(state: Any) -> None:
165
+ used: dict[str, int] = {}
166
+ assigned: set[str] = set(_RESERVED_HEADING_IDS)
167
+ headings: list[tuple[int, str, str]] = []
168
+ tokens = state.tokens
169
+
170
+ for index, token in enumerate(tokens):
171
+ if token.type != "heading_open":
172
+ continue
173
+ inline = tokens[index + 1] if index + 1 < len(tokens) else None
174
+ text = _inline_text(inline).strip()
175
+ base = _slugify(text)
176
+ # Counting bases alone is not enough: after two ``A`` headings, a
177
+ # literal ``A-2`` heading would collide with the generated ``a-2``.
178
+ # Probe the assigned set until the candidate is genuinely free.
179
+ count = used.get(base, 0)
180
+ while True:
181
+ count += 1
182
+ heading_id = base if count == 1 else f"{base}-{count}"
183
+ if heading_id not in assigned:
184
+ break
185
+ used[base] = count
186
+ assigned.add(heading_id)
187
+ token.attrSet("id", heading_id)
188
+ headings.append((int(token.tag[1:]), text, heading_id))
189
+
190
+ state.env["headings"] = headings
191
+
192
+
193
+ @dataclass
194
+ class _HeadingBuilder:
195
+ level: int
196
+ text: str
197
+ id: str
198
+ children: list[_HeadingBuilder]
199
+
200
+
201
+ def _build_toc(flat: list[tuple[int, str, str]]) -> tuple[Heading, ...]:
202
+ roots: list[_HeadingBuilder] = []
203
+ stack: list[_HeadingBuilder] = []
204
+
205
+ for level, text, heading_id in flat:
206
+ node = _HeadingBuilder(level, text, heading_id, [])
207
+ while stack and stack[-1].level >= level:
208
+ stack.pop()
209
+ if stack:
210
+ stack[-1].children.append(node)
211
+ else:
212
+ roots.append(node)
213
+ stack.append(node)
214
+
215
+ def freeze(nodes: list[_HeadingBuilder]) -> tuple[Heading, ...]:
216
+ return tuple(
217
+ Heading(node.level, node.text, node.id, freeze(node.children))
218
+ for node in nodes
219
+ )
220
+
221
+ return freeze(roots)
222
+
223
+
224
+ def _detect_scheme(value: str) -> str | None:
225
+ normalised = _SCHEME_NOISE_RE.sub("", value).lower()
226
+ match = _SCHEME_RE.match(normalised)
227
+ return match.group(1) if match else None
228
+
229
+
230
+ def _parse_target(value: str, *, allowed_schemes: frozenset[str]) -> _Target:
231
+ scheme = _detect_scheme(value)
232
+ if scheme is not None:
233
+ if scheme in allowed_schemes:
234
+ return _Target(external=True)
235
+ return _Target(unsafe=True)
236
+
237
+ try:
238
+ parts = urlsplit(value)
239
+ except ValueError:
240
+ return _Target(unsafe=True)
241
+
242
+ if parts.netloc:
243
+ return _Target(external=True)
244
+ if not parts.path:
245
+ return _Target(
246
+ query=parts.query,
247
+ fragment=parts.fragment,
248
+ fragment_only=bool(parts.fragment),
249
+ )
250
+ return _Target(path=parts.path, query=parts.query, fragment=parts.fragment)
251
+
252
+
253
+ def _resolve_path(path: str, source_path: str) -> str | None:
254
+ if path.startswith("/"):
255
+ candidate = path.lstrip("/")
256
+ else:
257
+ base = PurePosixPath(source_path).parent
258
+ candidate = str(base / path) if str(base) != "." else path
259
+
260
+ normalised = posixpath.normpath(candidate)
261
+ if (
262
+ normalised in ("", ".", "..")
263
+ or normalised.startswith("../")
264
+ or normalised.startswith("/")
265
+ ):
266
+ return None
267
+ return normalised
268
+
269
+
270
+ #: Characters left alone when quoting a query or fragment. ``%`` is kept so
271
+ #: existing escapes are not double-encoded; everything else (spaces, quotes)
272
+ #: is percent-encoded so the rewritten URL stays well-formed.
273
+ _QUERY_SAFE = "%=&/?@:;+,$!~*'()-._"
274
+
275
+
276
+ def _build_url(prefix: str, path: str, query: str, fragment: str) -> str:
277
+ quoted = "/".join(quote(unquote(part), safe="") for part in path.split("/"))
278
+ url = f"{prefix}{quoted}"
279
+ if query:
280
+ url = f"{url}?{quote(query, safe=_QUERY_SAFE)}"
281
+ if fragment:
282
+ url = f"{url}#{quote(fragment, safe=_QUERY_SAFE)}"
283
+ return url
284
+
285
+
286
+ def _decide_link(href: str, source_path: str) -> _Decision:
287
+ target = _parse_target(href, allowed_schemes=_LINK_SCHEMES)
288
+ if target.unsafe:
289
+ return _Decision(unsafe=True)
290
+ if target.external:
291
+ return _Decision(external=True)
292
+ if target.fragment_only or not target.path:
293
+ return _Decision()
294
+
295
+ resolved = _resolve_path(target.path, source_path)
296
+ if resolved is None:
297
+ # A target that escapes the root is deliberately left as written: it
298
+ # cannot be mapped to any route, the browser resolves it to a path the
299
+ # server answers with a styled 404, and rewriting it would imply the
300
+ # viewer can serve it. Documented in docs/security.md.
301
+ return _Decision()
302
+ # Every in-root relative link is rewritten, whatever its extension. Leaving
303
+ # the original href in place would resolve it against ``/view/<dir>/<doc>``,
304
+ # which can never be correct, so a link to a directory or to an unsupported
305
+ # file must still land on a route that can explain itself.
306
+ return _Decision(
307
+ url=_build_url("/view/", resolved, target.query, target.fragment),
308
+ fragment=True,
309
+ )
310
+
311
+
312
+ def _decide_image(src: str, source_path: str) -> _Decision:
313
+ target = _parse_target(src, allowed_schemes=_EXTERNAL_SCHEMES)
314
+ if target.unsafe:
315
+ return _Decision(unsafe=True)
316
+ if target.external or target.fragment_only or not target.path:
317
+ return _Decision()
318
+
319
+ resolved = _resolve_path(target.path, source_path)
320
+ if resolved is None:
321
+ return _Decision()
322
+
323
+ kind = kind_for_name(resolved)
324
+ if kind in (FileKind.IMAGE, FileKind.SVG):
325
+ prefix = "/assets/"
326
+ elif kind is FileKind.GRAPHVIZ:
327
+ prefix = "/api/svg/"
328
+ else:
329
+ return _Decision()
330
+ return _Decision(url=_build_url(prefix, resolved, target.query, target.fragment))
331
+
332
+
333
+ def _strip_link_token(token: Token) -> None:
334
+ token.type = "text"
335
+ token.content = ""
336
+ token.attrs = {}
337
+
338
+
339
+ def _attribute(token: Token, name: str) -> str:
340
+ """Read a token attribute as text.
341
+
342
+ ``attrGet`` is typed as ``str | int | float | None`` because attributes can
343
+ carry numeric values; a URL attribute is always treated as text here.
344
+ """
345
+ value = token.attrGet(name)
346
+ return "" if value is None else str(value)
347
+
348
+
349
+ def _rewrite_link(link_token: Token, source_path: str) -> bool:
350
+ decision = _decide_link(_attribute(link_token, "href"), source_path)
351
+ if decision.unsafe:
352
+ return False
353
+ if decision.url is not None:
354
+ link_token.attrSet("href", decision.url)
355
+ if decision.fragment:
356
+ link_token.attrSet("data-get", decision.url)
357
+ link_token.attrSet("data-target", "#content")
358
+ link_token.attrSet("data-push-url", "true")
359
+ if decision.external:
360
+ link_token.attrSet("rel", "noopener noreferrer")
361
+ return True
362
+
363
+
364
+ def _link_rule(state: Any) -> None:
365
+ source_path = state.env.get("source_path", "")
366
+
367
+ for token in state.tokens:
368
+ if token.type != "inline" or not token.children:
369
+ continue
370
+
371
+ dropped_link_depth = 0
372
+ for child in token.children:
373
+ if child.type == "link_open":
374
+ if dropped_link_depth:
375
+ _strip_link_token(child)
376
+ dropped_link_depth += 1
377
+ elif not _rewrite_link(child, source_path):
378
+ _strip_link_token(child)
379
+ dropped_link_depth = 1
380
+ elif child.type == "link_close":
381
+ if dropped_link_depth:
382
+ _strip_link_token(child)
383
+ dropped_link_depth -= 1
384
+ elif child.type == "image":
385
+ decision = _decide_image(_attribute(child, "src"), source_path)
386
+ if decision.unsafe:
387
+ child.type = "text"
388
+ child.content = child.content or _attribute(child, "alt") or "image"
389
+ child.attrs = {}
390
+ elif decision.url is not None:
391
+ child.attrSet("src", decision.url)
392
+
393
+
394
+ def _highlight_code(source: str, language: str) -> str:
395
+ try:
396
+ lexer = (
397
+ get_lexer_by_name(language, stripall=False)
398
+ if language
399
+ else get_lexer_by_name("text")
400
+ )
401
+ except ClassNotFound:
402
+ lexer = get_lexer_by_name("text")
403
+
404
+ body = highlight(source, lexer, _FORMATTER)
405
+ class_attr = (
406
+ f' class="language-{html.escape(language, quote=True)}"' if language else ""
407
+ )
408
+ return f'<pre class="highlight"><code{class_attr}>{body}</code></pre>\n'
409
+
410
+
411
+ def _render_error(message: str) -> str:
412
+ escaped = html.escape(message, quote=True)
413
+ return f'<div class="render-error" role="alert"><p>{escaped}</p></div>\n'
414
+
415
+
416
+ class MarkdownRenderer:
417
+ """Render Markdown safely with a nested heading outline."""
418
+
419
+ def __init__(
420
+ self,
421
+ graphviz: SvgRenderer | None = None,
422
+ *,
423
+ max_embedded_diagrams: int = _DEFAULT_MAX_EMBEDDED_DIAGRAMS,
424
+ render_deadline: float = _DEFAULT_RENDER_DEADLINE,
425
+ ) -> None:
426
+ if max_embedded_diagrams <= 0:
427
+ raise ValueError("max_embedded_diagrams must be a positive integer")
428
+ if render_deadline <= 0:
429
+ raise ValueError("render_deadline must be a positive number of seconds")
430
+
431
+ self._graphviz = graphviz or GraphvizRenderer()
432
+ self._max_embedded_diagrams = max_embedded_diagrams
433
+ self._render_deadline = float(render_deadline)
434
+
435
+ markdown = MarkdownIt(
436
+ "default",
437
+ {"html": False, "linkify": False, "typographer": False},
438
+ ).use(tasklists_plugin)
439
+ markdown.core.ruler.push("markdotserver_headings", _heading_rule)
440
+ markdown.core.ruler.push("markdotserver_links", _link_rule)
441
+
442
+ def fence(
443
+ renderer: Any,
444
+ tokens: Any,
445
+ index: int,
446
+ options: Any,
447
+ env: Any,
448
+ ) -> str:
449
+ return self._render_fence(tokens[index], env)
450
+
451
+ markdown.add_render_rule("fence", fence)
452
+ self._md = markdown
453
+
454
+ def render(self, source: str, *, source_path: str = "") -> MarkdownResult:
455
+ """Render Markdown source for a document at a root-relative path."""
456
+ env: dict[str, Any] = self._environment(source_path)
457
+ output = self._md.render(source, env)
458
+ headings = _build_toc(env.get("headings", []))
459
+ return MarkdownResult(html=output, headings=headings)
460
+
461
+ def parse_headings(
462
+ self, source: str, *, source_path: str = ""
463
+ ) -> tuple[Heading, ...]:
464
+ """Return the heading outline without rendering the document body.
465
+
466
+ Running only the core chain skips the renderer entirely, so embedded
467
+ Graphviz fences cost nothing here. The heading endpoint would otherwise
468
+ pay for a full page render just to list the anchors.
469
+ """
470
+ env: dict[str, Any] = self._environment(source_path)
471
+ self._md.parse(source, env)
472
+ return _build_toc(env.get("headings", []))
473
+
474
+ def _environment(self, source_path: str) -> dict[str, Any]:
475
+ return {
476
+ "source_path": source_path,
477
+ "diagrams_rendered": 0,
478
+ "deadline": time.monotonic() + self._render_deadline,
479
+ }
480
+
481
+ def _render_fence(self, token: Token, env: Any) -> str:
482
+ info = (token.info or "").strip()
483
+ language = info.split(maxsplit=1)[0] if info else ""
484
+ if language.lower() in _DOT_LANGUAGES:
485
+ return self._render_embedded_graphviz(token.content, env)
486
+ return _highlight_code(token.content, language)
487
+
488
+ def _render_embedded_graphviz(self, source: str, env: Any) -> str:
489
+ # A single document could otherwise spawn an unbounded number of
490
+ # subprocesses and hold a worker thread for the whole time.
491
+ rendered = int(env.get("diagrams_rendered", 0)) + 1
492
+ if isinstance(env, dict):
493
+ env["diagrams_rendered"] = rendered
494
+ if rendered > self._max_embedded_diagrams:
495
+ return _render_error(
496
+ "Embedded diagram not rendered: this document exceeds the limit of "
497
+ f"{self._max_embedded_diagrams} embedded Graphviz diagrams."
498
+ )
499
+ if time.monotonic() > float(env.get("deadline", float("inf"))):
500
+ return _render_error(
501
+ "Embedded diagram not rendered: the rendering deadline of "
502
+ f"{self._render_deadline:g} seconds for this document was exceeded."
503
+ )
504
+
505
+ try:
506
+ svg = self._graphviz.render_svg(source)
507
+ except GraphvizError as exc:
508
+ return _render_error(str(exc))
509
+
510
+ data = base64.b64encode(svg).decode("ascii")
511
+ return (
512
+ '<figure class="embedded-diagram">\n'
513
+ f'<img src="data:image/svg+xml;base64,{data}" '
514
+ 'alt="Embedded Graphviz diagram">\n'
515
+ "</figure>\n"
516
+ )
markdotserver/py.typed ADDED
@@ -0,0 +1 @@
1
+ # Marker file per PEP 561: this package ships inline type annotations.