mateu-ui 3.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.
Files changed (188) hide show
  1. mateu_ui/__init__.py +15 -0
  2. mateu_ui/_version.py +8 -0
  3. mateu_ui/bundle/__init__.py +607 -0
  4. mateu_ui/bundle/__main__.py +158 -0
  5. mateu_ui/bundle/inliner.py +153 -0
  6. mateu_ui/bundle/static_safety.py +316 -0
  7. mateu_ui/bundle/writer.py +178 -0
  8. mateu_ui/core/__init__.py +29 -0
  9. mateu_ui/core/action_guard.py +318 -0
  10. mateu_ui/core/action_registry.py +319 -0
  11. mateu_ui/core/agent_push.py +1066 -0
  12. mateu_ui/core/authoring/__init__.py +24 -0
  13. mateu_ui/core/authoring/resources/authoring-guide.md +88 -0
  14. mateu_ui/core/authoring/resources/specs-schema.json +9994 -0
  15. mateu_ui/core/authoring/resources/uidl-catalog.json +2794 -0
  16. mateu_ui/core/authoring/resources/uidl-schema.json +9517 -0
  17. mateu_ui/core/authoring/resources.py +102 -0
  18. mateu_ui/core/authoring/schemas.py +79 -0
  19. mateu_ui/core/authoring/service.py +57 -0
  20. mateu_ui/core/authoring/spec_writer.py +164 -0
  21. mateu_ui/core/authoring/validator.py +628 -0
  22. mateu_ui/core/authoring_gate.py +44 -0
  23. mateu_ui/core/capabilities.py +49 -0
  24. mateu_ui/core/component_registry.py +369 -0
  25. mateu_ui/core/dev_specs.py +223 -0
  26. mateu_ui/core/documents.py +209 -0
  27. mateu_ui/core/environments.py +176 -0
  28. mateu_ui/core/error_boundary.py +111 -0
  29. mateu_ui/core/errors.py +40 -0
  30. mateu_ui/core/eta_estimator.py +76 -0
  31. mateu_ui/core/export.py +68 -0
  32. mateu_ui/core/field_type_registry.py +255 -0
  33. mateu_ui/core/filter_criteria.py +98 -0
  34. mateu_ui/core/form_columns_inference.py +100 -0
  35. mateu_ui/core/hidden_members.py +26 -0
  36. mateu_ui/core/idempotency_keys.py +435 -0
  37. mateu_ui/core/identity.py +104 -0
  38. mateu_ui/core/importwizard.py +390 -0
  39. mateu_ui/core/inbox.py +69 -0
  40. mateu_ui/core/inference_switches.py +36 -0
  41. mateu_ui/core/input_purpose.py +11 -0
  42. mateu_ui/core/islands.py +93 -0
  43. mateu_ui/core/labels_aside_inference.py +80 -0
  44. mateu_ui/core/layout_delta.py +225 -0
  45. mateu_ui/core/layout_inference.py +77 -0
  46. mateu_ui/core/mapper/__init__.py +441 -0
  47. mateu_ui/core/mapper/_base.py +16 -0
  48. mateu_ui/core/mapper/_common.py +488 -0
  49. mateu_ui/core/mapper/app.py +706 -0
  50. mateu_ui/core/mapper/archetypes.py +237 -0
  51. mateu_ui/core/mapper/components.py +1695 -0
  52. mateu_ui/core/mapper/composed_page_header.py +82 -0
  53. mateu_ui/core/mapper/crud.py +1041 -0
  54. mateu_ui/core/mapper/crud_modes.py +106 -0
  55. mateu_ui/core/mapper/decorations.py +304 -0
  56. mateu_ui/core/mapper/fields.py +1156 -0
  57. mateu_ui/core/mapper/layout.py +863 -0
  58. mateu_ui/core/mapper/more_components.py +295 -0
  59. mateu_ui/core/mapper/view.py +448 -0
  60. mateu_ui/core/mapper/wizard.py +416 -0
  61. mateu_ui/core/mcp.py +768 -0
  62. mateu_ui/core/menu_route_conformance.py +55 -0
  63. mateu_ui/core/microfrontends.py +1226 -0
  64. mateu_ui/core/mobile_manifest.py +119 -0
  65. mateu_ui/core/naming.py +76 -0
  66. mateu_ui/core/nested_forms.py +200 -0
  67. mateu_ui/core/observability.py +430 -0
  68. mateu_ui/core/page_breadcrumbs.py +100 -0
  69. mateu_ui/core/page_inference.py +63 -0
  70. mateu_ui/core/page_templates.py +456 -0
  71. mateu_ui/core/page_type_inference.py +73 -0
  72. mateu_ui/core/partial_registry.py +239 -0
  73. mateu_ui/core/presence.py +131 -0
  74. mateu_ui/core/progress.py +566 -0
  75. mateu_ui/core/project_renderer.py +113 -0
  76. mateu_ui/core/proxy_expression.py +662 -0
  77. mateu_ui/core/public_base.py +60 -0
  78. mateu_ui/core/push.py +168 -0
  79. mateu_ui/core/pwa.py +443 -0
  80. mateu_ui/core/pwa_files/icon-192.png +0 -0
  81. mateu_ui/core/pwa_files/icon-512.png +0 -0
  82. mateu_ui/core/pwa_files/icon-maskable-512.png +0 -0
  83. mateu_ui/core/pwa_files/register.js +46 -0
  84. mateu_ui/core/pwa_files/sw-off.js +18 -0
  85. mateu_ui/core/pwa_files/sw.js +213 -0
  86. mateu_ui/core/reflection.py +132 -0
  87. mateu_ui/core/registry.py +387 -0
  88. mateu_ui/core/request_context.py +91 -0
  89. mateu_ui/core/rest_source_registry.py +314 -0
  90. mateu_ui/core/route_registry.py +668 -0
  91. mateu_ui/core/routed_tabs.py +329 -0
  92. mateu_ui/core/sample_sources.py +27 -0
  93. mateu_ui/core/sign_in_providers.py +446 -0
  94. mateu_ui/core/subresources.py +229 -0
  95. mateu_ui/core/sync_handler/__init__.py +829 -0
  96. mateu_ui/core/sync_handler/_base.py +16 -0
  97. mateu_ui/core/sync_handler/_common.py +168 -0
  98. mateu_ui/core/sync_handler/actions.py +309 -0
  99. mateu_ui/core/sync_handler/app.py +535 -0
  100. mateu_ui/core/sync_handler/contract.py +76 -0
  101. mateu_ui/core/sync_handler/crud.py +932 -0
  102. mateu_ui/core/sync_handler/dispatch.py +771 -0
  103. mateu_ui/core/sync_handler/editable_view.py +293 -0
  104. mateu_ui/core/sync_handler/grid_field.py +307 -0
  105. mateu_ui/core/sync_handler/helpers.py +419 -0
  106. mateu_ui/core/sync_handler/listing.py +372 -0
  107. mateu_ui/core/sync_handler/proxy.py +387 -0
  108. mateu_ui/core/sync_handler/render.py +92 -0
  109. mateu_ui/core/sync_handler/search.py +718 -0
  110. mateu_ui/core/sync_handler/undo_delete.py +33 -0
  111. mateu_ui/core/sync_handler/wizard.py +206 -0
  112. mateu_ui/core/titles.py +100 -0
  113. mateu_ui/core/translations.py +264 -0
  114. mateu_ui/core/ui_page.py +562 -0
  115. mateu_ui/core/untrusted.py +268 -0
  116. mateu_ui/core/uploads.py +275 -0
  117. mateu_ui/core/url_template.py +229 -0
  118. mateu_ui/core/user_profiles.py +76 -0
  119. mateu_ui/core/validation.py +289 -0
  120. mateu_ui/core/version_skew.py +207 -0
  121. mateu_ui/core/yaml_access.py +236 -0
  122. mateu_ui/core/yaml_app_shell.py +552 -0
  123. mateu_ui/core/yaml_preview.py +797 -0
  124. mateu_ui/core/yaml_spec_loader.py +708 -0
  125. mateu_ui/dtos/__init__.py +271 -0
  126. mateu_ui/dtos/app.py +254 -0
  127. mateu_ui/dtos/base.py +20 -0
  128. mateu_ui/dtos/basic.py +308 -0
  129. mateu_ui/dtos/components.py +354 -0
  130. mateu_ui/dtos/dashboard.py +217 -0
  131. mateu_ui/dtos/envelope.py +300 -0
  132. mateu_ui/dtos/fields.py +276 -0
  133. mateu_ui/dtos/front_office.py +403 -0
  134. mateu_ui/dtos/layout.py +200 -0
  135. mateu_ui/dtos/more_components.py +285 -0
  136. mateu_ui/dtos/overlays.py +117 -0
  137. mateu_ui/dtos/records.py +392 -0
  138. mateu_ui/dtos/ux.py +344 -0
  139. mateu_ui/fastapi/__init__.py +1363 -0
  140. mateu_ui/fastapi/_uploads.py +209 -0
  141. mateu_ui/py.typed +0 -0
  142. mateu_ui/testing/__init__.py +874 -0
  143. mateu_ui/uidl/__init__.py +542 -0
  144. mateu_ui/uidl/_enums.py +31 -0
  145. mateu_ui/uidl/action_catalog.py +51 -0
  146. mateu_ui/uidl/adapters.py +64 -0
  147. mateu_ui/uidl/archetype_pages.py +608 -0
  148. mateu_ui/uidl/archetypes.py +295 -0
  149. mateu_ui/uidl/audit.py +71 -0
  150. mateu_ui/uidl/business_components.py +46 -0
  151. mateu_ui/uidl/class_decorators.py +917 -0
  152. mateu_ui/uidl/components.py +2509 -0
  153. mateu_ui/uidl/constraints.py +84 -0
  154. mateu_ui/uidl/documents.py +81 -0
  155. mateu_ui/uidl/editable_views.py +123 -0
  156. mateu_ui/uidl/environments.py +35 -0
  157. mateu_ui/uidl/export.py +130 -0
  158. mateu_ui/uidl/feature_flags.py +19 -0
  159. mateu_ui/uidl/field_types.py +116 -0
  160. mateu_ui/uidl/flow.py +107 -0
  161. mateu_ui/uidl/i18n.py +29 -0
  162. mateu_ui/uidl/inbox_store.py +95 -0
  163. mateu_ui/uidl/listing.py +433 -0
  164. mateu_ui/uidl/live_header_values.py +62 -0
  165. mateu_ui/uidl/live_notifications.py +98 -0
  166. mateu_ui/uidl/markers.py +634 -0
  167. mateu_ui/uidl/messages.py +220 -0
  168. mateu_ui/uidl/method_decorators.py +397 -0
  169. mateu_ui/uidl/more_components.py +466 -0
  170. mateu_ui/uidl/page_templates.py +219 -0
  171. mateu_ui/uidl/patterns.py +217 -0
  172. mateu_ui/uidl/placement.py +124 -0
  173. mateu_ui/uidl/presence_store.py +160 -0
  174. mateu_ui/uidl/progress.py +238 -0
  175. mateu_ui/uidl/push.py +177 -0
  176. mateu_ui/uidl/remote.py +241 -0
  177. mateu_ui/uidl/request.py +30 -0
  178. mateu_ui/uidl/rest_sources.py +207 -0
  179. mateu_ui/uidl/security.py +225 -0
  180. mateu_ui/uidl/suppliers.py +398 -0
  181. mateu_ui/uidl/uploads.py +171 -0
  182. mateu_ui/uidl/user_profile.py +56 -0
  183. mateu_ui/uidl/views.py +181 -0
  184. mateu_ui-3.0.0.dist-info/METADATA +326 -0
  185. mateu_ui-3.0.0.dist-info/RECORD +188 -0
  186. mateu_ui-3.0.0.dist-info/WHEEL +4 -0
  187. mateu_ui-3.0.0.dist-info/licenses/LICENSE.txt +202 -0
  188. mateu_ui-3.0.0.dist-info/licenses/NOTICE +65 -0
