From ea91034d8471457ea6f0e0a4fffbec8219a1d27e Mon Sep 17 00:00:00 2001 From: Torben Nehmer Date: Thu, 3 Dec 2026 23:34:19 +0100 Subject: [PATCH] Add page identity and frontmatter domain types PageId (UUIDv7) and PageTitle validate on construction; frontmatter is split losslessly, read as text-only YAML without anchors or duplicate keys, and written canonically. All page errors live in domain/errors. Co-Authored-By: Claude Sonnet 5.5 --- src/chemenu/domain/errors.py | 25 ++++++ src/chemenu/domain/frontmatter.py | 140 ++++++++++++++++++++++++++++++ src/chemenu/domain/identity.py | 75 ++++++++++++++++ tests/domain/test_frontmatter.py | 135 ++++++++++++++++++++++++++++ tests/domain/test_identity.py | 117 +++++++++++++++++++++++++ 5 files changed, 492 insertions(+) create mode 100644 src/chemenu/domain/errors.py create mode 100644 src/chemenu/domain/frontmatter.py create mode 100644 src/chemenu/domain/identity.py create mode 100644 tests/domain/test_frontmatter.py create mode 100644 tests/domain/test_identity.py diff --git a/src/chemenu/domain/errors.py b/src/chemenu/domain/errors.py new file mode 100644 index 0000000..649145f --- /dev/null +++ b/src/chemenu/domain/errors.py @@ -0,0 +1,25 @@ +"""Errors raised by the page domain.""" + + +class PageError(ValueError): + """Base class for all page domain errors.""" + + +class FrontmatterError(PageError): + """Frontmatter is missing, ambiguous or malformed.""" + + +class InvalidPageIdError(PageError): + """A page id is not a lowercase UUIDv7.""" + + +class InvalidTitleError(PageError): + """A page title is not usable as a file name and title line.""" + + +class FactTimeError(PageError): + """A fact time is invalid.""" + + +class InvalidSourceError(PageError): + """A source reference is invalid.""" diff --git a/src/chemenu/domain/frontmatter.py b/src/chemenu/domain/frontmatter.py new file mode 100644 index 0000000..f850cf2 --- /dev/null +++ b/src/chemenu/domain/frontmatter.py @@ -0,0 +1,140 @@ +"""Lossless splitting, strict reading and canonical writing of page frontmatter.""" + +import re +import unicodedata +from collections.abc import Mapping, Sequence +from typing import Any, cast + +import yaml + +from chemenu.domain.errors import FrontmatterError + +type Value = str | list[Value] | dict[str, Value] + +_FENCE = "---" +_LINE_RE = re.compile(r"([^\r\n]*)(\r\n|\n|\r|$)") +_KEY_RE = re.compile(r"[a-z][a-z0-9_]*") +# PyYAML breaks lines here, `split_document` does not. +_AMBIGUOUS_BREAKS_RE = re.compile("[\x85\u2028\u2029]") +_SURROGATE_RE = re.compile("[\ud800-\udfff]") +_MAX_DEPTH = 32 +_ALWAYS_ESCAPED = frozenset(map(chr, (0x85, 0x2028, 0x2029, 0xFEFF, 0xFFFE, 0xFFFF))) + + +def split_document(text: str) -> tuple[str, str]: + """Split text into the YAML block between the fences and the body, losslessly.""" + pos = 0 + block_start = -1 + while pos < len(text): + match = _LINE_RE.match(text, pos) + if match is None: # unreachable: the pattern matches at any position + raise FrontmatterError("cannot read line") + line, eol = match.group(1), match.group(2) + end = match.end() + if block_start < 0: + if line != _FENCE or not eol: + raise FrontmatterError("document does not start with a '---' line") + block_start = end + elif line == _FENCE: + return text[block_start:pos], text[end:] + pos = end + raise FrontmatterError("frontmatter is not closed by a '---' line") + + +class _Loader(yaml.BaseLoader): + """Composes nodes without anchors and aliases; values stay text.""" + + _depth = 0 + + def compose_node(self, parent: Any, index: Any) -> Any: # pyright: ignore[reportIncompatibleMethodOverride] + if self.check_event(yaml.AliasEvent): + raise FrontmatterError("YAML aliases are not allowed") + event = cast("object", self.peek_event()) # pyright: ignore[reportUnknownMemberType] + if getattr(event, "anchor", None) is not None: + raise FrontmatterError("YAML anchors are not allowed") + self._depth += 1 + if self._depth > _MAX_DEPTH: + raise FrontmatterError("frontmatter is nested too deeply") + node = super().compose_node(parent, index) + self._depth -= 1 + return node + + +def _scalar(node: yaml.ScalarNode) -> str: + text = str(node.value) + if _SURROGATE_RE.search(text): # from an escape such as "\\ud800" + raise FrontmatterError("text contains a lone surrogate") + return text + + +def _convert(node: yaml.Node) -> Value: + if isinstance(node, yaml.ScalarNode): + return _scalar(node) + if isinstance(node, yaml.SequenceNode): + return [_convert(child) for child in node.value] + if isinstance(node, yaml.MappingNode): + result: dict[str, Value] = {} + for key_node, value_node in node.value: + if not isinstance(key_node, yaml.ScalarNode): + raise FrontmatterError("mapping keys must be plain text") + key = _scalar(key_node) + if key in result: + raise FrontmatterError(f"duplicate key: {key!r}") + result[key] = _convert(value_node) + return result + raise FrontmatterError("unsupported YAML node") + + +def parse_frontmatter(block: str) -> dict[str, Value]: + """Read a YAML block into nested text values; every problem is a FrontmatterError.""" + if _AMBIGUOUS_BREAKS_RE.search(block): + raise FrontmatterError("frontmatter contains U+0085, U+2028 or U+2029") + try: + loader = _Loader(block) + try: + node = loader.get_single_node() + finally: + loader.dispose() + if node is None: + raise FrontmatterError("frontmatter is empty") + if not isinstance(node, yaml.MappingNode): + raise FrontmatterError("frontmatter must be a mapping") + value = _convert(node) + except FrontmatterError: + raise + except (yaml.YAMLError, RecursionError, ValueError, TypeError) as exc: + raise FrontmatterError(f"invalid frontmatter: {' '.join(str(exc).split())}") from exc + if not isinstance(value, dict): + raise FrontmatterError("frontmatter must be a mapping") + return value + + +def _quote(text: str) -> str: + out = ['"'] + for char in text: + code = ord(char) + if 0xD800 <= code <= 0xDFFF: + raise FrontmatterError("text contains a lone surrogate") + if char == '"' or char == "\\": + out.append("\\" + char) + elif unicodedata.category(char) == "Cc" or char in _ALWAYS_ESCAPED: + out.append(f"\\u{code:04x}") + else: + out.append(char) + out.append('"') + return "".join(out) + + +def render_frontmatter(fields: Mapping[str, str | Sequence[str]]) -> str: + """Write fields in order between fences; texts quoted, lists on one line.""" + lines = [_FENCE] + for key, value in fields.items(): + if not _KEY_RE.fullmatch(key): + raise FrontmatterError(f"invalid key: {key!r}") + if isinstance(value, str): + rendered = _quote(value) + else: + rendered = "[" + ", ".join(_quote(item) for item in value) + "]" + lines.append(f"{key}: {rendered}") + lines.append(_FENCE) + return "\n".join(lines) + "\n" diff --git a/src/chemenu/domain/identity.py b/src/chemenu/domain/identity.py new file mode 100644 index 0000000..262c9e7 --- /dev/null +++ b/src/chemenu/domain/identity.py @@ -0,0 +1,75 @@ +"""Page identity: id (UUIDv7) and title.""" + +import re +import unicodedata +from dataclasses import dataclass + +from chemenu.domain.errors import InvalidPageIdError, InvalidTitleError + +_ID_RE = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}") +_FORBIDDEN_CHARS = frozenset('<>:"/\\|?*[]#^') +_LINE_BREAKS = frozenset("\u2028\u2029") +_MAX_TITLE_BYTES = 252 +# Invisible format characters (Cf) are forbidden, except the joiners that some +# scripts and emoji sequences need and the tag characters of subdivision flags. +_ALLOWED_FORMAT = frozenset("\u200c\u200d") +_TAGS = range(0xE0020, 0xE0080) +_DEVICE_NAMES = frozenset( + {"CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$"} + | {f"{name}{digit}" for name in ("COM", "LPT") for digit in "123456789¹²³"} +) + + +@dataclass(frozen=True, slots=True) +class PageId: + """A lowercase UUIDv7 with hyphens.""" + + value: str + + def __post_init__(self) -> None: + if not _ID_RE.fullmatch(self.value): + raise InvalidPageIdError(f"invalid page id: {self.value!r}") + + +@dataclass(frozen=True, slots=True) +class PageTitle: + """A page title that is safe as a file name and as a single title line.""" + + value: str + + def __post_init__(self) -> None: + reason = _title_problem(self.value) + if reason: + raise InvalidTitleError(f"invalid title {self.value!r}: {reason}") + + +def _invisible(char: str) -> bool: + return ( + unicodedata.category(char) == "Cf" + and char not in _ALLOWED_FORMAT + and ord(char) not in _TAGS + ) + + +def _title_problem(title: str) -> str | None: + if not title: + return "empty" + if any(0xD800 <= ord(c) <= 0xDFFF for c in title): + return "contains surrogates" + if any(c in _FORBIDDEN_CHARS for c in title) or "%%" in title: + return "contains a forbidden character" + if any(unicodedata.category(c) == "Cc" or c in _LINE_BREAKS for c in title): + return "contains a control character or line break" + if any(_invisible(c) for c in title): + return "contains an invisible character" + if title.casefold().endswith(".md"): + return "ends with .md, which Obsidian reads as the file extension" + if title != title.strip() or title.startswith(".") or title.endswith("."): + return "starts or ends with whitespace or a dot" + if title.split(".", 1)[0].rstrip(" ").upper() in _DEVICE_NAMES: + return "is a reserved device name" + if not unicodedata.is_normalized("NFC", title): + return "is not NFC" + if len(title.encode("utf-8")) > _MAX_TITLE_BYTES: + return f"longer than {_MAX_TITLE_BYTES} bytes" + return None diff --git a/tests/domain/test_frontmatter.py b/tests/domain/test_frontmatter.py new file mode 100644 index 0000000..261f872 --- /dev/null +++ b/tests/domain/test_frontmatter.py @@ -0,0 +1,135 @@ +import sys +import unicodedata + +import pytest + +from chemenu.domain.errors import FrontmatterError +from chemenu.domain.frontmatter import parse_frontmatter, render_frontmatter, split_document + + +def test_split_keeps_line_endings() -> None: + assert split_document("---\na: b\n---\nbody\n") == ("a: b\n", "body\n") + assert split_document("---\r\na: b\r\n---\r\nx\r\ny") == ("a: b\r\n", "x\r\ny") + assert split_document("---\ra: b\r---\rx") == ("a: b\r", "x") + assert split_document("---\na: b\n---") == ("a: b\n", "") + assert split_document("---\n---\n") == ("", "") + body = "l1\u2028l2\x0cl3\r\nl4\rl5\n" + assert split_document("---\na: b\u2028c\x0c\n---\r\n" + body) == ("a: b\u2028c\x0c\n", body) + for bad in [ + "", + "a\n", + "--- \na\n---\n", + "---\na: b\n", + "\n---\na\n---\n", + "---", + "---\na\n----\n", + ]: + with pytest.raises(FrontmatterError): + split_document(bad) + + +def test_values_stay_text() -> None: + parsed = parse_frontmatter( + "version: 1.10\nflag: no\nday: 2026-11-28\nn: null\nempty:\n" + "tags: [a, 1, true]\nnested:\n k: 0x10\n l:\n - 1e3\n" + ) + assert parsed == { + "version": "1.10", + "flag": "no", + "day": "2026-11-28", + "n": "null", + "empty": "", + "tags": ["a", "1", "true"], + "nested": {"k": "0x10", "l": ["1e3"]}, + } + + +@pytest.mark.parametrize( + "block", + [ + "", + "\n", + "# only a comment\n", + "a: [\n", + "a: b: c\n", + "- a\n- b\n", + "just text\n", + "~\n", + "a: 1\n---\nb: 2\n", + "a: 1\n...\n---\nb: 2\n", + "? [a, b]\n: c\n", + "? {a: b}\n: c\n", + "a: \x01\n", + "a: \ud800\n", + "a: \ufffe\n", + 'a: "\\ud800"\n', + '"\\ud800": a\n', + f"# comment{chr(0x2028)}type: source\n", + f"a: b{chr(0x85)}c\n", + "[" * 100000 + "\n", + ], +) +def test_invalid_frontmatter_raises(block: str) -> None: + with pytest.raises(FrontmatterError): + parse_frontmatter(block) + + +def test_deep_nesting_raises() -> None: + block = "a: " + "[" * 5000 + "]" * 5000 + "\n" + with pytest.raises(FrontmatterError): + parse_frontmatter(block) + # The limit is fixed, not the interpreter's recursion limit. + parse_frontmatter("a: " + "[" * 30 + "]" * 30 + "\n") + with pytest.raises(FrontmatterError, match="nested too deeply"): + parse_frontmatter("a: " + "[" * 40 + "]" * 40 + "\n") + + +def test_duplicate_key_raises() -> None: + for block in [ + "a: 1\na: 2\n", + "x:\n a: 1\n a: 2\n", + "x: {a: 1, a: 2}\n", + "l:\n - a: 1\n a: 2\n", + ]: + with pytest.raises(FrontmatterError): + parse_frontmatter(block) + + +def test_yaml_alias_raises() -> None: + for block in ["a: &x 1\nb: *x\n", "a: &x 1\n", "a: *x\n", "a: [&x 1, *x]\n", "a: &x\n b: c\n"]: + with pytest.raises(FrontmatterError): + parse_frontmatter(block) + + +def test_render_format() -> None: + assert ( + render_frontmatter({"id": "x", "tags": ["a", "b"], "none": []}) + == '---\nid: "x"\ntags: ["a", "b"]\nnone: []\n---\n' + ) + assert render_frontmatter({"t": 'a"b\\c\u0085\u00e4\U0001f600'}) == ( + '---\nt: "a\\"b\\\\c\\u0085\u00e4\U0001f600"\n---\n' + ) + + +def test_render_invalid_input_raises() -> None: + for fields in [{"Bad": "x"}, {"1a": "x"}, {"a-b": "x"}, {"": "x"}, {"a\n": "x"}]: + with pytest.raises(FrontmatterError): + render_frontmatter(fields) + with pytest.raises(FrontmatterError): + render_frontmatter({"a": "x\ud800"}) + with pytest.raises(FrontmatterError): + render_frontmatter({"a": ["x\udfff"]}) + + +def test_render_round_trips_any_text() -> None: + step = 2048 + for start in range(0, sys.maxunicode + 1, step): + chars = [chr(c) for c in range(start, min(start + step, sys.maxunicode + 1))] + text = "".join(c for c in chars if unicodedata.category(c) != "Cs") + rendered = render_frontmatter({"k": text, "l": [text, "x"]}) + block, body = split_document(rendered + "body") + assert body == "body" + assert parse_frontmatter(block) == {"k": text, "l": [text, "x"]} + for text in ["", " ", "---", "a\r\nb", "\ufeffx", "\ufffe\uffff", "#c", "\t"]: + block, _ = split_document(render_frontmatter({"k": text})) + assert parse_frontmatter(block) == {"k": text} diff --git a/tests/domain/test_identity.py b/tests/domain/test_identity.py new file mode 100644 index 0000000..ff1cde4 --- /dev/null +++ b/tests/domain/test_identity.py @@ -0,0 +1,117 @@ +import pytest + +from chemenu.domain.errors import InvalidPageIdError, InvalidTitleError +from chemenu.domain.identity import PageId, PageTitle + +VALID_ID = "01a238ea-2e6d-7157-ba55-5da7405095ff" + + +def test_valid_id() -> None: + assert PageId(VALID_ID).value == VALID_ID + assert PageId(VALID_ID.replace("ba55", "8a55")).value.startswith("01a2") + + +@pytest.mark.parametrize( + "value", + [ + "", + VALID_ID + "\n", + VALID_ID.upper(), + VALID_ID.replace("-7157", "-4157"), + VALID_ID.replace("ba55", "ca55"), + VALID_ID.replace("-", ""), + VALID_ID[:-1], + VALID_ID[:-1] + "g", + VALID_ID[:-1] + chr(0xFF10), + " " + VALID_ID, + ], +) +def test_invalid_id_raises(value: str) -> None: + with pytest.raises(InvalidPageIdError): + PageId(value) + + +@pytest.mark.parametrize( + "value", + [ + "Ordnungs-, Wisch- und Sanitätsdienst", + "Äpfel 🍎", + "a" * 252, + "CONSOLE", + "Aux-Plan", + "a.b", + "x%y", + "md", + "notes.mdx", + "a.md b", + "Familie 👨" + chr(0x200D) + "👩", + "Mi" + chr(0x200C) + "zan", + "🏴" + "".join(chr(0xE0000 + ord(c)) for c in "gbeng") + chr(0xE007F), + ], +) +def test_title_with_comma(value: str) -> None: + assert PageTitle(value).value == value + + +@pytest.mark.parametrize( + "value", + [ + "", + " ", + "ab", + "a:b", + 'a"b', + "a/b", + "a\\b", + "a|b", + "a?b", + "a*b", + "a[b", + "a]b", + "a#b", + "a^b", + "a%%b", + "a\tb", + "a\nb", + "a\x7fb", + "a\x85b", + f"a{chr(0x2028)}b", + f"a{chr(0x2029)}b", + ".a", + "a.", + " a", + "a ", + f"a{chr(0xA0)}", + f"{chr(0x3000)}a", + "con", + "CON", + "Con.txt", + "con .txt", + "NUL", + "prn", + "conin$", + "CONOUT$", + "aux", + "COM1", + "lpt9.x", + "COM¹", + "LPT²", + "COM³.a", + "e\u0301", + "a" * 253, + "ä" * 127, + "a\ud800b", + "README.md", + "notes.MD", + "x.Md", + "a" + chr(0x200B) + "b", + chr(0xFEFF) + "a", + "a" + chr(0x202E) + "b", + "a" + chr(0x00AD) + "b", + "a" + chr(0x2060) + "b", + ], +) +def test_invalid_title_raises(value: str) -> None: + with pytest.raises(InvalidTitleError): + PageTitle(value)