ruml-parser 1.0.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.
- ruml_parser/__init__.py +183 -0
- ruml_parser/internal/__init__.py +2 -0
- ruml_parser/internal/extension.py +91 -0
- ruml_parser/internal/mapping.py +731 -0
- ruml_parser/internal/ruml/__init__.py +237 -0
- ruml_parser/internal/ruml/actions/__init__.py +2 -0
- ruml_parser/internal/ruml/actions/actions_capability_declaration.py +23 -0
- ruml_parser/internal/ruml/actions/actions_node_capability.py +40 -0
- ruml_parser/internal/ruml/ai_query/__init__.py +2 -0
- ruml_parser/internal/ruml/ai_query/ai_query_capability_declaration.py +25 -0
- ruml_parser/internal/ruml/ai_query/ai_query_node_capability.py +66 -0
- ruml_parser/internal/ruml/aliases.py +93 -0
- ruml_parser/internal/ruml/capability/__init__.py +2 -0
- ruml_parser/internal/ruml/capability/abstract_capability_declaration.py +23 -0
- ruml_parser/internal/ruml/capability/abstract_node_capability.py +14 -0
- ruml_parser/internal/ruml/capability/capability_declaration.py +52 -0
- ruml_parser/internal/ruml/capability/capability_declarations.py +199 -0
- ruml_parser/internal/ruml/capability/extension_node_capability.py +17 -0
- ruml_parser/internal/ruml/capability/node_capabilities.py +113 -0
- ruml_parser/internal/ruml/capability/other_node_capability.py +21 -0
- ruml_parser/internal/ruml/context/__init__.py +2 -0
- ruml_parser/internal/ruml/context/context.py +40 -0
- ruml_parser/internal/ruml/context/context_capability_declaration.py +25 -0
- ruml_parser/internal/ruml/context/context_refs_node_capability.py +17 -0
- ruml_parser/internal/ruml/datapoints/__init__.py +2 -0
- ruml_parser/internal/ruml/datapoints/datapoint.py +101 -0
- ruml_parser/internal/ruml/datapoints/datapoint_set.py +20 -0
- ruml_parser/internal/ruml/datapoints/datapoints_capability_declaration.py +29 -0
- ruml_parser/internal/ruml/datapoints/option.py +11 -0
- ruml_parser/internal/ruml/expression/__init__.py +2 -0
- ruml_parser/internal/ruml/expression/expression_capability_declaration.py +23 -0
- ruml_parser/internal/ruml/expression/expression_node_capability.py +20 -0
- ruml_parser/internal/ruml/metadata.py +83 -0
- ruml_parser/internal/ruml/nodes/__init__.py +2 -0
- ruml_parser/internal/ruml/nodes/abstract_node.py +29 -0
- ruml_parser/internal/ruml/nodes/branch_node.py +15 -0
- ruml_parser/internal/ruml/nodes/leaf_node.py +10 -0
- ruml_parser/internal/ruml/nodes/node.py +6 -0
- ruml_parser/internal/ruml/protocol/__init__.py +2 -0
- ruml_parser/internal/ruml/protocol/protocol_capability_declaration.py +29 -0
- ruml_parser/internal/ruml/query/__init__.py +2 -0
- ruml_parser/internal/ruml/query/query_capability_declaration.py +23 -0
- ruml_parser/internal/ruml/query/query_node_capability.py +17 -0
- ruml_parser/internal/ruml/ruml_document.py +45 -0
- ruml_parser/internal/ruml/text_reference/__init__.py +2 -0
- ruml_parser/internal/ruml/text_reference/text.py +69 -0
- ruml_parser/internal/ruml/text_reference/text_reference_capability_declaration.py +25 -0
- ruml_parser/internal/ruml/text_reference/text_refs_node_capability.py +32 -0
- ruml_parser/internal/ruml/tree/__init__.py +2 -0
- ruml_parser/internal/ruml/tree/tree_capability_declarations.py +30 -0
- ruml_parser/internal/validation/__init__.py +14 -0
- ruml_parser/internal/validation/capabilities.py +227 -0
- ruml_parser/internal/validation/contexts.py +51 -0
- ruml_parser/internal/validation/datapoint_sets.py +125 -0
- ruml_parser/internal/validation/modular.py +42 -0
- ruml_parser/internal/validation/recursion.py +197 -0
- ruml_parser/internal/validation/root.py +36 -0
- ruml_parser/internal/validation/texts.py +50 -0
- ruml_parser/model/__init__.py +2 -0
- ruml_parser/model/ruml.py +1156 -0
- ruml_parser/model/ruml_result.py +430 -0
- ruml_parser/node_result_status.py +19 -0
- ruml_parser/pydantic.py +96 -0
- ruml_parser/ruml_parser.py +75 -0
- ruml_parser/schema_files.py +23 -0
- ruml_parser/schema_validation.py +354 -0
- ruml_parser/structural_error.py +36 -0
- ruml_parser/text.py +220 -0
- ruml_parser-1.0.0.dist-info/METADATA +119 -0
- ruml_parser-1.0.0.dist-info/RECORD +72 -0
- ruml_parser-1.0.0.dist-info/WHEEL +4 -0
- ruml_parser-1.0.0.dist-info/licenses/LICENSE +73 -0
|
@@ -0,0 +1,354 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 Rulemapping Group GmbH
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""Validation of RUML documents against ruml.schema.json and extensions' payload schemas."""
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import re
|
|
7
|
+
from collections.abc import Iterable, Mapping
|
|
8
|
+
from datetime import datetime
|
|
9
|
+
from functools import lru_cache
|
|
10
|
+
from typing import Any, Literal
|
|
11
|
+
|
|
12
|
+
import email_validator
|
|
13
|
+
import jsonschema
|
|
14
|
+
import regress
|
|
15
|
+
from referencing import Registry, Resource
|
|
16
|
+
from referencing.jsonschema import DRAFT202012
|
|
17
|
+
|
|
18
|
+
from ruml_parser.internal.extension import CapabilityExtension
|
|
19
|
+
from ruml_parser.schema_files import SCHEMA_PATH
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@lru_cache(maxsize=1)
|
|
23
|
+
def _schema() -> dict[str, Any]:
|
|
24
|
+
return _keep_paths_of_forbidden_properties(
|
|
25
|
+
json.loads(SCHEMA_PATH.read_text(encoding="utf-8"))
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _keep_paths_of_forbidden_properties(schema: Any) -> Any:
|
|
30
|
+
"""Replace each property schema `false` with its equivalent `{"not": {}}`.
|
|
31
|
+
|
|
32
|
+
jsonschema reports a `false` subschema's error without the property's path (its
|
|
33
|
+
`descend()` takes a shortcut for boolean schemas that skips setting it), so the
|
|
34
|
+
violation would be located at the object instead of at the forbidden property.
|
|
35
|
+
"""
|
|
36
|
+
if isinstance(schema, list):
|
|
37
|
+
return [_keep_paths_of_forbidden_properties(item) for item in schema]
|
|
38
|
+
if not isinstance(schema, dict):
|
|
39
|
+
return schema
|
|
40
|
+
result = {
|
|
41
|
+
key: _keep_paths_of_forbidden_properties(value) for key, value in schema.items()
|
|
42
|
+
}
|
|
43
|
+
for keyword in ("properties", "patternProperties"):
|
|
44
|
+
if isinstance(result.get(keyword), dict):
|
|
45
|
+
result[keyword] = {
|
|
46
|
+
name: {"not": {}} if subschema is False else subschema
|
|
47
|
+
for name, subschema in result[keyword].items()
|
|
48
|
+
}
|
|
49
|
+
return result
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def ruml_validator(
|
|
53
|
+
extensions: Iterable[CapabilityExtension] = (),
|
|
54
|
+
) -> jsonschema.protocols.Validator:
|
|
55
|
+
"""Build a validator of RUML documents that checks the payloads of ``extensions``.
|
|
56
|
+
|
|
57
|
+
Building one is not cheap, so reuse it where possible, as ``RumlParser`` does.
|
|
58
|
+
"""
|
|
59
|
+
extensions = tuple(extensions)
|
|
60
|
+
schema = _extended_schema(extensions) if extensions else _schema()
|
|
61
|
+
validator_cls = jsonschema.validators.validator_for(schema)
|
|
62
|
+
validator_cls.check_schema(schema)
|
|
63
|
+
resources: list[tuple[str, Mapping[str, Any]]] = [(_schema()["$id"], _schema())]
|
|
64
|
+
for extension in extensions:
|
|
65
|
+
schemas = extension.payload_schemas
|
|
66
|
+
root = _keep_paths_of_forbidden_properties(schemas.root)
|
|
67
|
+
node = _keep_paths_of_forbidden_properties(schemas.node)
|
|
68
|
+
resources.append((_payload_schema_uri(extension, "root"), root))
|
|
69
|
+
resources.append((_payload_schema_uri(extension, "node"), node))
|
|
70
|
+
registry = Registry().with_resources(
|
|
71
|
+
(uri, Resource.from_contents(contents, default_specification=DRAFT202012))
|
|
72
|
+
for uri, contents in resources
|
|
73
|
+
)
|
|
74
|
+
return validator_cls(schema, registry=registry, format_checker=_FORMAT_CHECKER)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
_RFC_3339_DATE_TIME = re.compile(
|
|
78
|
+
r"[0-9]{4}-[0-9]{2}-[0-9]{2}[Tt](?:[01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]"
|
|
79
|
+
r"(?:\.[0-9]+)?(?:[Zz]|[+-](?:[01][0-9]|2[0-3]):[0-5][0-9])"
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
_DURATION = re.compile(
|
|
83
|
+
r"P(?!$)(?:[0-9]+Y)?(?:[0-9]+M)?(?:[0-9]+D)?(?:T(?=[0-9])(?:[0-9]+H)?(?:[0-9]+M)?(?:[0-9]+S)?)?"
|
|
84
|
+
r"|P[0-9]+W"
|
|
85
|
+
)
|
|
86
|
+
"""RFC 3339 Appendix A durations, with the leniency of ajv-formats (`P1Y2D`)."""
|
|
87
|
+
|
|
88
|
+
_MAX_REGEX_LENGTH = 1000
|
|
89
|
+
_MAX_REGEX_NESTING = 64
|
|
90
|
+
"""Limits of a checkable pattern: beyond them `regress` can overflow a thread's stack,
|
|
91
|
+
which kills the process instead of raising."""
|
|
92
|
+
|
|
93
|
+
_FORMAT_CHECKER = jsonschema.FormatChecker(formats=())
|
|
94
|
+
"""Draft 2020-12's format checks, stricter for `date-time`, `duration` and `email`,
|
|
95
|
+
ECMA `regex`."""
|
|
96
|
+
_FORMAT_CHECKER.checkers.update(jsonschema.Draft202012Validator.FORMAT_CHECKER.checkers)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
@_FORMAT_CHECKER.checks("date-time")
|
|
100
|
+
def _is_rfc_3339_date_time(value: object) -> bool:
|
|
101
|
+
"""Whether a string is an RFC 3339 date-time; an offset is mandatory there.
|
|
102
|
+
|
|
103
|
+
Leap seconds (`23:59:60Z`) are rejected: a Python `datetime`, which the model holds
|
|
104
|
+
timestamps as, cannot represent them.
|
|
105
|
+
"""
|
|
106
|
+
if not isinstance(value, str):
|
|
107
|
+
return True
|
|
108
|
+
if not _RFC_3339_DATE_TIME.fullmatch(value):
|
|
109
|
+
return False
|
|
110
|
+
try:
|
|
111
|
+
datetime.fromisoformat(value.upper())
|
|
112
|
+
except ValueError:
|
|
113
|
+
return False
|
|
114
|
+
return True
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
@_FORMAT_CHECKER.checks("duration")
|
|
118
|
+
def _is_duration(value: object) -> bool:
|
|
119
|
+
"""Whether a string is a duration as the TypeScript parser accepts it.
|
|
120
|
+
|
|
121
|
+
jsonschema's own check (isoduration) also takes fractions and signs (`P0.5Y`,
|
|
122
|
+
`-P1D`), which RFC 3339 Appendix A does not.
|
|
123
|
+
"""
|
|
124
|
+
return not isinstance(value, str) or _DURATION.fullmatch(value) is not None
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
@_FORMAT_CHECKER.checks("email")
|
|
128
|
+
def _is_email(value: object) -> bool:
|
|
129
|
+
"""Whether a string is an address the model's `EmailStr` accepts as well."""
|
|
130
|
+
if not isinstance(value, str):
|
|
131
|
+
return True
|
|
132
|
+
try:
|
|
133
|
+
email_validator.validate_email(value, check_deliverability=False)
|
|
134
|
+
except email_validator.EmailNotValidError:
|
|
135
|
+
return False
|
|
136
|
+
return True
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
@_FORMAT_CHECKER.checks("regex")
|
|
140
|
+
def _is_ecma_262_regex(value: object) -> bool:
|
|
141
|
+
"""Whether a string is an ECMA-262 regular expression to `new RegExp(value)`.
|
|
142
|
+
|
|
143
|
+
That is without the `u` flag, as the TypeScript parser checks it, so the syntax of
|
|
144
|
+
Annex B is valid (`\\p` for `p`, a lone `]`). A string that `regress` cannot even
|
|
145
|
+
take, one with a lone surrogate, is rejected, and so is a pattern longer than
|
|
146
|
+
`_MAX_REGEX_LENGTH` or nested deeper than `_MAX_REGEX_NESTING`.
|
|
147
|
+
"""
|
|
148
|
+
if not isinstance(value, str):
|
|
149
|
+
return True
|
|
150
|
+
if len(value) > _MAX_REGEX_LENGTH or _regex_nesting(value) > _MAX_REGEX_NESTING:
|
|
151
|
+
return False
|
|
152
|
+
try:
|
|
153
|
+
regress.Regex(value)
|
|
154
|
+
except Exception:
|
|
155
|
+
return False
|
|
156
|
+
return True
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _regex_nesting(pattern: str) -> int:
|
|
160
|
+
"""How deep the groups of ``pattern`` nest; brackets in a class or escaped don't count."""
|
|
161
|
+
depth = deepest = 0
|
|
162
|
+
escaped = in_class = False
|
|
163
|
+
for char in pattern:
|
|
164
|
+
if escaped:
|
|
165
|
+
escaped = False
|
|
166
|
+
elif char == "\\":
|
|
167
|
+
escaped = True
|
|
168
|
+
elif in_class:
|
|
169
|
+
in_class = char != "]"
|
|
170
|
+
elif char == "[":
|
|
171
|
+
in_class = True
|
|
172
|
+
elif char == "(":
|
|
173
|
+
depth += 1
|
|
174
|
+
deepest = max(deepest, depth)
|
|
175
|
+
elif char == ")":
|
|
176
|
+
depth = max(depth - 1, 0)
|
|
177
|
+
return deepest
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _extended_schema(extensions: Iterable[CapabilityExtension]) -> dict[str, Any]:
|
|
181
|
+
"""Narrow the RUML schema to the payload schemas of ``extensions``.
|
|
182
|
+
|
|
183
|
+
The extensions' schemas describe payloads only. Lifted to whole documents (by
|
|
184
|
+
restating the path from the root down to the capability entries, and leaving
|
|
185
|
+
everything else unconstrained), they combine with the RUML schema by ``allOf`` into
|
|
186
|
+
a schema that a document satisfies if and only if it satisfies both.
|
|
187
|
+
"""
|
|
188
|
+
root_rules: list[dict[str, Any]] = []
|
|
189
|
+
node_rules: list[dict[str, Any]] = []
|
|
190
|
+
for extension in extensions:
|
|
191
|
+
root_uri = _payload_schema_uri(extension, "root")
|
|
192
|
+
node_uri = _payload_schema_uri(extension, "node")
|
|
193
|
+
root_rules.append(_payload_rule(extension.id, root_uri))
|
|
194
|
+
node_rules.append(_payload_rule(extension.id, node_uri))
|
|
195
|
+
lifted_node_rules = {
|
|
196
|
+
"properties": {"capabilities": {"items": {"allOf": node_rules}}}
|
|
197
|
+
}
|
|
198
|
+
return {
|
|
199
|
+
"$schema": _schema()["$schema"],
|
|
200
|
+
"allOf": [
|
|
201
|
+
{"$ref": _schema()["$id"]},
|
|
202
|
+
{
|
|
203
|
+
"properties": {
|
|
204
|
+
"capabilities": {"items": {"allOf": root_rules}},
|
|
205
|
+
"rulemap": {
|
|
206
|
+
"properties": {
|
|
207
|
+
"nodes": {"additionalProperties": lifted_node_rules}
|
|
208
|
+
}
|
|
209
|
+
},
|
|
210
|
+
}
|
|
211
|
+
},
|
|
212
|
+
],
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def _payload_rule(capability_id: str, payload_schema_uri: str) -> dict[str, Any]:
|
|
217
|
+
"""Build the schema rule picking a capability entry's payload schema by its id.
|
|
218
|
+
|
|
219
|
+
The rule works the way the RUML schema's rules in ``CapabilityEntry`` and
|
|
220
|
+
``NodeCapabilityEntry`` do.
|
|
221
|
+
"""
|
|
222
|
+
return {
|
|
223
|
+
"if": {"required": ["id"], "properties": {"id": {"const": capability_id}}},
|
|
224
|
+
"then": {"properties": {"payload": {"$ref": payload_schema_uri}}},
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def _payload_schema_uri(
|
|
229
|
+
extension: CapabilityExtension, level: Literal["root", "node"]
|
|
230
|
+
) -> str:
|
|
231
|
+
"""Name the URI of one of ``extension``'s payload schemas in an extended schema."""
|
|
232
|
+
return f"urn:ruml:capability-payload:{level}:{extension.id}"
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def json_pointer(path: Iterable[Any]) -> str:
|
|
236
|
+
"""RFC 6901 JSON Pointer for a sequence of path segments."""
|
|
237
|
+
|
|
238
|
+
def escape(segment: Any) -> str:
|
|
239
|
+
return str(segment).replace("~", "~0").replace("/", "~1")
|
|
240
|
+
|
|
241
|
+
return "".join(f"/{escape(segment)}" for segment in path)
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def offending_path(error: jsonschema.exceptions.ValidationError) -> list[Any]:
|
|
245
|
+
"""`error.absolute_path`, extended to the specific key that offends.
|
|
246
|
+
|
|
247
|
+
jsonschema reports `additionalProperties` and `propertyNames` failures
|
|
248
|
+
against the *container* — the extra or malformed key itself, though it
|
|
249
|
+
exists right there in the document, isn't part of `absolute_path`. Both
|
|
250
|
+
keywords make the offending key identifiable, so append it: the key
|
|
251
|
+
itself for `propertyNames` (`error.instance` *is* that key), and — for
|
|
252
|
+
`additionalProperties` — whichever instance key matches neither
|
|
253
|
+
`properties` nor `patternProperties` on the failing schema, the same
|
|
254
|
+
computation `additionalProperties` itself does.
|
|
255
|
+
"""
|
|
256
|
+
path: list[Any] = list(error.absolute_path)
|
|
257
|
+
if (
|
|
258
|
+
error.validator == "additionalProperties"
|
|
259
|
+
and isinstance(error.schema, dict)
|
|
260
|
+
and isinstance(error.instance, dict)
|
|
261
|
+
):
|
|
262
|
+
allowed = set(error.schema.get("properties", {}))
|
|
263
|
+
patterns = list(error.schema.get("patternProperties", {}))
|
|
264
|
+
extra = sorted(
|
|
265
|
+
key
|
|
266
|
+
for key in error.instance
|
|
267
|
+
if key not in allowed and not any(re.search(p, key) for p in patterns)
|
|
268
|
+
)
|
|
269
|
+
if extra:
|
|
270
|
+
path.append(extra[0])
|
|
271
|
+
elif "propertyNames" in error.schema_path:
|
|
272
|
+
path.append(error.instance)
|
|
273
|
+
return path
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def _resolve(
|
|
277
|
+
error: jsonschema.exceptions.ValidationError,
|
|
278
|
+
) -> jsonschema.exceptions.ValidationError:
|
|
279
|
+
"""Resolve one top-level error to the sub-error that best explains it.
|
|
280
|
+
|
|
281
|
+
A plain keyword failure explains itself. A `oneOf`/`anyOf` failure does
|
|
282
|
+
not — jsonschema's own `best_match()` over its branches can pick one
|
|
283
|
+
that's wrong only because of its own discriminator (a `const`/`enum`
|
|
284
|
+
mismatch) over a sibling branch that *is* the right variant and fails on
|
|
285
|
+
something substantive. E.g. `binding: {type: "external"}` failing the
|
|
286
|
+
`input` branch's `type == "input"` const is a worse explanation than
|
|
287
|
+
failing the `external` branch's `required: [ref]`. Prefer the
|
|
288
|
+
substantive branch when there is one.
|
|
289
|
+
"""
|
|
290
|
+
if error.validator not in ("oneOf", "anyOf") or not error.context:
|
|
291
|
+
return error
|
|
292
|
+
candidate = jsonschema.exceptions.best_match(error.context)
|
|
293
|
+
if candidate is None:
|
|
294
|
+
return error
|
|
295
|
+
if candidate.validator in ("const", "enum"):
|
|
296
|
+
siblings = [e for e in error.context if e.validator not in ("const", "enum")]
|
|
297
|
+
if siblings:
|
|
298
|
+
candidate = jsonschema.exceptions.best_match(siblings) or candidate
|
|
299
|
+
return candidate
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def _drop_redundant_patterns(
|
|
303
|
+
errors: list[jsonschema.exceptions.ValidationError],
|
|
304
|
+
) -> list[jsonschema.exceptions.ValidationError]:
|
|
305
|
+
"""Drop a `pattern` error when its subschema's `format` fails on the same value.
|
|
306
|
+
|
|
307
|
+
The schema pairs some formats with a pattern that narrows them (`Uuid`: a
|
|
308
|
+
lowercase v4 UUID); a value that is no UUID at all breaks both, and one error
|
|
309
|
+
says enough.
|
|
310
|
+
"""
|
|
311
|
+
|
|
312
|
+
def subschema(error: jsonschema.exceptions.ValidationError) -> tuple[Any, ...]:
|
|
313
|
+
return (*error.absolute_path, "@", *list(error.absolute_schema_path)[:-1])
|
|
314
|
+
|
|
315
|
+
failed_formats = {subschema(e) for e in errors if e.validator == "format"}
|
|
316
|
+
return [
|
|
317
|
+
error
|
|
318
|
+
for error in errors
|
|
319
|
+
if error.validator != "pattern" or subschema(error) not in failed_formats
|
|
320
|
+
]
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def _message(error: jsonschema.exceptions.ValidationError) -> str:
|
|
324
|
+
"""Word the error; a forbidden property reads as it did before the rewrite."""
|
|
325
|
+
if error.validator == "not" and error.validator_value == {}:
|
|
326
|
+
return f"False schema does not allow {error.instance!r}"
|
|
327
|
+
return error.message
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
class RumlValidationError(ValueError):
|
|
331
|
+
"""Raised by ``RumlParser`` when a document fails schema validation.
|
|
332
|
+
|
|
333
|
+
A document can be invalid in more than one place at once, and a caller
|
|
334
|
+
that only learns about one of them may "fix" it and resubmit only to
|
|
335
|
+
be rejected again for a different, previously-hidden reason. This
|
|
336
|
+
collects every independent violation `jsonschema` finds — resolved
|
|
337
|
+
through `_resolve()` — and exposes their locations as JSON Pointers
|
|
338
|
+
(`paths`) so callers — validation-test cases in particular — can check
|
|
339
|
+
*where* the document was rejected, not just that it was.
|
|
340
|
+
|
|
341
|
+
Rules the schema cannot express raise ``RumlStructuralError`` instead.
|
|
342
|
+
"""
|
|
343
|
+
|
|
344
|
+
errors: list[jsonschema.exceptions.ValidationError]
|
|
345
|
+
"""The resolved `jsonschema` errors."""
|
|
346
|
+
paths: list[str]
|
|
347
|
+
"""JSON Pointers of every offending location, sorted."""
|
|
348
|
+
|
|
349
|
+
def __init__(self, causes: Iterable[jsonschema.exceptions.ValidationError]):
|
|
350
|
+
self.errors = _drop_redundant_patterns([_resolve(cause) for cause in causes])
|
|
351
|
+
super().__init__("; ".join(_message(error) for error in self.errors))
|
|
352
|
+
self.paths = sorted(
|
|
353
|
+
{json_pointer(offending_path(error)) for error in self.errors}
|
|
354
|
+
)
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 Rulemapping Group GmbH
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""The error for Structural violations found on the internal model (ADR 0001)."""
|
|
4
|
+
|
|
5
|
+
from collections.abc import Iterable, Sequence
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@dataclass(frozen=True, slots=True)
|
|
10
|
+
class StructuralViolation:
|
|
11
|
+
"""One violated spec rule, with every location that violates it."""
|
|
12
|
+
|
|
13
|
+
rule: str
|
|
14
|
+
"""The RUML spec's code for the rule, e.g. ``OP-02``."""
|
|
15
|
+
message: str
|
|
16
|
+
paths: Sequence[str]
|
|
17
|
+
"""JSON Pointers of the offending locations in the RUML document."""
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class RumlStructuralError(ValueError):
|
|
21
|
+
"""Raised by ``to_internal``'s validators when a document violates a rule the schema cannot express.
|
|
22
|
+
|
|
23
|
+
Like ``RumlValidationError`` for the schema, it collects every violation found, so a
|
|
24
|
+
caller learns about all of them at once.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
violations: list[StructuralViolation]
|
|
28
|
+
|
|
29
|
+
def __init__(self, violations: Iterable[StructuralViolation]):
|
|
30
|
+
self.violations = list(violations)
|
|
31
|
+
super().__init__(
|
|
32
|
+
"; ".join(
|
|
33
|
+
f"{violation.message} (spec rule {violation.rule})"
|
|
34
|
+
for violation in self.violations
|
|
35
|
+
)
|
|
36
|
+
)
|
ruml_parser/text.py
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 Rulemapping Group GmbH
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""RUML Text (§4.12) in its JSON form: `{type, attrs?, content?}` elements and strings.
|
|
4
|
+
|
|
5
|
+
Reading inserts the whitespace the builder does not write: a `num` runs into what
|
|
6
|
+
follows with a space, every other element is a line of its own. Writing follows
|
|
7
|
+
the builder's norm editor: rows go in, `akomaNtoso > act > (preamble,) body` comes
|
|
8
|
+
out, an element carries its row's id as `GUID` and its parts derive theirs from it.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import hashlib
|
|
14
|
+
import json
|
|
15
|
+
import re
|
|
16
|
+
from collections.abc import Iterable
|
|
17
|
+
from dataclasses import dataclass
|
|
18
|
+
from decimal import Decimal
|
|
19
|
+
from typing import Any
|
|
20
|
+
|
|
21
|
+
LDML_NAMESPACE = "http://Inhaltsdaten.LegalDocML.de/1.8.2/"
|
|
22
|
+
"""Default namespace of the texts written here; it names their dialect (§4.12)."""
|
|
23
|
+
GUID_ATTR = "GUID"
|
|
24
|
+
|
|
25
|
+
Element = dict[str, Any]
|
|
26
|
+
|
|
27
|
+
_PARAGRAPH_NUM = re.compile(r"^\((\d+[a-z]?)\)\s*")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _separator(previous: Any, current: Any) -> str:
|
|
31
|
+
if isinstance(previous, str) and isinstance(current, str):
|
|
32
|
+
return ""
|
|
33
|
+
if isinstance(previous, dict) and previous.get("type") == "num":
|
|
34
|
+
return " "
|
|
35
|
+
return "\n"
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def text_of(tree: Any) -> str:
|
|
39
|
+
"""Return the readable text of a RUML Text element."""
|
|
40
|
+
if isinstance(tree, str):
|
|
41
|
+
return tree
|
|
42
|
+
if not isinstance(tree, dict):
|
|
43
|
+
return ""
|
|
44
|
+
text = ""
|
|
45
|
+
previous: Any = None
|
|
46
|
+
for child in tree.get("content") or ():
|
|
47
|
+
child_text = text_of(child)
|
|
48
|
+
# an empty element (an unnumbered paragraph's `num`) takes no space
|
|
49
|
+
if not child_text and isinstance(child, dict):
|
|
50
|
+
continue
|
|
51
|
+
text += ("" if previous is None else _separator(previous, child)) + child_text
|
|
52
|
+
previous = child
|
|
53
|
+
return text
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def elements_by_guid(tree: Any) -> dict[str, Element]:
|
|
57
|
+
"""Return the elements of `tree` keyed by their GUID, in document order."""
|
|
58
|
+
index: dict[str, Element] = {}
|
|
59
|
+
|
|
60
|
+
def walk(node: Any) -> None:
|
|
61
|
+
if not isinstance(node, dict):
|
|
62
|
+
return
|
|
63
|
+
guid = (node.get("attrs") or {}).get(GUID_ATTR)
|
|
64
|
+
if isinstance(guid, str):
|
|
65
|
+
index[guid] = node
|
|
66
|
+
for child in node.get("content") or ():
|
|
67
|
+
walk(child)
|
|
68
|
+
|
|
69
|
+
walk(tree)
|
|
70
|
+
return index
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def derived_guid(owner: str, role: str) -> str:
|
|
74
|
+
"""Return the GUID of an element's `role` under `owner`, stable across runs.
|
|
75
|
+
|
|
76
|
+
The same derivation as the builder's `derivedGuid`.
|
|
77
|
+
"""
|
|
78
|
+
digest = bytearray(hashlib.sha256(f"{owner}/{role}".encode()).digest()[:16])
|
|
79
|
+
digest[6] = (digest[6] & 0x0F) | 0x80
|
|
80
|
+
digest[8] = (digest[8] & 0x3F) | 0x80
|
|
81
|
+
hex_ = digest.hex()
|
|
82
|
+
return f"{hex_[:8]}-{hex_[8:12]}-{hex_[12:16]}-{hex_[16:20]}-{hex_[20:]}"
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _number(value: float) -> str:
|
|
86
|
+
"""Return `value` as ECMAScript's Number::toString writes it, as RFC 8785 asks."""
|
|
87
|
+
if value == 0:
|
|
88
|
+
return "0"
|
|
89
|
+
sign = "-" if value < 0 else ""
|
|
90
|
+
_, digit_tuple, exponent = Decimal(repr(abs(value))).normalize().as_tuple()
|
|
91
|
+
digits = "".join(map(str, digit_tuple))
|
|
92
|
+
point = int(exponent) + len(digits)
|
|
93
|
+
if len(digits) <= point <= 21:
|
|
94
|
+
return sign + digits + "0" * (point - len(digits))
|
|
95
|
+
if 0 < point <= 21:
|
|
96
|
+
return sign + digits[:point] + "." + digits[point:]
|
|
97
|
+
if -6 < point <= 0:
|
|
98
|
+
return sign + "0." + "0" * -point + digits
|
|
99
|
+
mantissa = digits[0] + ("." + digits[1:] if len(digits) > 1 else "")
|
|
100
|
+
return f"{sign}{mantissa}e{'+' if point > 0 else '-'}{abs(point - 1)}"
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _utf16(key: str) -> bytes:
|
|
104
|
+
return key.encode("utf-16-be")
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _canonical(value: Any) -> str:
|
|
108
|
+
if isinstance(value, dict):
|
|
109
|
+
keys = sorted(value, key=_utf16)
|
|
110
|
+
members = (f"{_canonical(k)}:{_canonical(value[k])}" for k in keys)
|
|
111
|
+
return "{" + ",".join(members) + "}"
|
|
112
|
+
if isinstance(value, list):
|
|
113
|
+
return "[" + ",".join(_canonical(item) for item in value) + "]"
|
|
114
|
+
if isinstance(value, float):
|
|
115
|
+
return _number(value)
|
|
116
|
+
return json.dumps(value, ensure_ascii=False)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def digest(value: Any) -> str:
|
|
120
|
+
"""Return the SHA3-256 digest of `value` in RFC 8785 form."""
|
|
121
|
+
return "sha3-256:" + hashlib.sha3_256(_canonical(value).encode()).hexdigest()
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
@dataclass(frozen=True)
|
|
125
|
+
class Row:
|
|
126
|
+
"""One line of a text; with a `unit` ("article", "chapter", …) a heading."""
|
|
127
|
+
|
|
128
|
+
id: str
|
|
129
|
+
text: str
|
|
130
|
+
unit: str | None = None
|
|
131
|
+
num: str = ""
|
|
132
|
+
level: int = 0
|
|
133
|
+
"""Rank of an outline unit; it closes the open units of its rank or below."""
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _element(type_: str, guid: str, content: list[Any]) -> Element:
|
|
137
|
+
return {"type": type_, "attrs": {GUID_ATTR: guid}, "content": content}
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _leaf(type_: str, guid: str, text: str) -> Element:
|
|
141
|
+
return _element(type_, guid, [text] if text else [])
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _heading(row: Row) -> Element:
|
|
145
|
+
content = [_leaf("num", derived_guid(row.id, "num"), row.num)]
|
|
146
|
+
if row.text:
|
|
147
|
+
content.append(_leaf("heading", derived_guid(row.id, "heading"), row.text))
|
|
148
|
+
return _element(row.unit or "article", row.id, content)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _paragraph(guid: str, num: str) -> Element:
|
|
152
|
+
return _element(
|
|
153
|
+
"paragraph",
|
|
154
|
+
guid,
|
|
155
|
+
[
|
|
156
|
+
_leaf("num", derived_guid(guid, "num"), num),
|
|
157
|
+
_element("content", derived_guid(guid, "content"), []),
|
|
158
|
+
],
|
|
159
|
+
)
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def ruml_text(owner: str, rows: Iterable[Row]) -> Element:
|
|
163
|
+
"""Return `rows` as a RUML Text document whose own GUIDs derive from `owner`.
|
|
164
|
+
|
|
165
|
+
An outline unit nests by level, an article opens on its heading row, a `(1)`
|
|
166
|
+
row opens a numbered paragraph, and a free row joins the open paragraph, an
|
|
167
|
+
implicit one, or the preamble before anything else.
|
|
168
|
+
"""
|
|
169
|
+
body = _element("body", derived_guid(owner, "body"), [])
|
|
170
|
+
preamble: Element | None = None
|
|
171
|
+
outline: list[tuple[int, Element]] = []
|
|
172
|
+
article: Element | None = None
|
|
173
|
+
paragraph: Element | None = None
|
|
174
|
+
|
|
175
|
+
def container() -> Element:
|
|
176
|
+
return outline[-1][1] if outline else body
|
|
177
|
+
|
|
178
|
+
def open_paragraph(node: Element) -> Element:
|
|
179
|
+
(article or container())["content"].append(node)
|
|
180
|
+
return node
|
|
181
|
+
|
|
182
|
+
for row in rows:
|
|
183
|
+
if row.unit == "article":
|
|
184
|
+
article, paragraph = _heading(row), None
|
|
185
|
+
container()["content"].append(article)
|
|
186
|
+
elif row.unit:
|
|
187
|
+
while outline and outline[-1][0] >= row.level:
|
|
188
|
+
outline.pop()
|
|
189
|
+
node = _heading(row)
|
|
190
|
+
container()["content"].append(node)
|
|
191
|
+
outline.append((row.level, node))
|
|
192
|
+
article = paragraph = None
|
|
193
|
+
elif not row.text:
|
|
194
|
+
continue
|
|
195
|
+
elif match := _PARAGRAPH_NUM.match(row.text):
|
|
196
|
+
paragraph = open_paragraph(_paragraph(row.id, f"({match.group(1)})"))
|
|
197
|
+
text = row.text[match.end() :]
|
|
198
|
+
paragraph["content"][1]["content"].append(
|
|
199
|
+
_leaf("p", derived_guid(row.id, "p"), text)
|
|
200
|
+
)
|
|
201
|
+
elif article is None and paragraph is None and not body["content"]:
|
|
202
|
+
preamble = preamble or _element(
|
|
203
|
+
"preamble", derived_guid(owner, "preamble"), []
|
|
204
|
+
)
|
|
205
|
+
preamble["content"].append(_leaf("p", row.id, row.text))
|
|
206
|
+
else:
|
|
207
|
+
if paragraph is None:
|
|
208
|
+
paragraph = open_paragraph(
|
|
209
|
+
_paragraph(derived_guid(row.id, "paragraph"), "")
|
|
210
|
+
)
|
|
211
|
+
paragraph["content"][1]["content"].append(_leaf("p", row.id, row.text))
|
|
212
|
+
|
|
213
|
+
act = [preamble, body] if preamble else [body]
|
|
214
|
+
return {
|
|
215
|
+
"type": "akomaNtoso",
|
|
216
|
+
"attrs": {"xmlns": LDML_NAMESPACE},
|
|
217
|
+
"content": [
|
|
218
|
+
{"type": "act", "attrs": {"name": "regelungstext"}, "content": act}
|
|
219
|
+
],
|
|
220
|
+
}
|