mateu_ui/__init__.py ADDED
@@ -0,0 +1,15 @@
1
+ """Mateu for Python, distributed on PyPI as ``mateu-ui``.
2
+
3
+ Everything lives under this one namespace so the wheel installs a single top-level package:
4
+
5
+ - :mod:`mateu_ui.uidl` — the authoring API (``@ui``, ``@title``, ``Annotated`` field modifiers, …)
6
+ - :mod:`mateu_ui.dtos` — the wire model exchanged with the renderers
7
+ - :mod:`mateu_ui.core` — the engine (registry, reflection mapper, the sync use case)
8
+ - :mod:`mateu_ui.fastapi` — the FastAPI adapter
9
+
10
+ Importing this package is cheap: the subpackages are loaded only when imported.
11
+ """
12
+
13
+ from ._version import __version__
14
+
15
+ __all__ = ["__version__"]
mateu_ui/_version.py ADDED
@@ -0,0 +1,8 @@
1
+ """The single source of the package version.
2
+
3
+ Development builds carry ``3.0.0.dev0``. The release workflow rewrites this line from the release
4
+ tag (``v3.0-alpha.406`` → ``3.0.0a406``, see ``scripts/set_version.py``) before building, so the
5
+ PyPI package moves in lockstep with the Maven artifacts.
6
+ """
7
+
8
+ __version__ = "3.0.0"
@@ -0,0 +1,607 @@
1
+ """Build-time exporter of a Mateu app into a STATIC BUNDLE — the Python twin of Java's
2
+ ``MateuBundleExporter`` + ``BundleManifest`` (``io.mateu.core.application.export``) and of the
3
+ ``mateu-bundle:bundle`` Maven goal.
4
+
5
+ For each declared route it renders the initial load (the same ``actionId=""`` increment the server
6
+ returns) through the port's OWN :class:`~mateu_ui.core.SyncHandler`, in process — no HTTP server —
7
+ and serializes it to wire JSON in ``manifest.json``. A static host serves the bundle and the
8
+ renderer's bundle mode answers route loads from it with no backend.
9
+
10
+ Two loads per route under an app shell (#557): the FRESH load (a deep link, a reload — consumed
11
+ route ``_empty``) answers the SHELL, and the shell then asks for its content slot with its own
12
+ consumed route — the route's own screen. Both are exported (``json`` / ``contentJson``).
13
+
14
+ The manifest is the same document Java writes (same members, same order): the entries, the
15
+ AUTHORED route table, the REST source catalogue (shipped once), the action catalogue, the
16
+ translations (``${i18n.…}`` stays as written in the entries and is resolved in the browser), the
17
+ raw definitions a specs-mode bundle expands in the browser, the environment and the mock flag.
18
+
19
+ Usage: ``python -m mateu_ui.bundle my_app.views --out dist --ui mateu-vaadin.jar`` (see
20
+ :mod:`mateu_ui.bundle.__main__`), or :func:`export_all` + :func:`mateu_ui.bundle.writer.write`.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import datetime as _dt
26
+ import hashlib
27
+ import json
28
+ import logging
29
+ import os
30
+ import re
31
+ from contextlib import contextmanager
32
+ from dataclasses import dataclass, field
33
+ from pathlib import Path
34
+ from typing import Any, Iterator
35
+
36
+ import yaml
37
+
38
+ log = logging.getLogger("mateu.bundle")
39
+
40
+ #: A ``:name`` route segment (the param marker).
41
+ PARAM_SEGMENT = re.compile(r":([^/]+)")
42
+
43
+ #: Placeholder substituted for each param when rendering a template's param-independent structure.
44
+ PARAM_PLACEHOLDER = "__mateu_param__"
45
+
46
+ #: The top-level definition types the browser's expander (``libs/mateu/.../expander``) turns into
47
+ #: the wire — Java's ``MateuBundleExporter.CLIENT_EXPANDABLE_TYPES``, a deliberate mirror.
48
+ CLIENT_EXPANDABLE_TYPES = frozenset(
49
+ {
50
+ "AppShell",
51
+ "Listing",
52
+ "Crudl",
53
+ "Crud",
54
+ "Form",
55
+ "VerticalLayout",
56
+ "HorizontalLayout",
57
+ "Div",
58
+ "Card",
59
+ "CustomComponent",
60
+ }
61
+ )
62
+
63
+
64
+ @dataclass
65
+ class BundleEntry:
66
+ """One route's export result (Java's ``BundleEntry``). ``json`` is None when skipped."""
67
+
68
+ route: str
69
+ sync_path: str
70
+ json: str | None
71
+ ok: bool
72
+ skip_reason: str | None = None
73
+ route_pattern: str | None = None
74
+ param_names: list[str] | None = None
75
+ content_json: str | None = None
76
+
77
+ def to_wire(self) -> dict[str, Any]:
78
+ return {
79
+ "route": self.route,
80
+ "syncPath": self.sync_path,
81
+ "json": self.json,
82
+ "ok": self.ok,
83
+ "skipReason": self.skip_reason,
84
+ "routePattern": self.route_pattern,
85
+ "paramNames": self.param_names,
86
+ "contentJson": self.content_json,
87
+ }
88
+
89
+
90
+ @dataclass
91
+ class BundleManifest:
92
+ """The whole bundle (Java's ``BundleManifest``)."""
93
+
94
+ base_url: str
95
+ generated_at: str
96
+ static_only: bool
97
+ entries: list[BundleEntry]
98
+ routes: list[dict[str, Any]] = field(default_factory=list)
99
+ sources: list[dict[str, Any]] = field(default_factory=list)
100
+ required_capabilities: list[str] = field(default_factory=list)
101
+ definitions: dict[str, Any] = field(default_factory=dict)
102
+ actions: list[dict[str, Any]] = field(default_factory=list)
103
+ translations: dict[str, dict[str, str]] = field(default_factory=dict)
104
+ environment: str | None = None
105
+ mock_sources: bool | None = None
106
+
107
+ def to_wire(self) -> dict[str, Any]:
108
+ """The manifest as Java's Jackson writes it (members in record order)."""
109
+ return {
110
+ "baseUrl": self.base_url,
111
+ "generatedAt": self.generated_at,
112
+ "staticOnly": self.static_only,
113
+ "entries": [e.to_wire() for e in self.entries],
114
+ "routes": {"routes": self.routes},
115
+ "sources": {"sources": self.sources},
116
+ "requiredCapabilities": self.required_capabilities,
117
+ "definitions": self.definitions,
118
+ "actions": self.actions,
119
+ "translations": self.translations,
120
+ "environment": self.environment,
121
+ "mockSources": self.mock_sources,
122
+ }
123
+
124
+ def to_json(self) -> str:
125
+ return json.dumps(self.to_wire(), indent=2, ensure_ascii=False)
126
+
127
+ def structure_hash(self) -> str:
128
+ """A stable identity for what the bundle CONTAINS (Java's ``structureHash``): the entries'
129
+ wire without the per-environment source catalogue, independent of the build time."""
130
+ parts = []
131
+ for e in sorted(self.entries, key=lambda x: str(x.route)):
132
+ text = f"{e.route}\x00{'true' if e.ok else 'false'}\x00{without_catalogue(e.json)}"
133
+ if e.content_json is not None:
134
+ text += "\x00" + without_catalogue(e.content_json)
135
+ parts.append(text)
136
+ return hashlib.sha256("\x01".join(parts).encode("utf-8")).hexdigest()
137
+
138
+
139
+ def without_catalogue(text: str | None) -> str:
140
+ """Entry JSON without the REST source catalogue an app shell carries (``restSources``)."""
141
+ if text is None:
142
+ return ""
143
+ if '"restSources"' not in text:
144
+ return text
145
+ try:
146
+ tree = json.loads(text)
147
+ except ValueError:
148
+ return text
149
+
150
+ def drop(node: Any) -> None:
151
+ if isinstance(node, dict):
152
+ node.pop("restSources", None)
153
+ for v in node.values():
154
+ drop(v)
155
+ elif isinstance(node, list):
156
+ for v in node:
157
+ drop(v)
158
+
159
+ drop(tree)
160
+ return json.dumps(tree, separators=(",", ":"), ensure_ascii=False)
161
+
162
+
163
+ def to_sync_path(route: str | None) -> str:
164
+ """The ``/mateu/v3/sync/<seg>`` segment of a route — mirrors the browser: ``"/foo" -> "foo"``,
165
+ blank/root ``-> "_no_route"``."""
166
+ r = route or ""
167
+ r = r[1:] if r.startswith("/") else r
168
+ return r or "_no_route"
169
+
170
+
171
+ def is_static(route: str) -> bool:
172
+ return ":" not in (route or "")
173
+
174
+
175
+ def normalized_route(route: str | None) -> str:
176
+ return (route or "").strip("/")
177
+
178
+
179
+ def is_client_expandable(definition: Any) -> bool:
180
+ if not isinstance(definition, dict):
181
+ return False
182
+ root = definition.get("layout") if "layout" in definition else definition
183
+ return isinstance(root, dict) and root.get("type") in CLIENT_EXPANDABLE_TYPES
184
+
185
+
186
+ class _SkipError(Exception):
187
+ """A load that rendered nothing usable: the route stays backend-served, for this reason."""
188
+
189
+
190
+ @contextmanager
191
+ def _env(name: str, value: str | None) -> Iterator[None]:
192
+ previous = os.environ.get(name)
193
+ if value is not None:
194
+ os.environ[name] = value
195
+ try:
196
+ yield
197
+ finally:
198
+ if value is not None:
199
+ if previous is None:
200
+ os.environ.pop(name, None)
201
+ else:
202
+ os.environ[name] = previous
203
+
204
+
205
+ class BundleExporter:
206
+ """Renders an app's routes through ``handler`` (a :class:`~mateu_ui.core.SyncHandler`)."""
207
+
208
+ def __init__(self, handler, specs_dir: str | Path | None = None) -> None:
209
+ self.handler = handler
210
+ self.specs_dir = Path(specs_dir or os.environ.get("MATEU_SPECS_DIR") or Path("specs") / "ui")
211
+
212
+ # ------------------------------------------------------------------ discovery
213
+
214
+ def declared_routes(self) -> list[str]:
215
+ """The routes the registered classes declare (``@ui`` / ``@app(route=…)``), as written."""
216
+ out: list[str] = []
217
+ app_type = self.handler.registry.app_type
218
+ if app_type is not None and not (
219
+ app_type.__dict__.get("__mateu_app_route__") or app_type.__dict__.get("__mateu_ui__")
220
+ ):
221
+ # a route-less @app is the root: it answers "" (Java's @UI(""))
222
+ out.append("")
223
+ for cls in self.handler.registry.registered_types:
224
+ route = cls.__dict__.get("__mateu_app_route__") or cls.__dict__.get("__mateu_ui__")
225
+ if route is None:
226
+ continue
227
+ if route not in out:
228
+ out.append(route)
229
+ return out
230
+
231
+ def classes_by_route(self) -> dict[str, type]:
232
+ """Which class answers each route: the registered views, then the authored view models
233
+ (authored wins)."""
234
+ out: dict[str, type] = {}
235
+ if "" in self.declared_routes() and self.handler.registry.app_type is not None:
236
+ out[""] = self.handler.registry.app_type
237
+ for cls in self.handler.registry.registered_types:
238
+ route = cls.__dict__.get("__mateu_app_route__") or cls.__dict__.get("__mateu_ui__")
239
+ if route is not None:
240
+ out.setdefault(normalized_route(route), cls)
241
+ for entry in self.handler.routes.authored().routes:
242
+ if entry.view_model:
243
+ t = self.handler.registry.authored_type(entry.view_model)
244
+ if t is not None:
245
+ out[normalized_route(entry.route)] = t
246
+ return out
247
+
248
+ # ------------------------------------------------------------------ export
249
+
250
+ def export_all(
251
+ self,
252
+ base_url: str = "",
253
+ static_only: bool = True,
254
+ include_param_routes: bool = False,
255
+ specs_only: bool = False,
256
+ mock: bool = False,
257
+ environment: str | None = None,
258
+ ) -> BundleManifest:
259
+ """Render every declared route (Java's ``exportAll``): the registered classes' routes and
260
+ every ``routes.yaml`` entry (with or without a view model). ``:param`` routes are skipped
261
+ unless ``include_param_routes`` bundles them as TEMPLATES. ``specs_only`` ships each
262
+ browser-expandable definition-only route RAW instead of pre-rendering it."""
263
+ only_static = static_only and not include_param_routes
264
+ routes: list[str] = []
265
+
266
+ def add(route: str) -> None:
267
+ if route is not None and (not only_static or is_static(route)) and route not in routes:
268
+ routes.append(route)
269
+
270
+ for r in self.declared_routes():
271
+ add(r)
272
+ authored = self.handler.routes.authored()
273
+ for entry in authored.routes:
274
+ add("/" + entry.route)
275
+ classes = self.classes_by_route()
276
+ definitions = self.collect_definitions(authored)
277
+ self.stamp_mount_homes(authored, definitions)
278
+ expanded_in_browser: set[str] = set()
279
+ if specs_only:
280
+ for entry in authored.routes:
281
+ d = entry.definition
282
+ if (
283
+ d
284
+ and not entry.view_model
285
+ and is_client_expandable(definitions.get(d))
286
+ and self.yaml_access_restriction("/" + entry.route, authored, definitions) is None
287
+ ):
288
+ expanded_in_browser.add(normalized_route(entry.route))
289
+
290
+ entries: list[BundleEntry] = []
291
+ with _env("MATEU_SOURCES_MOCK", "true" if mock else None):
292
+ for route in routes:
293
+ if normalized_route(route) in expanded_in_browser:
294
+ log.info("bundle: %s ships as its raw definition (expanded in the browser)", route)
295
+ continue
296
+ restriction = identity_restriction(classes.get(normalized_route(route)))
297
+ if restriction is None:
298
+ restriction = self.yaml_access_restriction(route, authored, definitions)
299
+ if restriction is not None:
300
+ entries.append(BundleEntry(route, to_sync_path(route), None, False, restriction))
301
+ continue
302
+ entries.append(
303
+ self.export_route(base_url, route)
304
+ if is_static(route)
305
+ else self.export_template(base_url, route)
306
+ )
307
+ sources = self.source_catalogue(with_samples=mock)
308
+ from mateu_ui.core import environments
309
+
310
+ return BundleManifest(
311
+ base_url=base_url,
312
+ generated_at=_dt.datetime.now(_dt.timezone.utc).isoformat().replace("+00:00", "Z"),
313
+ static_only=only_static,
314
+ entries=entries,
315
+ routes=[route_entry_wire(e) for e in authored.routes],
316
+ sources=sources,
317
+ required_capabilities=aggregate_capabilities(entries),
318
+ definitions=without_guarded_definitions(definitions, authored),
319
+ actions=self.action_catalogue(),
320
+ translations=self.handler.translations.catalogue(),
321
+ environment=environments.active_name(environment),
322
+ mock_sources=True if mock else None,
323
+ )
324
+
325
+ def export(self, base_url: str, routes: list[str]) -> BundleManifest:
326
+ """Render exactly ``routes`` (Java's ``export``, the goal's explicit allow-list)."""
327
+ entries = [self.export_route(base_url, r) for r in routes]
328
+ return BundleManifest(
329
+ base_url=base_url,
330
+ generated_at=_dt.datetime.now(_dt.timezone.utc).isoformat().replace("+00:00", "Z"),
331
+ static_only=True,
332
+ entries=entries,
333
+ required_capabilities=aggregate_capabilities(entries),
334
+ )
335
+
336
+ def export_route(self, base_url: str, route: str) -> BundleEntry:
337
+ """A single route's loads; a skip (exception / no fragments) yields ``ok=False``."""
338
+ sync_path = to_sync_path(route)
339
+ try:
340
+ text = self.render(base_url, route, "_empty")
341
+ except _SkipError as skip:
342
+ return BundleEntry(route, sync_path, None, False, str(skip))
343
+ except Exception as e: # noqa: BLE001 - a route that cannot render stays backend-served
344
+ log.warning("skipping route %s (export failed): %r", route, e)
345
+ return BundleEntry(route, sync_path, None, False, f"{type(e).__name__}: {e}")
346
+ content = None
347
+ consumed = app_shell_consumed_route(text)
348
+ if consumed is not None and normalized_route(route):
349
+ try:
350
+ content = self.render(base_url, route, consumed)
351
+ except Exception as e: # noqa: BLE001 - the shell still bundles
352
+ log.warning("route %s: its content load could not be exported: %r", route, e)
353
+ return BundleEntry(route, sync_path, text, True, None, None, None, content)
354
+
355
+ def export_template(self, base_url: str, template_route: str) -> BundleEntry:
356
+ """A ``:param`` route as a TEMPLATE: rendered once with a placeholder per param; the entry
357
+ carries the regex + param names the browser matches a concrete path with."""
358
+ names = PARAM_SEGMENT.findall(template_route)
359
+ rendered = self.export_route(base_url, PARAM_SEGMENT.sub(PARAM_PLACEHOLDER, template_route))
360
+ sync_path = to_sync_path(template_route)
361
+ pattern = "^" + PARAM_SEGMENT.sub("([^/]+)", sync_path) + "$"
362
+ return BundleEntry(
363
+ template_route, sync_path, rendered.json, rendered.ok, rendered.skip_reason,
364
+ pattern, names, rendered.content_json,
365
+ )
366
+
367
+ def render(self, base_url: str, route: str, consumed_route: str) -> str:
368
+ """One ``actionId=""`` load of ``route`` as wire JSON."""
369
+ from mateu_ui.core import RunActionRq
370
+ from mateu_ui.core.translations import raw_expressions
371
+
372
+ rq = RunActionRq(route=route, consumed_route=consumed_route, action_id="")
373
+ # ${i18n.…} stays as written: the bundle serves every visitor, the browser resolves it
374
+ with raw_expressions():
375
+ increment = self.handler.handle(rq, base_url)
376
+ if increment is None:
377
+ raise _SkipError("empty increment")
378
+ if not increment.fragments:
379
+ messages = increment.messages or []
380
+ raise _SkipError(messages[0].text if messages and messages[0].text else "no fragments")
381
+ wire = increment.model_dump(by_alias=True, mode="json")
382
+ # A load renders for no initiator: the answer echoes it (an empty target) — the bundle
383
+ # leaves it untargeted (as Java's export does) and the browser re-targets it at whoever
384
+ # asked. ("ux_main" too: what the port answered up to 3.0-beta.67.)
385
+ for key in ("fragments", "commands"):
386
+ for item in wire.get(key) or []:
387
+ if isinstance(item, dict) and item.get("targetComponentId") in ("", "ux_main"):
388
+ item["targetComponentId"] = None
389
+ return json.dumps(wire, separators=(",", ":"), ensure_ascii=False)
390
+
391
+ def static_safety(self, manifest: BundleManifest) -> list:
392
+ """Every way the bundled routes still need a server (see :mod:`.static_safety`); empty
393
+ means the bundle runs with no backend at all."""
394
+ from .static_safety import check
395
+
396
+ return check(manifest, self.classes_by_route())
397
+
398
+ # ------------------------------------------------------------------ catalogues
399
+
400
+ def source_catalogue(self, with_samples: bool = False) -> list[dict[str, Any]]:
401
+ """The REST source catalogue as Java's ``RestSourceCatalog`` ships it: the authored
402
+ provenance (not the inferred one), samples only with the mock flag, a proxied source's
403
+ headers/body never (``forTheClient``)."""
404
+ from mateu_ui.core.rest_source_registry import entry_record
405
+
406
+ out = []
407
+ for entry in self.handler.rest_sources.catalog():
408
+ record = entry_record(entry, with_samples).model_dump(by_alias=True, mode="json")
409
+ record["provenance"] = getattr(entry.provenance, "value", entry.provenance)
410
+ out.append(record)
411
+ return out
412
+
413
+ def action_catalogue(self) -> list[dict[str, Any]]:
414
+ from mateu_ui.core.action_registry import to_dto
415
+
416
+ return [
417
+ to_dto(a).model_dump(by_alias=True, mode="json") for a in self.handler.action_catalog.catalog()
418
+ ]
419
+
420
+ # ------------------------------------------------------------------ definitions
421
+
422
+ def collect_definitions(self, authored) -> dict[str, Any]:
423
+ """The raw definitions of the definition-only routes, partials and business components
424
+ inlined and field types resolved (the browser has none of those catalogues)."""
425
+ from .inliner import DefinitionInliner
426
+
427
+ inliner = DefinitionInliner(self.specs_dir)
428
+ out: dict[str, Any] = {}
429
+ for entry in authored.routes:
430
+ d = entry.definition
431
+ if not d or entry.view_model or d in out:
432
+ continue
433
+ path = self.specs_dir / d.lstrip("/")
434
+ if not path.is_file():
435
+ log.warning("bundle: definition %s not found at %s — omitted", d, path)
436
+ continue
437
+ try:
438
+ tree = yaml.safe_load(path.read_text())
439
+ except Exception as e: # noqa: BLE001
440
+ log.warning("bundle: could not read definition %s: %s", d, e)
441
+ continue
442
+ out[d] = self.handler.field_types.resolve(inliner.inline(tree))
443
+ return out
444
+
445
+ def stamp_mount_homes(self, authored, definitions: dict[str, Any]) -> None:
446
+ """A mount's ``home:`` travels INTO its shell: an AppShell bound to the mount root that
447
+ declares no ``homeRoute:`` ships with the mount's home (Java's ``stampMountHomes``)."""
448
+ from mateu_ui.core import yaml_app_shell
449
+
450
+ for entry in authored.routes:
451
+ mount, home = yaml_app_shell.mount_of(self.handler.routes, entry.route)
452
+ if not home or normalized_route(entry.route) != mount:
453
+ continue
454
+ node = definitions.get(entry.definition) if entry.definition else None
455
+ if isinstance(node, dict) and node.get("type") == "AppShell" and node.get("homeRoute") is None:
456
+ node["homeRoute"] = home
457
+
458
+ def yaml_access_restriction(self, route: str, authored, definitions: dict[str, Any]) -> str | None:
459
+ from mateu_ui.core import yaml_access
460
+
461
+ match = authored.match(normalized_route(route))
462
+ if match is None:
463
+ return None
464
+ entry = match.entry
465
+ if entry.restricts_access():
466
+ return "identity-dependent: the route declares access: — kept backend-served"
467
+ definition = definitions.get(entry.definition) if entry.definition else None
468
+ if yaml_access.declares_access(definition):
469
+ return (
470
+ f"identity-dependent: definition '{entry.definition}' declares access keys — kept"
471
+ " backend-served"
472
+ )
473
+ return None
474
+
475
+
476
+ def app_shell_consumed_route(text: str) -> str | None:
477
+ """The consumed route an app shell sends when it loads its content slot, or None when the
478
+ increment is not an app shell."""
479
+ try:
480
+ component = json.loads(text)["fragments"][0]["component"]
481
+ except (ValueError, KeyError, IndexError, TypeError):
482
+ return None
483
+ metadata = component.get("metadata") or {}
484
+ if metadata.get("type") != "App":
485
+ return None
486
+ consumed = metadata.get("homeConsumedRoute")
487
+ return consumed if isinstance(consumed, str) else ""
488
+
489
+
490
+ def identity_restriction(cls: type | None) -> str | None:
491
+ """Why a class's route must NOT be pre-rendered (a screen depending on WHO asks), or None —
492
+ Java's ``identityRestriction``: ``@eyes_only`` on the class, a field or a method."""
493
+ if not isinstance(cls, type):
494
+ return None
495
+ if cls.__dict__.get("__mateu_eyes_only__") is not None:
496
+ return "identity-dependent: the class declares @eyes_only — kept backend-served"
497
+ from mateu_ui.uidl.security import EyesOnly
498
+
499
+ for name, hint in getattr(cls, "__annotations__", {}).items():
500
+ if any(isinstance(m, EyesOnly) for m in getattr(hint, "__metadata__", ())):
501
+ return f"identity-dependent: field '{name}' declares @eyes_only — kept backend-served"
502
+ for name, member in cls.__dict__.items():
503
+ if callable(member) and getattr(member, "__mateu_eyes_only__", None) is not None:
504
+ return f"identity-dependent: method '{name}' declares @eyes_only — kept backend-served"
505
+ return None
506
+
507
+
508
+ def without_guarded_definitions(definitions: dict[str, Any], authored) -> dict[str, Any]:
509
+ """No definition that depends on WHO asks: one declaring access keys, or one only
510
+ ``access:``-restricted routes use (Java's ``withoutGuardedDefinitions``)."""
511
+ from mateu_ui.core import yaml_access
512
+
513
+ public = {e.definition for e in authored.routes if e.definition and not e.restricts_access()}
514
+ out: dict[str, Any] = {}
515
+ for name, node in definitions.items():
516
+ if yaml_access.declares_access(node):
517
+ log.info("bundle: definition %s declares access keys — not shipped raw", name)
518
+ elif name not in public:
519
+ log.info("bundle: definition %s serves only access-restricted routes — not shipped", name)
520
+ else:
521
+ out[name] = node
522
+ return out
523
+
524
+
525
+ def aggregate_capabilities(entries: list[BundleEntry]) -> list[str]:
526
+ """The union of every entry's ``requiredCapabilities``, walked for the KEY (Java's
527
+ ``aggregateCapabilities``)."""
528
+ caps: set[str] = set()
529
+
530
+ def walk(node: Any) -> None:
531
+ if isinstance(node, dict):
532
+ rc = node.get("requiredCapabilities")
533
+ if isinstance(rc, list):
534
+ caps.update(c for c in rc if isinstance(c, str) and c.strip())
535
+ for v in node.values():
536
+ walk(v)
537
+ elif isinstance(node, list):
538
+ for v in node:
539
+ walk(v)
540
+
541
+ for e in entries:
542
+ if e.ok and e.json:
543
+ try:
544
+ walk(json.loads(e.json))
545
+ except ValueError:
546
+ pass
547
+ return sorted(caps)
548
+
549
+
550
+ def _source_ref_wire(ref) -> dict[str, Any] | None:
551
+ if ref is None:
552
+ return None
553
+ return {
554
+ "ref": ref.ref or "",
555
+ "url": ref.url or "",
556
+ "method": ref.method or "GET",
557
+ "headers": {},
558
+ "body": ref.body or "",
559
+ "itemsPath": ref.items_path or "",
560
+ "valuePath": ref.value_path or "value",
561
+ "labelPath": ref.label_path or "label",
562
+ "proxy": bool(ref.proxy),
563
+ "sample": None,
564
+ }
565
+
566
+
567
+ def _access_wire(access) -> dict[str, Any] | None:
568
+ if access is None:
569
+ return None
570
+ return {
571
+ k: list(getattr(access, k, ()) or ())
572
+ for k in ("roles", "groups", "scopes", "permissions")
573
+ }
574
+
575
+
576
+ def route_entry_wire(entry) -> dict[str, Any]:
577
+ """An authored route as Java's ``RouteEntry`` record serializes (the manifest's ``routes``)."""
578
+ return {
579
+ "route": entry.route,
580
+ "definition": entry.definition,
581
+ "viewModel": entry.view_model,
582
+ "fixedParams": dict(entry.fixed_params),
583
+ "defaultParams": dict(entry.default_params),
584
+ "parent": entry.parent,
585
+ "children": [],
586
+ "state": dict(entry.state),
587
+ "appState": dict(entry.app_state),
588
+ "data": _source_ref_wire(entry.data),
589
+ "appData": _source_ref_wire(entry.app_data),
590
+ "defaultChild": None,
591
+ "show": None,
592
+ "access": _access_wire(entry.access),
593
+ }
594
+
595
+
596
+ __all__ = [
597
+ "BundleEntry",
598
+ "BundleExporter",
599
+ "BundleManifest",
600
+ "CLIENT_EXPANDABLE_TYPES",
601
+ "PARAM_PLACEHOLDER",
602
+ "aggregate_capabilities",
603
+ "app_shell_consumed_route",
604
+ "is_client_expandable",
605
+ "to_sync_path",
606
+ "without_catalogue",
607
+ ]