fjkit 0.1.0.dev0__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 (127) hide show
  1. fjkit/__init__.py +49 -0
  2. fjkit/auth/__init__.py +54 -0
  3. fjkit/auth/csrf.py +88 -0
  4. fjkit/auth/errors.py +31 -0
  5. fjkit/auth/plugin.py +496 -0
  6. fjkit/auth/sources.py +24 -0
  7. fjkit/auth/stores.py +141 -0
  8. fjkit/auth/types.py +141 -0
  9. fjkit/cli/__init__.py +67 -0
  10. fjkit/cli/build_css.py +135 -0
  11. fjkit/cli/check.py +193 -0
  12. fjkit/cli/eject.py +562 -0
  13. fjkit/cli/ejected.py +202 -0
  14. fjkit/cli/vocabulary.py +85 -0
  15. fjkit/config.py +130 -0
  16. fjkit/errors.py +156 -0
  17. fjkit/flash.py +189 -0
  18. fjkit/forms.py +145 -0
  19. fjkit/htmx.py +76 -0
  20. fjkit/icons.py +60 -0
  21. fjkit/messages.py +227 -0
  22. fjkit/mounting.py +72 -0
  23. fjkit/plugins.py +223 -0
  24. fjkit/py.typed +0 -0
  25. fjkit/rendering.py +554 -0
  26. fjkit/signing.py +63 -0
  27. fjkit/static/brand/torii-bolt.png +0 -0
  28. fjkit/static/dist/fjkit-luma.css +2 -0
  29. fjkit/static/dist/fjkit-lyra.css +2 -0
  30. fjkit/static/dist/fjkit-maia.css +2 -0
  31. fjkit/static/dist/fjkit-mira.css +2 -0
  32. fjkit/static/dist/fjkit-nova.css +2 -0
  33. fjkit/static/dist/fjkit-rhea.css +2 -0
  34. fjkit/static/dist/fjkit-sera.css +2 -0
  35. fjkit/static/dist/fjkit-vega.css +2 -0
  36. fjkit/static/icons/lucide.json +1 -0
  37. fjkit/static/js/errors.js +117 -0
  38. fjkit/static/js/multiselect.js +126 -0
  39. fjkit/static/js/reveal.js +51 -0
  40. fjkit/static/js/select.js +113 -0
  41. fjkit/static/src/fjkit.css +385 -0
  42. fjkit/static/vendor/basecoat/base/base.css +136 -0
  43. fjkit/static/vendor/basecoat/basecoat-base.css +2 -0
  44. fjkit/static/vendor/basecoat/basecoat-components.css +39 -0
  45. fjkit/static/vendor/basecoat/basecoat-luma.css +2 -0
  46. fjkit/static/vendor/basecoat/basecoat-lyra.css +2 -0
  47. fjkit/static/vendor/basecoat/basecoat-maia.css +2 -0
  48. fjkit/static/vendor/basecoat/basecoat-mira.css +2 -0
  49. fjkit/static/vendor/basecoat/basecoat-nova.css +2 -0
  50. fjkit/static/vendor/basecoat/basecoat-rhea.css +2 -0
  51. fjkit/static/vendor/basecoat/basecoat-sera.css +2 -0
  52. fjkit/static/vendor/basecoat/basecoat-vega.css +2 -0
  53. fjkit/static/vendor/basecoat/basecoat.all.css +1 -0
  54. fjkit/static/vendor/basecoat/basecoat.css +1 -0
  55. fjkit/static/vendor/basecoat/components/accordion.css +27 -0
  56. fjkit/static/vendor/basecoat/components/alert.css +38 -0
  57. fjkit/static/vendor/basecoat/components/avatar.css +47 -0
  58. fjkit/static/vendor/basecoat/components/badge.css +6 -0
  59. fjkit/static/vendor/basecoat/components/breadcrumb.css +30 -0
  60. fjkit/static/vendor/basecoat/components/button-group.css +54 -0
  61. fjkit/static/vendor/basecoat/components/button.css +6 -0
  62. fjkit/static/vendor/basecoat/components/card.css +26 -0
  63. fjkit/static/vendor/basecoat/components/chart.css +56 -0
  64. fjkit/static/vendor/basecoat/components/checkbox.css +12 -0
  65. fjkit/static/vendor/basecoat/components/collapsible.css +21 -0
  66. fjkit/static/vendor/basecoat/components/combobox.css +99 -0
  67. fjkit/static/vendor/basecoat/components/command.css +140 -0
  68. fjkit/static/vendor/basecoat/components/dialog.css +101 -0
  69. fjkit/static/vendor/basecoat/components/drawer.css +89 -0
  70. fjkit/static/vendor/basecoat/components/dropdown-menu.css +56 -0
  71. fjkit/static/vendor/basecoat/components/empty.css +26 -0
  72. fjkit/static/vendor/basecoat/components/field.css +82 -0
  73. fjkit/static/vendor/basecoat/components/form.css +9 -0
  74. fjkit/static/vendor/basecoat/components/input-group.css +74 -0
  75. fjkit/static/vendor/basecoat/components/input.css +32 -0
  76. fjkit/static/vendor/basecoat/components/item.css +50 -0
  77. fjkit/static/vendor/basecoat/components/kbd.css +6 -0
  78. fjkit/static/vendor/basecoat/components/label.css +13 -0
  79. fjkit/static/vendor/basecoat/components/native-select.css +12 -0
  80. fjkit/static/vendor/basecoat/components/popover.css +107 -0
  81. fjkit/static/vendor/basecoat/components/progress.css +14 -0
  82. fjkit/static/vendor/basecoat/components/radio.css +11 -0
  83. fjkit/static/vendor/basecoat/components/range.css +50 -0
  84. fjkit/static/vendor/basecoat/components/scrollbar.css +46 -0
  85. fjkit/static/vendor/basecoat/components/select.css +64 -0
  86. fjkit/static/vendor/basecoat/components/sidebar.css +101 -0
  87. fjkit/static/vendor/basecoat/components/skeleton.css +6 -0
  88. fjkit/static/vendor/basecoat/components/switch.css +8 -0
  89. fjkit/static/vendor/basecoat/components/table.css +34 -0
  90. fjkit/static/vendor/basecoat/components/tabs.css +31 -0
  91. fjkit/static/vendor/basecoat/components/textarea.css +7 -0
  92. fjkit/static/vendor/basecoat/components/toast.css +57 -0
  93. fjkit/static/vendor/basecoat/components/tooltip.css +82 -0
  94. fjkit/static/vendor/basecoat/js/all.min.js +1 -0
  95. fjkit/static/vendor/basecoat/styles/luma.css +1376 -0
  96. fjkit/static/vendor/basecoat/styles/lyra.css +1379 -0
  97. fjkit/static/vendor/basecoat/styles/maia.css +1364 -0
  98. fjkit/static/vendor/basecoat/styles/mira.css +1373 -0
  99. fjkit/static/vendor/basecoat/styles/nova.css +1387 -0
  100. fjkit/static/vendor/basecoat/styles/rhea.css +1381 -0
  101. fjkit/static/vendor/basecoat/styles/sera.css +1397 -0
  102. fjkit/static/vendor/basecoat/styles/vega.css +1386 -0
  103. fjkit/static/vendor/htmx/htmx.min.js +1 -0
  104. fjkit/static/vendor/htmx/json-enc.js +38 -0
  105. fjkit/styles.py +30 -0
  106. fjkit/templates/errors/page.html +92 -0
  107. fjkit/templates/ui/attrs.html +18 -0
  108. fjkit/templates/ui/button.html +64 -0
  109. fjkit/templates/ui/data.html +362 -0
  110. fjkit/templates/ui/disclosure.html +89 -0
  111. fjkit/templates/ui/feedback.html +313 -0
  112. fjkit/templates/ui/form.html +595 -0
  113. fjkit/templates/ui/icon.html +13 -0
  114. fjkit/templates/ui/layout.html +189 -0
  115. fjkit/templates/ui/nav.html +110 -0
  116. fjkit/templates/ui/overlay.html +624 -0
  117. fjkit/templates/ui/shell.html +170 -0
  118. fjkit/templates/ui/sidebar.html +170 -0
  119. fjkit/templates/ui/table.html +427 -0
  120. fjkit/templates/ui/tabs.html +133 -0
  121. fjkit/templating.py +365 -0
  122. fjkit/vendored.py +46 -0
  123. fjkit-0.1.0.dev0.dist-info/METADATA +119 -0
  124. fjkit-0.1.0.dev0.dist-info/RECORD +127 -0
  125. fjkit-0.1.0.dev0.dist-info/WHEEL +4 -0
  126. fjkit-0.1.0.dev0.dist-info/entry_points.txt +2 -0
  127. fjkit-0.1.0.dev0.dist-info/licenses/LICENSE +21 -0
