formkrafter 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,39 @@
1
+ """FormKrafter for Python backends: the spec compiled to the browser's validation schema, and submitted
2
+ data validated with it — same error keys, same messages, same verdict as `@streamline-pulse/formkrafter-core`.
3
+ """
4
+
5
+ from formkrafter.lint import SpecIssue, lint_spec, validation_warnings
6
+ from formkrafter.messages import default_validation_message, register_validation_messages
7
+ from formkrafter.spec import (
8
+ BrickSpec,
9
+ build_validation_schema,
10
+ default_form_data,
11
+ iterate_bricks,
12
+ iterate_schema_bricks,
13
+ resolve_localized_text,
14
+ )
15
+ from formkrafter.validate import ErrorDetail, SpecNotSupported, ValidationResult, assert_supported, validate_form_data
16
+
17
+ __version__ = "0.1.0"
18
+ # The core release whose behaviour this version reproduces (python/tests/parity/expected.json).
19
+ CORE_VERSION = "0.33.0"
20
+
21
+ __all__ = [
22
+ "CORE_VERSION",
23
+ "BrickSpec",
24
+ "ErrorDetail",
25
+ "SpecIssue",
26
+ "SpecNotSupported",
27
+ "ValidationResult",
28
+ "assert_supported",
29
+ "build_validation_schema",
30
+ "default_form_data",
31
+ "default_validation_message",
32
+ "iterate_bricks",
33
+ "iterate_schema_bricks",
34
+ "lint_spec",
35
+ "register_validation_messages",
36
+ "resolve_localized_text",
37
+ "validate_form_data",
38
+ "validation_warnings",
39
+ ]
formkrafter/_js.py ADDED
@@ -0,0 +1,150 @@
1
+ """JavaScript semantics the core relies on: `Number()`, `String()` of a number, Ajv's formats and `RegExp`.
2
+
3
+ The core runs in a JavaScript engine and Ajv; the port reproduces the few places where Python would
4
+ otherwise disagree (`String(1e-7)` is "1e-7", `$` never matches before a trailing newline, `\\d` is ASCII).
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import math
10
+ from decimal import Decimal
11
+ from typing import Any
12
+
13
+ try: # `\p{L}` and other `u`-flag classes, when the optional `regex` module is installed
14
+ import regex as _re # type: ignore[import-not-found, import-untyped, unused-ignore]
15
+ except ImportError: # pragma: no cover - exercised when regex is absent
16
+ import re as _re
17
+
18
+ Number = int | float
19
+
20
+
21
+ def to_number(value: Any) -> Number:
22
+ """`Number(value)`: "12" is 12, "" and null are 0, true is 1, anything unreadable is NaN."""
23
+ if isinstance(value, bool):
24
+ return int(value)
25
+ if value is None:
26
+ return 0
27
+ if isinstance(value, int | float):
28
+ return _tidy(float(value)) if isinstance(value, float) else value
29
+ if isinstance(value, str):
30
+ text = value.strip()
31
+ if not text:
32
+ return 0
33
+ lowered = text.lower()
34
+ for prefix, base in (("0x", 16), ("0o", 8), ("0b", 2)):
35
+ if lowered.startswith(prefix):
36
+ try:
37
+ return int(text[2:], base)
38
+ except ValueError:
39
+ return math.nan
40
+ if text in ("Infinity", "+Infinity"):
41
+ return math.inf
42
+ if text == "-Infinity":
43
+ return -math.inf
44
+ if "_" in text or lowered.lstrip("+-") in ("inf", "infinity", "nan"):
45
+ return math.nan
46
+ try:
47
+ return _tidy(float(text))
48
+ except ValueError:
49
+ return math.nan
50
+ if isinstance(value, list) and len(value) <= 1:
51
+ return to_number(value[0]) if value else 0
52
+ return math.nan
53
+
54
+
55
+ def _tidy(n: float) -> Number:
56
+ """An integral float as an int (JSON writes 3, not 3.0), within the range JavaScript counts exactly."""
57
+ return int(n) if n.is_integer() and abs(n) < 2**53 else n
58
+
59
+
60
+ def number_to_string(n: Number) -> str:
61
+ """`String(n)`: 1 → "1", 0.5 → "0.5", 1e-7 → "1e-7", 1e21 → "1e+21"."""
62
+ if isinstance(n, bool):
63
+ return "true" if n else "false"
64
+ if isinstance(n, int):
65
+ n_float = float(n)
66
+ if abs(n) < 10**21:
67
+ return str(n)
68
+ n = n_float
69
+ if math.isnan(n):
70
+ return "NaN"
71
+ if math.isinf(n):
72
+ return "Infinity" if n > 0 else "-Infinity"
73
+ if n == 0:
74
+ return "0"
75
+ digits = Decimal(repr(n))
76
+ if 1e-6 <= abs(n) < 1e21:
77
+ text = format(digits, "f")
78
+ return text.rstrip("0").rstrip(".") if "." in text else text
79
+ sign, coefficient, exponent = digits.normalize().as_tuple()
80
+ mantissa = "".join(map(str, coefficient))
81
+ exp = exponent + len(mantissa) - 1 # type: ignore[operator]
82
+ body = mantissa[0] + ("." + mantissa[1:] if len(mantissa) > 1 else "")
83
+ return f"{'-' if sign else ''}{body}e{'+' if exp >= 0 else '-'}{abs(exp)}"
84
+
85
+
86
+ def to_string(value: Any) -> str:
87
+ """`String(value ?? "")`, as the default messages interpolate `{value}`."""
88
+ if value is None:
89
+ return ""
90
+ if isinstance(value, bool):
91
+ return "true" if value else "false"
92
+ if isinstance(value, int | float):
93
+ return number_to_string(value)
94
+ if isinstance(value, list):
95
+ return ",".join("" if v is None else to_string(v) for v in value)
96
+ if isinstance(value, dict):
97
+ return "[object Object]"
98
+ return str(value)
99
+
100
+
101
+ def compile_pattern(pattern: str) -> Any:
102
+ """`new RegExp(pattern, "u")` as a Python pattern: `$` anchors the end only, named groups, ASCII `\\d` and `\\w`."""
103
+ out: list[str] = []
104
+ in_class = False
105
+ i = 0
106
+ while i < len(pattern):
107
+ c = pattern[i]
108
+ if c == "\\" and i + 1 < len(pattern):
109
+ escape = pattern[i + 1]
110
+ if in_class:
111
+ out.append(_CLASS_ESCAPES.get(escape, pattern[i : i + 2]))
112
+ else:
113
+ out.append(_ESCAPES.get(escape, pattern[i : i + 2]))
114
+ i += 2
115
+ continue
116
+ if in_class:
117
+ if c == "]":
118
+ in_class = False
119
+ elif c == "[":
120
+ in_class = True
121
+ elif c == "$":
122
+ c = r"\Z"
123
+ elif pattern.startswith("(?<", i) and not pattern.startswith(("(?<=", "(?<!"), i):
124
+ c, i = "(?P<", i + 2
125
+ out.append(c)
126
+ i += 1
127
+ return _re.compile("".join(out))
128
+
129
+
130
+ # Under the `u` flag \d and \w are ASCII, while Python's are Unicode; \s stays Unicode in both.
131
+ _ESCAPES = {"d": "[0-9]", "D": "[^0-9]", "w": "[A-Za-z0-9_]", "W": "[^A-Za-z0-9_]"}
132
+ _CLASS_ESCAPES = {"d": "0-9", "w": "A-Za-z0-9_"}
133
+
134
+
135
+ # ajv-formats 3, "full" mode, verbatim (the core registers them with `addFormats(ajv, ["email", "uri"])`).
136
+ # They carry no `u` flag, so digits and case folding are ASCII.
137
+ _EMAIL = _re.compile(
138
+ r"^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\Z",
139
+ _re.IGNORECASE | _re.ASCII,
140
+ )
141
+ _NOT_URI_FRAGMENT = _re.compile(r"/|:")
142
+ _URI = _re.compile(
143
+ r"^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?\Z",
144
+ _re.IGNORECASE | _re.ASCII,
145
+ )
146
+
147
+ FORMATS = {
148
+ "email": lambda s: bool(_EMAIL.search(s)),
149
+ "uri": lambda s: bool(_NOT_URI_FRAGMENT.search(s)) and bool(_URI.search(s)),
150
+ }
formkrafter/lint.py ADDED
@@ -0,0 +1,99 @@
1
+ """Spec checks — `utils/lint-spec.ts` in the core: what silently breaks validation, on the client and the server."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from typing import Any, Literal
7
+
8
+ from formkrafter.spec import configs_of, iterate_bricks, truthy
9
+
10
+ SpecIssueCode = Literal[
11
+ "validations-without-data-type",
12
+ "input-without-key",
13
+ "duplicate-key",
14
+ "collection-without-children",
15
+ ]
16
+
17
+
18
+ @dataclass(frozen=True)
19
+ class SpecIssue:
20
+ code: SpecIssueCode
21
+ path: str
22
+ message: str
23
+ key: str | None = field(default=None)
24
+
25
+ def to_dict(self) -> dict[str, Any]:
26
+ """The issue as the core returns it (no `key` when the brick has none)."""
27
+ out: dict[str, Any] = {"code": self.code, "path": self.path}
28
+ if self.key is not None:
29
+ out["key"] = self.key
30
+ out["message"] = self.message
31
+ return out
32
+
33
+
34
+ def lint_spec(spec: Any) -> list[SpecIssue]:
35
+ """Issues of a spec: keyless inputs, validations without a dataType, duplicate keys, empty collections."""
36
+ issues: list[SpecIssue] = []
37
+ seen: dict[str, str] = {}
38
+
39
+ for brick, path in iterate_bricks(spec):
40
+ key: Any = configs_of(brick).get("key")
41
+ has_key = truthy(key)
42
+ brick_type = brick.get("type")
43
+ carries_data = brick_type in ("input", "collection")
44
+
45
+ if carries_data:
46
+ if not has_key:
47
+ issues.append(
48
+ SpecIssue(
49
+ "input-without-key",
50
+ path,
51
+ f'{brick_type} brick "{brick.get("id")}" has no configs.key — '
52
+ "it carries no data and is skipped by validation",
53
+ )
54
+ )
55
+ elif not truthy(brick.get("dataType")) or brick.get("dataType") == "void":
56
+ validations = brick.get("validations") or []
57
+ if validations:
58
+ issues.append(
59
+ SpecIssue(
60
+ "validations-without-data-type",
61
+ path,
62
+ f'"{key}" declares {len(validations)} validation(s) but has no dataType — '
63
+ "they are silently skipped, on the client and on the server",
64
+ key,
65
+ )
66
+ )
67
+
68
+ if has_key and carries_data:
69
+ previous = seen.get(key)
70
+ if previous:
71
+ issues.append(
72
+ SpecIssue(
73
+ "duplicate-key",
74
+ path,
75
+ f'key "{key}" is used by two bricks ({previous} and {path}) — '
76
+ "their values collide in the form data",
77
+ key,
78
+ )
79
+ )
80
+ else:
81
+ seen[key] = path
82
+
83
+ if brick_type == "collection" and not brick.get("children"):
84
+ issues.append(
85
+ SpecIssue(
86
+ "collection-without-children",
87
+ path,
88
+ f'collection "{key if key is not None else brick.get("id")}" has no row template — '
89
+ "it can never produce data",
90
+ key,
91
+ )
92
+ )
93
+
94
+ return issues
95
+
96
+
97
+ def validation_warnings(spec: Any) -> list[str]:
98
+ """The lint messages that `validate_form_data` returns as warnings."""
99
+ return [issue.message for issue in lint_spec(spec) if issue.code == "validations-without-data-type"]
@@ -0,0 +1,68 @@
1
+ """Default validation messages, per locale — `validators/default-messages.ts` in the core."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping
6
+ from typing import Any
7
+
8
+ from formkrafter._js import to_string
9
+
10
+ _MESSAGES: dict[str, dict[str, str]] = {
11
+ "en": {
12
+ "required": "This field is required",
13
+ "minLength": "Must be at least {value} characters",
14
+ "maxLength": "Must be at most {value} characters",
15
+ "min": "Must be at least {value}",
16
+ "max": "Must be at most {value}",
17
+ "pattern": "Invalid format",
18
+ "minItems": "Select at least {value} item(s)",
19
+ "maxItems": "Select at most {value} item(s)",
20
+ "email": "Invalid email address",
21
+ "url": "Invalid URL",
22
+ "type": "Invalid value",
23
+ "custom": "Invalid value",
24
+ "identity": "Invalid identifier for this format",
25
+ "iban": "Invalid IBAN",
26
+ "dateRange": "The end before the start is not allowed",
27
+ "mrz": "Machine-readable zone unreadable or inconsistent",
28
+ "plate": "Invalid registration plate for this format",
29
+ "registry": "Invalid registration number for this format",
30
+ },
31
+ "fr": {
32
+ "required": "Ce champ est obligatoire",
33
+ "minLength": "Minimum {value} caractères",
34
+ "maxLength": "Maximum {value} caractères",
35
+ "min": "Minimum {value}",
36
+ "max": "Maximum {value}",
37
+ "pattern": "Format invalide",
38
+ "minItems": "Sélectionnez au moins {value} élément(s)",
39
+ "maxItems": "Sélectionnez au plus {value} élément(s)",
40
+ "email": "Adresse email invalide",
41
+ "url": "URL invalide",
42
+ "type": "Valeur invalide",
43
+ "custom": "Valeur invalide",
44
+ "identity": "Identifiant invalide pour ce format",
45
+ "iban": "IBAN invalide",
46
+ "dateRange": "La fin ne peut pas précéder le début",
47
+ "mrz": "Zone de lecture illisible ou incohérente",
48
+ "plate": "Immatriculation invalide pour ce format",
49
+ "registry": "Numéro d’immatriculation invalide pour ce format",
50
+ },
51
+ }
52
+
53
+
54
+ def register_validation_messages(locale: str, messages: Mapping[str, str]) -> None:
55
+ """Add or override the default messages of a locale (`registerValidationMessages`).
56
+
57
+ Register the same messages on the client, or the server and the browser word their errors differently.
58
+ """
59
+ _MESSAGES[locale] = {**_MESSAGES.get(locale, {}), **messages}
60
+
61
+
62
+ def default_validation_message(validator: str, locale: str | None = None, value: Any = None) -> str:
63
+ """The default message of a validator, with `{value}` filled in; English when the locale has none."""
64
+ pack = _MESSAGES.get("en" if locale is None else locale, _MESSAGES["en"])
65
+ template = pack.get(validator)
66
+ if template is None:
67
+ template = _MESSAGES["en"].get(validator, "Invalid value")
68
+ return template.replace("{value}", to_string(value), 1)
formkrafter/models.py ADDED
@@ -0,0 +1,64 @@
1
+ """Pydantic models of a spec (`pip install formkrafter[pydantic]`), for backends that build specs in code.
2
+
3
+ Every function of the package takes these models or plain dicts alike. The models are permissive:
4
+ unknown fields are kept, so a spec from a newer core still round-trips.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from typing import Any, Literal
10
+
11
+ from pydantic import BaseModel, ConfigDict, Field
12
+
13
+ LocalizedText = str | dict[str, str]
14
+ JSONSchemaType = Literal["string", "number", "integer", "boolean", "object", "array", "null", "void"]
15
+
16
+
17
+ class _Model(BaseModel):
18
+ model_config = ConfigDict(extra="allow", populate_by_name=True)
19
+
20
+
21
+ class Validation(_Model):
22
+ validator: str
23
+ message: LocalizedText | None = None
24
+ value: Any = None
25
+ custom_validator: str | None = Field(default=None, alias="customValidator")
26
+
27
+
28
+ class EffectProperty(_Model):
29
+ target: str
30
+ type: Literal["logic", "code", "boolean", "string"]
31
+
32
+
33
+ class Effect(_Model):
34
+ name: str | None = None
35
+ property: EffectProperty | None = None
36
+ logic: Any = None
37
+ code: str | None = None
38
+ boolean: bool | None = None
39
+ string: str | None = None
40
+
41
+
42
+ class Rule(_Model):
43
+ name: str
44
+ type: Literal["jsonLogic", "javaScript"]
45
+ logic: Any = None
46
+ code: str | None = None
47
+ effects: list[Effect] | None = None
48
+
49
+
50
+ class BrickSpec(_Model):
51
+ type: Literal["panel", "input", "collection", "output", "action"]
52
+ id: str
53
+ name: str
54
+ data_type: JSONSchemaType | list[JSONSchemaType] | None = Field(default=None, alias="dataType")
55
+ category: str | None = None
56
+ validations: list[Validation] | None = None
57
+ rules: list[Rule] | None = None
58
+ configs: dict[str, Any] | None = None
59
+ styles: dict[str, Any] | None = None
60
+ children: list[BrickSpec] | None = None
61
+
62
+ def to_spec(self) -> dict[str, Any]:
63
+ """The spec as JSON for the client: camelCase keys, unset fields left out."""
64
+ return self.model_dump(by_alias=True, exclude_none=True)
formkrafter/py.typed ADDED
File without changes
formkrafter/spec.py ADDED
@@ -0,0 +1,186 @@
1
+ """Specs: walking the brick tree, localized text and the validation schema — `utils/brick-spec.ts` in the core."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterator, Mapping
6
+ from typing import Any
7
+
8
+ from formkrafter._js import to_number
9
+ from formkrafter.messages import default_validation_message
10
+
11
+ BrickSpec = Mapping[str, Any]
12
+
13
+
14
+ def as_spec(spec: Any) -> BrickSpec | None:
15
+ """A spec as a plain mapping: dicts pass through, Pydantic models (`formkrafter.models`) are dumped."""
16
+ if spec is None or isinstance(spec, Mapping):
17
+ return spec
18
+ dump = getattr(spec, "model_dump", None)
19
+ if dump is None:
20
+ raise TypeError(f"expected a brick spec (mapping or Pydantic model), got {type(spec).__name__}")
21
+ dumped: BrickSpec = dump(by_alias=True, exclude_none=True)
22
+ return dumped
23
+
24
+
25
+ def truthy(value: Any) -> bool:
26
+ """JavaScript truthiness: an empty list or object is true, "" and 0 are false."""
27
+ if isinstance(value, list | dict):
28
+ return True
29
+ return bool(value)
30
+
31
+
32
+ def configs_of(brick: BrickSpec) -> Mapping[str, Any]:
33
+ configs = brick.get("configs")
34
+ return configs if isinstance(configs, Mapping) else {}
35
+
36
+
37
+ def iterate_bricks(spec: Any, path: str = "0") -> Iterator[tuple[BrickSpec, str]]:
38
+ """Every brick of the tree with its path ("0.1.2"), collections included (`iterateBricks`)."""
39
+ spec = as_spec(spec)
40
+ if not spec:
41
+ return
42
+ yield spec, path
43
+ for index, child in enumerate(spec.get("children") or []):
44
+ yield from iterate_bricks(child, f"{path}.{index}")
45
+
46
+
47
+ def iterate_schema_bricks(spec: Any) -> Iterator[BrickSpec]:
48
+ """The bricks whose data sits at this level: a collection is yielded, its rows are not (`iterateSchemaBricks`)."""
49
+ spec = as_spec(spec)
50
+ if not spec:
51
+ return
52
+ yield spec
53
+ if spec.get("type") == "collection":
54
+ return
55
+ for child in spec.get("children") or []:
56
+ yield from iterate_schema_bricks(child)
57
+
58
+
59
+ def is_localized_object(value: Any) -> bool:
60
+ return isinstance(value, Mapping) and len(value) > 0 and all(isinstance(entry, str) for entry in value.values())
61
+
62
+
63
+ def resolve_localized_text(value: Any, locale: str | None = None) -> Any:
64
+ """`{"fr": "…", "en": "…"}` in the locale, else its first entry; any other value as is."""
65
+ if not is_localized_object(value):
66
+ return value
67
+ if locale and locale in value:
68
+ return value[locale]
69
+ return next(iter(value.values()))
70
+
71
+
72
+ def default_form_data(spec: Any) -> dict[str, Any]:
73
+ """The `defaultValue` of every keyed brick at this level, first brick wins (`defaultFormData`)."""
74
+ defaults: dict[str, Any] = {}
75
+ for brick in iterate_schema_bricks(spec):
76
+ configs = configs_of(brick)
77
+ key: Any = configs.get("key")
78
+ value = configs.get("defaultValue", _MISSING)
79
+ if truthy(key) and value is not _MISSING and key not in defaults:
80
+ defaults[key] = value
81
+ return defaults
82
+
83
+
84
+ _MISSING = object()
85
+
86
+ # validator -> JSON Schema keyword, for those that take a number
87
+ _NUMERIC = {
88
+ "minLength": "minLength",
89
+ "maxLength": "maxLength",
90
+ "min": "minimum",
91
+ "max": "maximum",
92
+ "minItems": "minItems",
93
+ "maxItems": "maxItems",
94
+ }
95
+
96
+
97
+ def build_validation_schema(spec: Any, locale: str | None = None) -> dict[str, Any] | None:
98
+ """The Ajv schema of the spec's top level, exactly as `buildValidationSchema` builds it.
99
+
100
+ It holds `nullable` and ajv-errors `errorMessage` keywords; collections are a single `array` property,
101
+ their rows being validated one by one by `validate_form_data`.
102
+ """
103
+ spec = as_spec(spec)
104
+ if not spec:
105
+ return None
106
+
107
+ properties: dict[str, Any] = {}
108
+ required: list[str] = []
109
+ required_messages: dict[str, str] = {}
110
+
111
+ def message_of(raw: Any) -> str | None:
112
+ resolved = resolve_localized_text(raw, locale)
113
+ return resolved if isinstance(resolved, str) else None
114
+
115
+ def message_or_default(raw: Any, validator: str, value: Any = None) -> str:
116
+ message = message_of(raw)
117
+ return default_validation_message(validator, locale, value) if message is None else message
118
+
119
+ for brick in iterate_schema_bricks(spec):
120
+ configs = configs_of(brick)
121
+ key: Any = configs.get("key")
122
+ data_type = (
123
+ "array" if configs.get("multiple") is True and brick.get("dataType") == "object" else brick.get("dataType")
124
+ )
125
+ if not truthy(key) or not truthy(data_type) or data_type == "void":
126
+ continue
127
+
128
+ validations = [v for v in brick.get("validations") or [] if isinstance(v, Mapping)]
129
+ is_required = next((v for v in validations if v.get("validator") == "required"), None)
130
+
131
+ prop: dict[str, Any] = {"type": data_type, "nullable": is_required is None}
132
+ messages: dict[str, str] = {"type": default_validation_message("type", locale)}
133
+
134
+ for validation in validations:
135
+ validator, value = validation.get("validator"), validation.get("value")
136
+ message = message_or_default(validation.get("message"), str(validator), value)
137
+ if validator in _NUMERIC and value is not None:
138
+ keyword = _NUMERIC[validator]
139
+ prop[keyword] = to_number(value)
140
+ messages[keyword] = message
141
+ elif validator == "pattern" and isinstance(value, str) and value:
142
+ prop["pattern"] = value
143
+ messages["pattern"] = message
144
+ elif validator == "email":
145
+ prop["format"] = "email"
146
+ messages["format"] = message
147
+ elif validator == "url":
148
+ prop["format"] = "uri"
149
+ messages["format"] = message
150
+
151
+ # Identity bricks: the rule comes from the brick, not from a validation to tick.
152
+ brick_id = brick.get("id")
153
+ if brick_id == "iban":
154
+ prop["format"] = "identity-iban"
155
+ messages["format"] = default_validation_message("iban", locale)
156
+ id_format = configs.get("idFormat")
157
+ if brick_id in ("national-id", "tax-id") and isinstance(id_format, str) and id_format:
158
+ prop["format"] = f"identity-{id_format}"
159
+ messages["format"] = default_validation_message("identity", locale)
160
+ if brick_id == "date-range":
161
+ prop["dateRange"] = True
162
+ messages["dateRange"] = default_validation_message("dateRange", locale)
163
+ if brick_id == "vehicle-plate":
164
+ plate = configs.get("plateFormat")
165
+ prop["format"] = f"plate-{plate if isinstance(plate, str) and plate else 'generic'}"
166
+ messages["format"] = default_validation_message("plate", locale)
167
+ if brick_id == "company-registry":
168
+ registry = configs.get("registryFormat")
169
+ prop["format"] = f"registry-{registry if isinstance(registry, str) and registry else 'generic'}"
170
+ messages["format"] = default_validation_message("registry", locale)
171
+ if brick_id == "mrz":
172
+ prop["mrzValid"] = True
173
+ messages["mrzValid"] = default_validation_message("mrz", locale)
174
+
175
+ prop["errorMessage"] = messages
176
+ properties[key] = prop
177
+
178
+ if is_required is not None:
179
+ required.append(key)
180
+ required_messages[key] = message_or_default(is_required.get("message"), "required")
181
+
182
+ schema: dict[str, Any] = {"type": "object", "properties": properties, "required": required}
183
+ if required_messages:
184
+ schema["errorMessage"] = {"required": required_messages}
185
+ schema["additionalProperties"] = False
186
+ return schema
formkrafter/testing.py ADDED
@@ -0,0 +1,137 @@
1
+ """Test helpers for backends: check that your specs compile and validate the same in Python and in the browser.
2
+
3
+ `assert_matches_core` runs the real core through Node, from your web project where
4
+ `@streamline-pulse/formkrafter-core` is installed, and compares it with this package.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import math
11
+ import shutil
12
+ import subprocess
13
+ from collections.abc import Iterable, Sequence
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+ from formkrafter.lint import lint_spec
18
+ from formkrafter.spec import as_spec, build_validation_schema
19
+ from formkrafter.validate import validate_form_data
20
+
21
+ _COMPILE_FAILURE = "the validation schema failed to compile, so no rule was enforced: "
22
+
23
+ _SCRIPT = """
24
+ import { buildValidationSchema, lintSpec, validateFormData } from "@streamline-pulse/formkrafter-core";
25
+ let input = "";
26
+ for await (const chunk of process.stdin) input += chunk;
27
+ const { spec, samples, locales } = JSON.parse(input);
28
+ const out = {
29
+ lint: lintSpec(spec),
30
+ locales: locales.map((locale) => ({
31
+ locale,
32
+ schema: buildValidationSchema(spec, locale ?? undefined),
33
+ results: samples.map((sample) => validateFormData(spec, sample, locale ?? undefined)),
34
+ })),
35
+ };
36
+ process.stdout.write(JSON.stringify(out));
37
+ """
38
+
39
+
40
+ def export_contract(spec: Any, locales: Iterable[str] = ("fr", "en")) -> dict[str, Any]:
41
+ """The spec with the schema the server compiles per locale, for a web test that checks the browser agrees:
42
+ `expect(buildValidationSchema(contract.spec, locale)).toEqual(contract.schemas[locale])`.
43
+ """
44
+ plain = as_spec(spec)
45
+ return {
46
+ "spec": plain,
47
+ "schemas": {locale: as_json(build_validation_schema(plain, locale)) for locale in locales},
48
+ }
49
+
50
+
51
+ def core_results(
52
+ spec: Any,
53
+ samples: Sequence[Any] = (),
54
+ locales: Sequence[str | None] = ("fr",),
55
+ *,
56
+ node_project: str | Path,
57
+ node: str = "node",
58
+ ) -> dict[str, Any]:
59
+ """What the core makes of the spec: lint issues, then per locale the schema and each sample's verdict."""
60
+ executable = shutil.which(node)
61
+ if executable is None:
62
+ raise RuntimeError(f"{node!r} not found: the core runs in Node")
63
+ payload = json.dumps({"spec": as_spec(spec), "samples": list(samples), "locales": list(locales)})
64
+ run = subprocess.run(
65
+ [executable, "--input-type=module", "-e", _SCRIPT],
66
+ input=payload,
67
+ capture_output=True,
68
+ text=True,
69
+ cwd=node_project,
70
+ check=False,
71
+ )
72
+ if run.returncode != 0:
73
+ raise RuntimeError(f"the core failed in {node_project}: {run.stderr.strip()}")
74
+ result: dict[str, Any] = json.loads(run.stdout)
75
+ return result
76
+
77
+
78
+ def compare_with_core(
79
+ spec: Any,
80
+ samples: Sequence[Any] = (),
81
+ locales: Sequence[str | None] = ("fr",),
82
+ *,
83
+ node_project: str | Path,
84
+ node: str = "node",
85
+ ) -> list[str]:
86
+ """The differences between the core and this package on the spec and samples; empty when they agree."""
87
+ core = core_results(spec, samples, locales, node_project=node_project, node=node)
88
+ differences: list[str] = []
89
+
90
+ lint = [issue.to_dict() for issue in lint_spec(spec)]
91
+ if lint != core["lint"]:
92
+ differences.append(f"lint: core {core['lint']}, python {lint}")
93
+
94
+ for expected in core["locales"]:
95
+ locale = expected["locale"]
96
+ schema = as_json(build_validation_schema(spec, locale))
97
+ if schema != expected["schema"]:
98
+ differences.append(f"schema [{locale}]: core {json.dumps(expected['schema'])}, python {json.dumps(schema)}")
99
+ for sample, verdict in zip(samples, expected["results"], strict=True):
100
+ result = validate_form_data(spec, sample, locale).to_dict()
101
+ if without_compile_reason(result) != without_compile_reason(verdict):
102
+ differences.append(f"verdict [{locale}] on {json.dumps(sample)}: core {verdict}, python {result}")
103
+ return differences
104
+
105
+
106
+ def assert_matches_core(
107
+ spec: Any,
108
+ samples: Sequence[Any] = (),
109
+ locales: Sequence[str | None] = ("fr",),
110
+ *,
111
+ node_project: str | Path,
112
+ node: str = "node",
113
+ ) -> None:
114
+ """Fail with every difference when the core and this package disagree on the spec or a sample."""
115
+ differences = compare_with_core(spec, samples, locales, node_project=node_project, node=node)
116
+ if differences:
117
+ raise AssertionError("FormKrafter core and Python disagree:\n- " + "\n- ".join(differences))
118
+
119
+
120
+ def as_json(value: Any) -> Any:
121
+ """What `JSON.stringify` keeps of a value: NaN and infinities become null."""
122
+ if isinstance(value, float) and not math.isfinite(value):
123
+ return None
124
+ if isinstance(value, dict):
125
+ return {k: as_json(v) for k, v in value.items()}
126
+ if isinstance(value, list):
127
+ return [as_json(v) for v in value]
128
+ return value
129
+
130
+
131
+ def without_compile_reason(result: dict[str, Any]) -> dict[str, Any]:
132
+ """Ajv and Python word a compile failure differently: only the fact that it failed must match."""
133
+ warnings = result.get("warnings")
134
+ if not warnings:
135
+ return result
136
+ trimmed = [w[: len(_COMPILE_FAILURE)] if w.startswith(_COMPILE_FAILURE) else w for w in warnings]
137
+ return {**result, "warnings": trimmed}
@@ -0,0 +1,285 @@
1
+ """Form data validation — `validators/validator.ts` in the core, with Ajv replaced by the handful of keywords
2
+ `build_validation_schema` emits, evaluated the way Ajv and ajv-errors report them.
3
+
4
+ Same spec, same data: same error keys (`items[0].hs_code`), same messages, same warnings as the browser.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import math
10
+ from collections.abc import Callable, Iterator, Mapping
11
+ from dataclasses import dataclass, field
12
+ from typing import Any
13
+
14
+ from formkrafter._js import FORMATS, compile_pattern, to_number
15
+ from formkrafter.lint import validation_warnings
16
+ from formkrafter.spec import (
17
+ BrickSpec,
18
+ as_spec,
19
+ build_validation_schema,
20
+ configs_of,
21
+ iterate_bricks,
22
+ iterate_schema_bricks,
23
+ )
24
+
25
+
26
+ class SpecNotSupported(ValueError):
27
+ """The spec relies on something the Python port does not check: refused rather than half validated."""
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class ErrorDetail:
32
+ """One error with its validator, so an API can return a stable code and let the client word it."""
33
+
34
+ validator: str
35
+ message: str
36
+ value: Any = None
37
+
38
+ def to_dict(self) -> dict[str, Any]:
39
+ return {"validator": self.validator, "value": self.value, "message": self.message}
40
+
41
+
42
+ @dataclass(frozen=True)
43
+ class ValidationResult:
44
+ valid: bool
45
+ errors: dict[str, str]
46
+ details: dict[str, ErrorDetail] = field(default_factory=dict)
47
+ warnings: list[str] = field(default_factory=list)
48
+
49
+ def to_dict(self) -> dict[str, Any]:
50
+ """The result as the core's `validateFormData` returns it."""
51
+ out: dict[str, Any] = {"valid": self.valid, "errors": dict(self.errors)}
52
+ if self.warnings:
53
+ out["warnings"] = list(self.warnings)
54
+ return out
55
+
56
+
57
+ # JSON Schema keyword -> FormKrafter validator, for `ErrorDetail.validator`
58
+ _VALIDATOR_OF = {
59
+ "type": "type",
60
+ "minLength": "minLength",
61
+ "maxLength": "maxLength",
62
+ "minimum": "min",
63
+ "maximum": "max",
64
+ "pattern": "pattern",
65
+ "minItems": "minItems",
66
+ "maxItems": "maxItems",
67
+ "dateRange": "dateRange",
68
+ }
69
+ _FORMAT_VALIDATOR = {"email": "email", "uri": "url"}
70
+ _COUNTS = ("minLength", "maxLength", "minItems", "maxItems")
71
+
72
+
73
+ def _is_number(value: Any) -> bool:
74
+ return isinstance(value, int | float) and not isinstance(value, bool)
75
+
76
+
77
+ _TYPE_CHECKS: dict[str, Callable[[Any], bool]] = {
78
+ "string": lambda v: isinstance(v, str),
79
+ "number": _is_number,
80
+ "integer": lambda v: _is_number(v) and math.isfinite(v) and float(v).is_integer(),
81
+ "boolean": lambda v: isinstance(v, bool),
82
+ "object": lambda v: isinstance(v, Mapping),
83
+ "array": lambda v: isinstance(v, list),
84
+ "null": lambda v: v is None,
85
+ }
86
+
87
+
88
+ def _js_le(a: Any, b: Any) -> bool:
89
+ if isinstance(a, str) and isinstance(b, str):
90
+ return a.encode("utf-16-be") <= b.encode("utf-16-be")
91
+ try:
92
+ return to_number(a) <= to_number(b)
93
+ except TypeError:
94
+ return False
95
+
96
+
97
+ def _failing_keywords(prop: Mapping[str, Any], value: Any, patterns: Mapping[str, Any]) -> Iterator[str]:
98
+ """The keywords of a property schema that the value fails, each applied to the types Ajv applies it to."""
99
+ types = prop.get("type")
100
+ allowed = types if isinstance(types, list) else [types]
101
+ if not (prop.get("nullable") and value is None) and not any(
102
+ _TYPE_CHECKS.get(str(t), lambda _: False)(value) for t in allowed
103
+ ):
104
+ yield "type"
105
+ if isinstance(value, str):
106
+ if "minLength" in prop and len(value) < prop["minLength"]:
107
+ yield "minLength"
108
+ if "maxLength" in prop and len(value) > prop["maxLength"]:
109
+ yield "maxLength"
110
+ if "pattern" in prop and not patterns[prop["pattern"]].search(value):
111
+ yield "pattern"
112
+ if "format" in prop and not FORMATS[prop["format"]](value):
113
+ yield "format"
114
+ if _is_number(value):
115
+ if "minimum" in prop and value < prop["minimum"]:
116
+ yield "minimum"
117
+ if "maximum" in prop and value > prop["maximum"]:
118
+ yield "maximum"
119
+ if isinstance(value, list):
120
+ if "minItems" in prop and len(value) < prop["minItems"]:
121
+ yield "minItems"
122
+ if "maxItems" in prop and len(value) > prop["maxItems"]:
123
+ yield "maxItems"
124
+ if prop.get("dateRange") and isinstance(value, Mapping):
125
+ start, end = value.get("from"), value.get("to")
126
+ if start and end and not _js_le(start, end):
127
+ yield "dateRange"
128
+
129
+
130
+ def _compile(schema: Mapping[str, Any]) -> dict[str, Any]:
131
+ """The checks Ajv runs when it compiles the schema (meta-schema, regular expressions); raises on failure."""
132
+ patterns: dict[str, Any] = {}
133
+ for key, prop in schema["properties"].items():
134
+ for keyword in _COUNTS:
135
+ if keyword in prop:
136
+ n = prop[keyword]
137
+ if not _is_number(n) or not math.isfinite(n) or n < 0 or not float(n).is_integer():
138
+ raise ValueError(f"schema is invalid: data/properties/{key}/{keyword} must be integer >= 0")
139
+ for keyword in ("minimum", "maximum"):
140
+ if keyword in prop and (not _is_number(prop[keyword]) or not math.isfinite(prop[keyword])):
141
+ raise ValueError(f"schema is invalid: data/properties/{key}/{keyword} must be number")
142
+ if "pattern" in prop and prop["pattern"] not in patterns:
143
+ try:
144
+ patterns[prop["pattern"]] = compile_pattern(prop["pattern"])
145
+ except Exception as error: # re.error, or regex.error with the optional module
146
+ raise ValueError(f"Invalid regular expression: /{prop['pattern']}/: {error}") from error
147
+ return patterns
148
+
149
+
150
+ def _detail(keyword: str, prop: Mapping[str, Any], message: str) -> ErrorDetail:
151
+ if keyword == "format":
152
+ return ErrorDetail(_FORMAT_VALIDATOR.get(prop["format"], "format"), message)
153
+ if keyword == "type":
154
+ return ErrorDetail("type", message, prop.get("type"))
155
+ if keyword == "dateRange":
156
+ return ErrorDetail(_VALIDATOR_OF[keyword], message)
157
+ return ErrorDetail(_VALIDATOR_OF[keyword], message, prop.get(keyword))
158
+
159
+
160
+ def _strip_empty(data: Any) -> dict[str, Any]:
161
+ if not isinstance(data, Mapping):
162
+ return {}
163
+ return {k: v for k, v in data.items() if v != "" and v is not None}
164
+
165
+
166
+ def _row_spec(collection: BrickSpec) -> BrickSpec:
167
+ return {
168
+ "type": "panel",
169
+ "id": "collection-row",
170
+ "name": "Row",
171
+ "configs": {"key": f"{configs_of(collection).get('key') or 'collection'}_row"},
172
+ "children": collection.get("children") or [],
173
+ }
174
+
175
+
176
+ def _levels(spec: BrickSpec) -> Iterator[BrickSpec]:
177
+ """The spec and the row template of every collection under it, at any depth."""
178
+ yield spec
179
+ for brick in iterate_schema_bricks(spec):
180
+ if brick.get("type") == "collection":
181
+ yield from _levels(_row_spec(brick))
182
+
183
+
184
+ def _has_key(brick: BrickSpec) -> bool:
185
+ return any(configs_of(b).get("key") for b, _ in iterate_bricks(brick))
186
+
187
+
188
+ def assert_supported(spec: Any) -> None:
189
+ """Raise `SpecNotSupported` when validating the spec needs what the port does not run.
190
+
191
+ Refused: JavaScript custom validators, rules that hide data-carrying bricks (their errors depend on the
192
+ rules), and the bricks whose check is not ported yet (identity numbers, plates, registries, MRZ).
193
+ Rules that only disable, prefill or require do not change validation and are accepted.
194
+ """
195
+ spec = as_spec(spec)
196
+ if not spec:
197
+ return
198
+ for brick, path in iterate_bricks(spec):
199
+ for validation in brick.get("validations") or []:
200
+ if (
201
+ isinstance(validation, Mapping)
202
+ and validation.get("validator") == "custom"
203
+ and validation.get("customValidator")
204
+ ):
205
+ raise SpecNotSupported(
206
+ f"{path} ({brick.get('name')}): JavaScript custom validators do not run server-side"
207
+ )
208
+ hides = any(
209
+ ((effect or {}).get("property") or {}).get("target") == "hidden"
210
+ for rule in brick.get("rules") or []
211
+ for effect in (rule or {}).get("effects") or []
212
+ )
213
+ if hides and _has_key(brick):
214
+ raise SpecNotSupported(
215
+ f"{path} ({brick.get('name')}): rules that hide fields are not evaluated server-side yet"
216
+ )
217
+ for level in _levels(spec):
218
+ schema = build_validation_schema(level) or {"properties": {}}
219
+ for key, prop in schema["properties"].items():
220
+ if "format" in prop and prop["format"] not in FORMATS:
221
+ raise SpecNotSupported(f'"{key}": the {prop["format"]} check is not ported to Python yet')
222
+ if "mrzValid" in prop:
223
+ raise SpecNotSupported(f'"{key}": the MRZ check is not ported to Python yet')
224
+
225
+
226
+ def _validate_level(
227
+ spec: BrickSpec, data: dict[str, Any], locale: str | None
228
+ ) -> tuple[dict[str, ErrorDetail], str | None]:
229
+ schema = build_validation_schema(spec, locale)
230
+ if not schema:
231
+ return {}, None
232
+ try:
233
+ patterns = _compile(schema)
234
+ except ValueError as error:
235
+ return {}, f"the validation schema failed to compile, so no rule was enforced: {error}"
236
+
237
+ details: dict[str, ErrorDetail] = {}
238
+ for key, prop in schema["properties"].items():
239
+ if key not in data:
240
+ continue
241
+ failing = set(_failing_keywords(prop, data[key], patterns))
242
+ # ajv-errors reports in the order of `errorMessage`; an empty message is dropped like the core does
243
+ for keyword, message in prop["errorMessage"].items():
244
+ if keyword in failing and message:
245
+ details[key] = _detail(keyword, prop, message)
246
+ break
247
+ required_messages = schema.get("errorMessage", {}).get("required", {})
248
+ for key in schema["required"]:
249
+ message = required_messages.get(key)
250
+ if key not in data and key not in details and message:
251
+ details[key] = ErrorDetail("required", message)
252
+ return details, None
253
+
254
+
255
+ def validate_form_data(spec: Any, data: Any, locale: str | None = None) -> ValidationResult:
256
+ """Validate submitted data against a spec, as `validateFormData` does in the browser.
257
+
258
+ Empty strings and nulls count as missing; collections are validated row by row, their errors keyed
259
+ `items[0].field`. Raises `SpecNotSupported` when the spec needs what the port does not run.
260
+ """
261
+ spec = as_spec(spec)
262
+ assert_supported(spec)
263
+ return _validate(spec, data, locale)
264
+
265
+
266
+ def _validate(spec: BrickSpec | None, data: Any, locale: str | None) -> ValidationResult:
267
+ if not spec:
268
+ return ValidationResult(True, {})
269
+ present = _strip_empty(data)
270
+ details, compile_failure = _validate_level(spec, present, locale)
271
+
272
+ for brick in iterate_schema_bricks(spec):
273
+ key: Any = configs_of(brick).get("key")
274
+ if brick.get("type") != "collection" or not key or not isinstance(present.get(key), list):
275
+ continue
276
+ row_spec = _row_spec(brick)
277
+ for index, row in enumerate(present[key]):
278
+ for field_key, detail in _validate(row_spec, row, locale).details.items():
279
+ details.setdefault(f"{key}[{index}].{field_key}", detail)
280
+
281
+ warnings = validation_warnings(spec)
282
+ if compile_failure:
283
+ warnings.append(compile_failure)
284
+ errors = {key: detail.message for key, detail in details.items()}
285
+ return ValidationResult(not errors, errors, details, warnings)
@@ -0,0 +1,116 @@
1
+ Metadata-Version: 2.5
2
+ Name: formkrafter
3
+ Version: 0.1.0
4
+ Summary: FormKrafter for Python backends: validate form submissions exactly like @streamline-pulse/formkrafter-core does in the browser
5
+ Project-URL: Homepage, https://github.com/streamline-pulse/formkrafter/tree/main/python#readme
6
+ Project-URL: Repository, https://github.com/streamline-pulse/formkrafter
7
+ Project-URL: Issues, https://github.com/streamline-pulse/formkrafter/issues
8
+ Author: Streamline Pulse
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: form-builder,formkrafter,forms,json-schema,validation
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: Typing :: Typed
16
+ Requires-Python: >=3.12
17
+ Provides-Extra: pydantic
18
+ Requires-Dist: pydantic>=2.6; extra == 'pydantic'
19
+ Provides-Extra: regex
20
+ Requires-Dist: regex>=2024.4; extra == 'regex'
21
+ Description-Content-Type: text/markdown
22
+
23
+ # formkrafter (Python)
24
+
25
+ FormKrafter for Python backends. The server validates a submission with the same spec the browser renders, and
26
+ reaches the same verdict: same error keys (`items[0].hs_code`), same messages, same warnings as
27
+ [`@streamline-pulse/formkrafter-core`](../packages/core).
28
+
29
+ ```bash
30
+ pip install formkrafter # no dependency
31
+ pip install "formkrafter[pydantic]" # Pydantic models for specs built in code
32
+ ```
33
+
34
+ ```python
35
+ from formkrafter import validate_form_data
36
+
37
+ result = validate_form_data(spec, payload, locale="fr")
38
+ if not result.valid:
39
+ # {"items[0].declared_value": "Minimum 0", "origin": "Ce champ est obligatoire"}
40
+ return 422, result.errors
41
+ ```
42
+
43
+ ## What it does
44
+
45
+ | Function | Core equivalent |
46
+ |---|---|
47
+ | `build_validation_schema(spec, locale)` | `buildValidationSchema`: the same Ajv schema, key for key |
48
+ | `validate_form_data(spec, data, locale)` | `validateFormData`: empty strings and nulls count as missing, collections are validated row by row |
49
+ | `lint_spec(spec)` | `lintSpec`: keyless inputs, validations without a dataType, duplicate keys, empty collections |
50
+ | `register_validation_messages(locale, messages)` | `registerValidationMessages` |
51
+ | `default_form_data`, `iterate_bricks`, `iterate_schema_bricks`, `resolve_localized_text` | same names in camelCase |
52
+
53
+ `validate_form_data` returns a `ValidationResult`:
54
+
55
+ - `valid`, `errors` (key → message) and `warnings`, as in the browser; `to_dict()` gives the core's shape;
56
+ - `details` (key → `ErrorDetail(validator, message, value)`), so an API can return a stable code and let the
57
+ client word it: `{"items[0].declared_value": {"validator": "min", "value": 0, "message": "Minimum 0"}}`.
58
+
59
+ Every function takes a plain dict or a `formkrafter.models.BrickSpec`.
60
+
61
+ ### Supported
62
+
63
+ - **Validations:** `required`, `min`/`max`, `minLength`/`maxLength`, `pattern`, `minItems`/`maxItems`, `email`, `url`.
64
+ - **Bricks:** panels, inputs, selects (multiple included), collections (data grids, nested at any depth), outputs.
65
+ On top of those, `date-range` must not end before it starts.
66
+ - **Rules:** rules that only disable, prefill or require a field are accepted. They do not change the verdict,
67
+ in the browser either.
68
+
69
+ The details that usually make a Python port drift are reproduced:
70
+
71
+ - Ajv's `email` and `uri` formats, copied verbatim;
72
+ - the browser's `RegExp`: `$` never matches before a trailing newline, and `\d` is ASCII;
73
+ - `String(1e-7)` is `1e-7`;
74
+ - the core compares lengths in code points;
75
+ - a schema Ajv refuses to compile enforces no rule (with a warning).
76
+
77
+ ### Refused
78
+
79
+ `validate_form_data` raises `SpecNotSupported` rather than half-validating a spec that needs:
80
+
81
+ - **JavaScript custom validators** (`validator: "custom"`). They run in the browser's sandbox and are not executed
82
+ server-side: move the check to the server, or to a declarative validation.
83
+ - **Rules that hide data-carrying fields.** A hidden field's errors are dropped in the browser. json-logic
84
+ evaluation is planned.
85
+ - **The checks not ported yet:** identity numbers (`national-id`, `tax-id`, `iban`), `vehicle-plate`,
86
+ `company-registry`, `mrz`.
87
+
88
+ `build_validation_schema` and `lint_spec` work on every spec. `assert_supported(spec)` checks up front, for
89
+ instance in the tests that cover the specs a backend serves.
90
+
91
+ ## Parity with the core
92
+
93
+ `tests/parity/cases.json` holds specs and data samples. The core compiles and validates them:
94
+
95
+ ```bash
96
+ bun scripts/python-parity.ts # from the repository root: rewrites tests/parity/expected.json
97
+ uv run pytest # the port must reach the same schemas, lint issues and verdicts
98
+ ```
99
+
100
+ CI regenerates the fixtures and fails when they are stale, so a change in the core shows up in the Python tests.
101
+ `formkrafter.CORE_VERSION` names the core release a version follows.
102
+
103
+ ### In your own project
104
+
105
+ `formkrafter.testing` checks your specs against the real core, through Node and your web app's installed
106
+ `@streamline-pulse/formkrafter-core`:
107
+
108
+ ```python
109
+ from formkrafter.testing import assert_matches_core
110
+
111
+ def test_served_forms_match_the_browser():
112
+ assert_matches_core(SPEC, samples=[VALID, {}, {"items": []}], locales=["fr", "en"], node_project="../web")
113
+ ```
114
+
115
+ `export_contract(spec, locales)` returns the spec with its schema per locale. Write it where your web tests read
116
+ it to assert that `buildValidationSchema(spec, locale)` gives the same.
@@ -0,0 +1,13 @@
1
+ formkrafter/__init__.py,sha256=a9fRiu8sAbYNmHMVamABFVZWTskNskejy3jMJ_B8TU4,1257
2
+ formkrafter/_js.py,sha256=ctmILiO_NUzEXsCz1eXvAXpBh-oQG8R7KLYZxoTUBmU,6537
3
+ formkrafter/lint.py,sha256=FzDIPtmW8WXzFk0iat_9Yuzl0VUIHMsWW06Te008HWI,3533
4
+ formkrafter/messages.py,sha256=RPubrWH57EM06EoOaddLqQVcD0m1D4pOkRvms_rDEHg,2918
5
+ formkrafter/models.py,sha256=Zmc1mADcSwZ7OfWOL86Lxny2J1j8jiDzhWBdVxZqA2g,1968
6
+ formkrafter/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ formkrafter/spec.py,sha256=12lQAe3qUQ68RFkAivAqbiLjYxSBAg7SP-YGLOzIKbE,7584
8
+ formkrafter/testing.py,sha256=SM63ok7Q7DCfDXGvfErmIEdoxtTLGzZs35UQIo4QRLE,5215
9
+ formkrafter/validate.py,sha256=oWHHadkzV_JlhMasbODLRKaj_Wr11_K0HakpAzRZEjg,11463
10
+ formkrafter-0.1.0.dist-info/METADATA,sha256=XcnwrUyqMYCgfJY5GI1TbNxQ9pyIpf9ZvZBk_elkYNk,5346
11
+ formkrafter-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
12
+ formkrafter-0.1.0.dist-info/licenses/LICENSE,sha256=GJdwBUdPLgCY17Q1a4BeEEAD2v9hCHSS7IlZRRv0qSs,1073
13
+ formkrafter-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Streamline Pulse
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.