fjkit/rendering.py ADDED
@@ -0,0 +1,554 @@
1
+ """`@render` — the handler returns data, the decorator picks the wire format.
2
+
3
+ @router.get("/tasks", name="tasks_page")
4
+ @render("tasks/page.html", partial="tasks/_board.html")
5
+ def tasks_page(service: ServiceDep, status: Status | None = None) -> BoardResponse:
6
+ return BoardResponse(...)
7
+
8
+ The return annotation is both FastAPI's `response_model` and the template
9
+ context. `@render` goes below the routing decorator.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import dataclasses
15
+ import inspect
16
+ import json
17
+ import sys
18
+ from collections.abc import Callable, Mapping
19
+ from functools import wraps
20
+ from typing import Any, TypeVar, get_type_hints
21
+
22
+ from fastapi import Request, Response
23
+
24
+ from fjkit import htmx, messages
25
+ from fjkit.config import RenderMode
26
+ from fjkit.forms import NO_ERRORS
27
+
28
+ __all__ = ["SCOPE_RENDER_MODE", "Trigger", "TriggerValue", "render"]
29
+
30
+ F = TypeVar("F", bound=Callable[..., Any])
31
+
32
+ #: ASGI scope key: the representation an in-process caller wants back, as one of
33
+ #: `RenderMode`. Read by `_mode`, between the decorator's own argument and the
34
+ #: app-wide default.
35
+ #:
36
+ #: A scope key rather than a header, because of who can set each. A header
37
+ #: travels from outside and would let any client turn every page in the app
38
+ #: into JSON; only code already running in this process can write a scope key,
39
+ #: which is the guarantee that makes honouring it safe.
40
+ SCOPE_RENDER_MODE = "fjkit_render_mode"
41
+
42
+ #: Names for the parameters `@render` appends to a handler that did not ask for
43
+ #: them. Deliberately unusable as ordinary argument names: they arrive in the
44
+ #: handler's keyword arguments, and a collision with an app's own parameter
45
+ #: would be silent.
46
+ _REQUEST = "__fjkit_request"
47
+ _RESPONSE = "__fjkit_response"
48
+
49
+
50
+ #: What a route broadcasts alongside its markup: a mapping of event name to
51
+ #: detail, a bare event name, or `None` for "not this time".
52
+ TriggerValue = Mapping[str, Any] | str | None
53
+
54
+ #: `hx_trigger`, as written on the decorator. A callable is resolved per request
55
+ #: — see `_TriggerSpec` for what it is handed.
56
+ Trigger = TriggerValue | Callable[..., TriggerValue]
57
+
58
+
59
+ @dataclasses.dataclass(frozen=True, slots=True)
60
+ class _TriggerSpec:
61
+ """A `hx_trigger` callable, and the names it asked for.
62
+
63
+ The names are read once, when the decorator is applied: a signature does not
64
+ change between requests, and `inspect` is not cheap.
65
+
66
+ A callable takes its arguments by name from the handler's own resolved
67
+ parameters plus `result`, what the handler returned. So the event is written
68
+ where the route is declared while still reading a path parameter the route
69
+ only has at request time:
70
+
71
+ @render(None, hx_trigger=lambda task_id: {"task-selected": {"id": task_id}})
72
+ def select_task(service: ServiceDep, task_id: int) -> None: ...
73
+
74
+ Declaring `**kwargs` asks for all of them.
75
+ """
76
+
77
+ call: Callable[..., TriggerValue]
78
+ #: The parameter names, or `None` for a callable that declared `**kwargs`.
79
+ wants: frozenset[str] | None
80
+
81
+ @classmethod
82
+ def of(cls, trigger: Trigger) -> _TriggerSpec | None:
83
+ if not callable(trigger):
84
+ return None
85
+ params = inspect.signature(trigger).parameters.values()
86
+ if any(p.kind is p.VAR_KEYWORD for p in params):
87
+ return cls(trigger, None)
88
+ return cls(trigger, frozenset(p.name for p in params))
89
+
90
+ def resolve(self, result: Any, call_kwargs: Mapping[str, Any]) -> TriggerValue:
91
+ available = {**call_kwargs, "result": result}
92
+ if self.wants is None:
93
+ return self.call(**available)
94
+ return self.call(**{name: available[name] for name in self.wants if name in available})
95
+
96
+
97
+ @dataclasses.dataclass(frozen=True, slots=True)
98
+ class _Plan:
99
+ """What the decorator was asked to do. Built once, read on every request."""
100
+
101
+ template: str | None
102
+ partial: str | None
103
+ mode: RenderMode | None
104
+ stream: bool
105
+ buffer_size: int
106
+ #: What to put in `HX-Trigger`. A literal value, or a spec resolved per
107
+ #: request. See `render`.
108
+ hx_trigger: TriggerValue
109
+ trigger_spec: _TriggerSpec | None
110
+ #: The same, for `HX-Trigger-After-Swap`. A separate field rather than a
111
+ #: header name on the first, because a route may raise both and they are
112
+ #: not interchangeable: the two differ in what a listener may read.
113
+ hx_trigger_after_swap: TriggerValue
114
+ trigger_after_swap_spec: _TriggerSpec | None
115
+ #: Whether a request that is not from htmx still has markup waiting for it.
116
+ #: Decided once, when the decorator is applied, because it is a property of
117
+ #: the route rather than of the request.
118
+ serves_a_page: bool
119
+
120
+
121
+ def render(
122
+ template: str | None,
123
+ *,
124
+ partial: str | None = None,
125
+ mode: RenderMode | None = None,
126
+ stream: bool = False,
127
+ buffer_size: int = 64,
128
+ hx_trigger: Trigger = None,
129
+ hx_trigger_after_swap: Trigger = None,
130
+ ) -> Callable[[F], F]:
131
+ """Render `template` with whatever the handler returned.
132
+
133
+ :param template: the full page, or the only template when there is one.
134
+ `None` for a route that answers with no body at all — the status code and
135
+ the headers still apply, so it is how a route broadcasts and renders
136
+ nothing.
137
+ :param partial: rendered instead of `template` for an htmx swap.
138
+ :param mode: `"html"`, `"json"` or `"auto"` for this route, overriding
139
+ `FjkitConfig.render_mode`. `"auto"` renders for htmx and for a page
140
+ route's navigation, and serialises the model otherwise.
141
+ :param stream: render through `templates.stream()` rather than `page()`.
142
+ :param buffer_size: chunk size when `stream=True`. Never 0.
143
+ :param hx_trigger: an event to raise in the browser on this response, as
144
+ `HX-Trigger`. Usually a callable, which receives the handler's own
145
+ parameters and `result` **by name**:
146
+
147
+ @render("selection/_list.html",
148
+ hx_trigger=lambda task_id: {"task-selected": {"task_id": task_id}})
149
+
150
+ so one route answers with its own partial and tells the rest of the page
151
+ what happened — swap and broadcast declared in one place, on a route that is
152
+ otherwise an ordinary partial route.
153
+
154
+ A `str` names an event with no detail. `None` — as the argument, or returned
155
+ by the callable — raises nothing, which is how a route broadcasts only
156
+ sometimes. Merged with any `HX-Trigger` the handler set on its `Response`
157
+ and with a queued toast, so none of the three silently drops another.
158
+
159
+ Sent on the HTML representation only, exactly like a toast. `HX-Trigger` is
160
+ htmx's protocol, and a caller that asked this route for JSON has no htmx in
161
+ it to read the header — see `mode`.
162
+
163
+ Send an **object** as the detail. htmx passes an object through as
164
+ `event.detail` and wraps anything else — an array included — as
165
+ `{value: ...}`, so a listener reading `event.detail.task_id` finds nothing.
166
+
167
+ :param hx_trigger_after_swap: the same event, in `HX-Trigger-After-Swap`.
168
+ It takes every form `hx_trigger` does and differs only in **when** htmx
169
+ raises it, which decides what a subscriber may read.
170
+
171
+ `HX-Trigger` fires **before** this response is swapped in. A subscriber that
172
+ reads `event.detail` is unaffected; one that reads the page is not, because
173
+ the markup it reads is what this reply is about to replace. A route that
174
+ answers with the table and raises `task-selected` in `HX-Trigger` therefore
175
+ cannot be heard by a fragment whose `hx-include` points at a value that
176
+ table carries: it would read the previous id.
177
+
178
+ `HX-Trigger-After-Swap` fires once the swap is in the document, which lets
179
+ the event carry no detail at all and every subscriber pick up what it needs
180
+ off the page with `hx-include`. A lazy tab panel needs that shape, because a
181
+ panel hidden when the pick happened never saw the event and has only the
182
+ page to read — see `ui/tabs.html`.
183
+
184
+ Both may be set on one route; they are separate headers and neither
185
+ merges into the other. Reach for `hx_trigger` when the listeners read
186
+ `event.detail`, and for this when they read the DOM.
187
+
188
+ The handler may return a Pydantic model, a dataclass, a mapping, `None`, or
189
+ a `Response`; a `Response` is passed through untouched.
190
+ """
191
+ plan = _Plan(
192
+ template=template,
193
+ partial=partial,
194
+ mode=mode,
195
+ stream=stream,
196
+ buffer_size=buffer_size,
197
+ hx_trigger=None if callable(hx_trigger) else hx_trigger,
198
+ trigger_spec=_TriggerSpec.of(hx_trigger),
199
+ hx_trigger_after_swap=None if callable(hx_trigger_after_swap) else hx_trigger_after_swap,
200
+ trigger_after_swap_spec=_TriggerSpec.of(hx_trigger_after_swap),
201
+ # `partial=` is definitive: it exists because `template` is the page a
202
+ # navigation gets. Otherwise the filename answers, on the convention
203
+ # every template in the codebase already follows and
204
+ # `test_conventions.py` enforces — a fragment is `_*.html`.
205
+ serves_a_page=template is not None
206
+ and (partial is not None or not template.rpartition("/")[2].startswith("_")),
207
+ )
208
+
209
+ def decorate(func: F) -> F:
210
+ # The frame applying the decorator. Its locals are the only place to
211
+ # find a response model defined inside a function — a factory, a test —
212
+ # and under `from __future__ import annotations` the annotation naming
213
+ # it is a string nothing else can resolve.
214
+ endpoint = _Endpoint(func, _caller_locals(depth=1))
215
+
216
+ if inspect.iscoroutinefunction(func):
217
+
218
+ @wraps(func)
219
+ async def wrapper(**kwargs: Any) -> Any:
220
+ request, response, call_kwargs = endpoint.unpack(kwargs)
221
+ return _finish(await func(**call_kwargs), request, response, plan, call_kwargs)
222
+
223
+ else:
224
+ # A sync handler keeps a sync wrapper on purpose. Starlette sends
225
+ # only `def` endpoints to the threadpool, so wrapping one in
226
+ # `async def` would move every template render onto the event loop
227
+ # and stall the worker's other requests.
228
+ @wraps(func)
229
+ def wrapper(**kwargs: Any) -> Any:
230
+ request, response, call_kwargs = endpoint.unpack(kwargs)
231
+ return _finish(func(**call_kwargs), request, response, plan, call_kwargs)
232
+
233
+ wrapper.__signature__ = endpoint.signature # type: ignore[attr-defined]
234
+ # Stamped on the function FastAPI registers, so `fjkit.errors` finds it
235
+ # from `request.scope["route"].endpoint` with nothing to keep in step:
236
+ # the route table already knows which function serves the request, and
237
+ # this rides on that instead of a second registry beside it.
238
+ wrapper.__fjkit_plan__ = plan # type: ignore[attr-defined]
239
+ return wrapper # type: ignore[return-value]
240
+
241
+ return decorate
242
+
243
+
244
+ class _Endpoint:
245
+ """The handler's signature, resolved and amended, ready for FastAPI.
246
+
247
+ String annotations resolve against the original function's globals, because
248
+ a wrapper's globals are fjkit's. `Request` and `Response` are appended when
249
+ the handler did not declare them.
250
+ """
251
+
252
+ __slots__ = ("injected", "request_param", "response_param", "signature")
253
+
254
+ def __init__(self, func: Callable[..., Any], localns: Mapping[str, Any] | None = None) -> None:
255
+ hints = _hints(func, localns)
256
+ original = inspect.signature(func)
257
+ params = [p.replace(annotation=hints.get(p.name, p.annotation)) for p in original.parameters.values()]
258
+
259
+ self.request_param = _param_named(params, Request)
260
+ self.response_param = _param_named(params, Response)
261
+
262
+ added: list[inspect.Parameter] = []
263
+ if self.request_param is None:
264
+ self.request_param = _REQUEST
265
+ added.append(inspect.Parameter(_REQUEST, inspect.Parameter.KEYWORD_ONLY, annotation=Request))
266
+ if self.response_param is None:
267
+ self.response_param = _RESPONSE
268
+ added.append(inspect.Parameter(_RESPONSE, inspect.Parameter.KEYWORD_ONLY, annotation=Response))
269
+ self.injected = frozenset(p.name for p in added)
270
+
271
+ # Keyword-only, and ahead of any **kwargs. An appended positional would
272
+ # have to follow the handler's defaulted parameters, and `Signature`
273
+ # rejects that outright.
274
+ var_kw = [p for p in params if p.kind is inspect.Parameter.VAR_KEYWORD]
275
+ fixed = [p for p in params if p.kind is not inspect.Parameter.VAR_KEYWORD]
276
+ # `get_type_hints` resolves `-> None` to `NoneType`, and FastAPI reads
277
+ # the return annotation to infer `response_model`. `None` is falsy and
278
+ # means "no model"; the class is not, so a handler annotated `-> None`
279
+ # would acquire a response model it never had — and on a 204 route
280
+ # FastAPI refuses outright, because no body is allowed there. Hand back
281
+ # what the source said.
282
+ returns = hints.get("return", original.return_annotation)
283
+ self.signature = original.replace(
284
+ parameters=fixed + added + var_kw,
285
+ return_annotation=None if returns is type(None) else returns,
286
+ )
287
+
288
+ def unpack(self, kwargs: dict[str, Any]) -> tuple[Request, Response | None, dict[str, Any]]:
289
+ """Split FastAPI's solved arguments into ours and the handler's."""
290
+ request = kwargs[self.request_param]
291
+ response = kwargs.get(self.response_param)
292
+ if self.injected:
293
+ kwargs = {k: v for k, v in kwargs.items() if k not in self.injected}
294
+ return request, response, kwargs
295
+
296
+
297
+ def _caller_locals(depth: int) -> Mapping[str, Any]:
298
+ """Locals of the frame `depth` levels up, or nothing when the interpreter
299
+ will not say. `sys._getframe` is CPython-only, so this improves the
300
+ resolution rules rather than being required by them."""
301
+ try:
302
+ return sys._getframe(depth + 1).f_locals
303
+ except (AttributeError, ValueError): # pragma: no cover — non-CPython
304
+ return {}
305
+
306
+
307
+ def _hints(func: Callable[..., Any], localns: Mapping[str, Any] | None) -> dict[str, Any]:
308
+ try:
309
+ return get_type_hints(func, localns=dict(localns) if localns else None, include_extras=True)
310
+ except Exception as exc: # noqa: BLE001 — re-raised with the part that matters
311
+ raise TypeError(
312
+ f"@render cannot resolve the annotations on {func.__module__}.{func.__qualname__}: {exc}. "
313
+ "Annotations on a decorated handler are resolved against its own module and the scope it was "
314
+ "defined in, because a wrapper's __globals__ belongs to fjkit — so a name imported inside "
315
+ "`if TYPE_CHECKING:` will not be found here even though the type checker sees it."
316
+ ) from exc
317
+
318
+
319
+ def _param_named(params: list[inspect.Parameter], kind: type) -> str | None:
320
+ for param in params:
321
+ if inspect.isclass(param.annotation) and issubclass(param.annotation, kind):
322
+ return param.name
323
+ return None
324
+
325
+
326
+ def _finish(
327
+ result: Any,
328
+ request: Request,
329
+ response: Response | None,
330
+ plan: _Plan,
331
+ call_kwargs: Mapping[str, Any],
332
+ ) -> Any:
333
+ # An explicit `Response` is the escape hatch — redirects, files, a
334
+ # hand-built `StreamingResponse`. Nothing here second-guesses one.
335
+ if isinstance(result, Response):
336
+ return result
337
+
338
+ # A route with no template answers with headers alone. Nothing below applies
339
+ # to it: there is no representation to negotiate, so no `Vary`, and no shell
340
+ # that could carry a toast instead of the header.
341
+ if plan.template is None:
342
+ status_code, headers = _response_args(request, response)
343
+ _deliver_trigger(plan, result, call_kwargs, headers)
344
+ _deliver_messages(request, headers, renders_shell=False)
345
+ return Response(status_code=status_code, headers=headers)
346
+
347
+ requested = _mode(request, plan.mode)
348
+ from_htmx = htmx.is_htmx(request)
349
+
350
+ # Whether the reply depends on the header, and so whether a shared cache may
351
+ # reuse it. Two ways it can: a route with a `partial` answers one URL with a
352
+ # page or a fragment, and a fragment route in `"auto"` answers it with
353
+ # markup or with JSON. Miss this and a CDN serves the fragment into a
354
+ # navigation — a page with no shell, and no error anywhere.
355
+ if plan.partial is not None or (requested == "auto" and not plan.serves_a_page):
356
+ _vary_on_htmx(response)
357
+
358
+ if requested == "auto":
359
+ # `is_htmx`, not `is_swap`: a boosted link is htmx doing an ordinary
360
+ # navigation, so it is excluded from the page-or-fragment decision but
361
+ # not from this one — it is still a browser waiting for markup. The two
362
+ # questions read different headers.
363
+ requested = "html" if from_htmx or plan.serves_a_page else "json"
364
+
365
+ if requested == "json":
366
+ # Handed back untouched: FastAPI validates and serialises it through the
367
+ # route's `response_model`, so the return annotation stays the one
368
+ # description of the JSON.
369
+ return result
370
+
371
+ templates = _templates(request)
372
+ name = plan.partial if plan.partial and htmx.is_swap(request) else plan.template
373
+ context = _context(result, plan.template)
374
+ # Every render can ask `errors.<name>`, including the ones with nothing to
375
+ # report, so a template passing `error=errors.title` never has to guard the
376
+ # key — see `fjkit.forms.NO_ERRORS`.
377
+ context.setdefault("errors", NO_ERRORS)
378
+ status_code, headers = _response_args(request, response)
379
+ _deliver_trigger(plan, result, call_kwargs, headers)
380
+ _deliver_messages(request, headers, renders_shell=name == plan.template and plan.serves_a_page)
381
+ if plan.stream:
382
+ return templates.stream(
383
+ request, name, context, buffer_size=plan.buffer_size, status_code=status_code, headers=headers
384
+ )
385
+ return templates.page(request, name, context, status_code=status_code, headers=headers)
386
+
387
+
388
+ def _deliver_trigger(plan: _Plan, result: Any, call_kwargs: Mapping[str, Any], headers: dict[str, str]) -> None:
389
+ """Write the route's own events into their headers, merging with what is
390
+ already there.
391
+
392
+ Runs before `_deliver_messages`, so a toast queued on the same response is
393
+ added to `HX-Trigger` rather than replacing it: the merge lives in one
394
+ place, `messages.trigger_header`.
395
+
396
+ The two headers are written independently and never merge into each other.
397
+ They are different moments, so an event in one is not the same event in the
398
+ other, and folding them together would change when a subscriber hears it.
399
+ """
400
+ _write_trigger(headers, "HX-Trigger", plan.hx_trigger, plan.trigger_spec, result, call_kwargs)
401
+ _write_trigger(
402
+ headers,
403
+ "HX-Trigger-After-Swap",
404
+ plan.hx_trigger_after_swap,
405
+ plan.trigger_after_swap_spec,
406
+ result,
407
+ call_kwargs,
408
+ )
409
+
410
+
411
+ def _write_trigger(
412
+ headers: dict[str, str],
413
+ name: str,
414
+ literal: TriggerValue,
415
+ spec: _TriggerSpec | None,
416
+ result: Any,
417
+ call_kwargs: Mapping[str, Any],
418
+ ) -> None:
419
+ """Write one event into one header. `None` — literal or resolved — writes
420
+ nothing."""
421
+ value = spec.resolve(result, call_kwargs) if spec is not None else literal
422
+ if value is None:
423
+ return
424
+ # Case-insensitively, because `_response_args` copies out of a Starlette
425
+ # `MutableHeaders`, which lowercases every name it was given.
426
+ existing = next((key for key in headers if key.lower() == name.lower()), None)
427
+ headers[existing or name] = _merge_trigger(headers.get(existing) if existing else None, value)
428
+
429
+
430
+ def _merge_trigger(existing: str | None, value: Mapping[str, Any] | str) -> str:
431
+ """Add `value` to whatever the handler's own `Response` already carried.
432
+
433
+ A bare name stays a bare name when nothing else is in play: htmx accepts
434
+ `HX-Trigger: task-selected`, and a route with one detail-free event should
435
+ not pay for JSON to say so.
436
+ """
437
+ if existing is None and isinstance(value, str):
438
+ return value
439
+ events = _as_events(existing)
440
+ events.update({value: None} if isinstance(value, str) else value)
441
+ return json.dumps(events, separators=(",", ":"))
442
+
443
+
444
+ def _as_events(header: str | None) -> dict[str, Any]:
445
+ """Read an `HX-Trigger` value as the mapping htmx reads it as.
446
+
447
+ The same promotion `messages.trigger_header` does, for the same reason: htmx
448
+ accepts a bare event name or a comma-separated list as well as JSON, and
449
+ neither may be discarded because something else wants to be in the header
450
+ too.
451
+ """
452
+ if not header:
453
+ return {}
454
+ text = header.strip()
455
+ if text.startswith("{"):
456
+ try:
457
+ return dict(json.loads(text))
458
+ except ValueError:
459
+ return {text: None}
460
+ return {name.strip(): None for name in text.split(",") if name.strip()}
461
+
462
+
463
+ def _deliver_messages(request: Request, headers: dict[str, str], *, renders_shell: bool) -> None:
464
+ """Pick the channel a queued message goes out on. See `fjkit.messages`.
465
+
466
+ A render of the shell carries the toaster, so the message goes in the
467
+ document; anything else sends it as `HX-Trigger`. Never both.
468
+ """
469
+ if renders_shell:
470
+ return
471
+ # Case-insensitively, because `_response_args` copies out of a Starlette
472
+ # `MutableHeaders`, which lowercases every name it was given. A handler
473
+ # writes `HX-Trigger`; what arrives here is `hx-trigger`.
474
+ existing = next((key for key in headers if key.lower() == "hx-trigger"), None)
475
+ trigger = messages.trigger_header(request, headers.get(existing) if existing else None)
476
+ if trigger is not None:
477
+ headers[existing or "HX-Trigger"] = trigger
478
+
479
+
480
+ def _mode(request: Request, override: RenderMode | None) -> RenderMode:
481
+ """Pick the mode: decorator argument, then `SCOPE_RENDER_MODE`, then the app
482
+ default.
483
+
484
+ Only in-process code can set the scope key (`fjkit_apidocs.console` does).
485
+ Resolved per request, because the decorator runs before the app has a
486
+ config.
487
+ """
488
+ if override is not None:
489
+ return override
490
+ asked = request.scope.get(SCOPE_RENDER_MODE)
491
+ if asked is not None:
492
+ return asked
493
+ return _templates(request).config.render_mode
494
+
495
+
496
+ def _templates(request: Request):
497
+ templates = getattr(request.app.state, "templates", None)
498
+ if templates is None:
499
+ raise RuntimeError(
500
+ "@render needs `app.state.templates`. Wire it once, at app "
501
+ "construction: `mount_fjkit(app, config)`."
502
+ )
503
+ return templates
504
+
505
+
506
+ def _vary_on_htmx(response: Response | None) -> None:
507
+ """Add `HX-Request` to `Vary`, keeping whatever the handler already set."""
508
+ if response is None: # pragma: no cover — the decorator always injects one
509
+ return
510
+ existing = response.headers.get("vary")
511
+ if existing is None:
512
+ response.headers["vary"] = "HX-Request"
513
+ elif "hx-request" not in existing.lower():
514
+ response.headers["vary"] = f"{existing}, HX-Request"
515
+
516
+
517
+ def _context(result: Any, template: str) -> dict[str, Any]:
518
+ """Build the template context from whatever the handler returned. A model is
519
+ spread field by field, not dumped, so the template gets the live objects.
520
+ """
521
+ if result is None:
522
+ return {}
523
+ if isinstance(result, Mapping):
524
+ return dict(result)
525
+ # Recognised by its fields rather than by `isinstance(result, BaseModel)`,
526
+ # so the kit does not import pydantic. FastAPI cannot exist without it, but
527
+ # fjkit declares two runtime dependencies and CHARTER §7 keeps it at two —
528
+ # an import is what turns a transitive package into a third.
529
+ cls = type(result)
530
+ fields = getattr(cls, "model_fields", None)
531
+ if isinstance(fields, Mapping):
532
+ computed = getattr(cls, "model_computed_fields", {})
533
+ return {name: getattr(result, name) for name in (*fields, *computed)}
534
+ if dataclasses.is_dataclass(result) and not isinstance(result, type):
535
+ return {f.name: getattr(result, f.name) for f in dataclasses.fields(result)}
536
+ raise TypeError(
537
+ f"@render({template!r}) expected a pydantic model, a dataclass, a mapping, None or a Response — "
538
+ f"got {type(result).__name__}."
539
+ )
540
+
541
+
542
+ def _response_args(request: Request, response: Response | None) -> tuple[int, dict[str, str]]:
543
+ """Resolve status and headers in precedence order: the handler's
544
+ `Response`, the route's `status_code`, 200. FastAPI merges these only into
545
+ replies it builds itself.
546
+ """
547
+ route = request.scope.get("route")
548
+ status_code = getattr(route, "status_code", None) or 200
549
+ headers: dict[str, str] = {}
550
+ if response is not None:
551
+ if response.status_code is not None:
552
+ status_code = response.status_code
553
+ headers.update(response.headers)
554
+ return status_code, headers
fjkit/signing.py ADDED
@@ -0,0 +1,63 @@
1
+ """`<body>.<mac>` — the one cookie format the kit signs with.
2
+
3
+ Two plugins keep a value in a cookie the browser must not be able to write: a
4
+ flash message (otherwise a way to make a site display any text an attacker
5
+ likes) and the API console's credential. Neither value has to stay secret — one
6
+ is about to be printed on the page, the other is the caller's own token — so
7
+ this signs and does not encrypt.
8
+
9
+ One implementation rather than one per plugin: signing and verifying drifting
10
+ apart is the shape of bug that makes every cookie look valid.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import base64
16
+ import binascii
17
+ import hashlib
18
+ import hmac
19
+
20
+ __all__ = ["sign", "sign_text", "unsign", "unsign_text"]
21
+
22
+
23
+ def sign(secret: bytes, payload: bytes) -> str:
24
+ """`payload`, base64url-encoded, with its MAC appended."""
25
+ return sign_text(secret, base64.urlsafe_b64encode(payload).decode("ascii").rstrip("="))
26
+
27
+
28
+ def sign_text(secret: bytes, body: str) -> str:
29
+ """Sign a body that is already ASCII-safe.
30
+
31
+ Verification calls this too: `unsign` re-signs the body it was handed and
32
+ compares, so one place decides what a signature is.
33
+ """
34
+ mac = hmac.new(secret, body.encode("ascii"), hashlib.sha256).digest()
35
+ return f"{body}.{base64.urlsafe_b64encode(mac).decode('ascii').rstrip('=')}"
36
+
37
+
38
+ def unsign(secret: bytes, raw: str) -> bytes | None:
39
+ """The payload `sign` was given, or `None` if this is not ours."""
40
+ body = unsign_text(secret, raw)
41
+ if body is None:
42
+ return None
43
+ try:
44
+ return base64.urlsafe_b64decode(body + "=" * (-len(body) % 4))
45
+ except (binascii.Error, ValueError):
46
+ return None
47
+
48
+
49
+ def unsign_text(secret: bytes, raw: str) -> str | None:
50
+ """The body half, verified but not decoded."""
51
+ body, _, signature = raw.partition(".")
52
+ if not signature:
53
+ return None
54
+ try:
55
+ expected = sign_text(secret, body)
56
+ except UnicodeEncodeError:
57
+ # `sign_text` never produced a body with non-ASCII in it, so it cannot
58
+ # verify. Refusing here keeps the failure a `None` like every other bad
59
+ # cookie instead of an exception on the hot path.
60
+ return None
61
+ if not hmac.compare_digest(raw, expected):
62
+ return None
63
+ return body
Binary file