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.
- fjkit/__init__.py +49 -0
- fjkit/auth/__init__.py +54 -0
- fjkit/auth/csrf.py +88 -0
- fjkit/auth/errors.py +31 -0
- fjkit/auth/plugin.py +496 -0
- fjkit/auth/sources.py +24 -0
- fjkit/auth/stores.py +141 -0
- fjkit/auth/types.py +141 -0
- fjkit/cli/__init__.py +67 -0
- fjkit/cli/build_css.py +135 -0
- fjkit/cli/check.py +193 -0
- fjkit/cli/eject.py +562 -0
- fjkit/cli/ejected.py +202 -0
- fjkit/cli/vocabulary.py +85 -0
- fjkit/config.py +130 -0
- fjkit/errors.py +156 -0
- fjkit/flash.py +189 -0
- fjkit/forms.py +145 -0
- fjkit/htmx.py +76 -0
- fjkit/icons.py +60 -0
- fjkit/messages.py +227 -0
- fjkit/mounting.py +72 -0
- fjkit/plugins.py +223 -0
- fjkit/py.typed +0 -0
- fjkit/rendering.py +554 -0
- fjkit/signing.py +63 -0
- fjkit/static/brand/torii-bolt.png +0 -0
- fjkit/static/dist/fjkit-luma.css +2 -0
- fjkit/static/dist/fjkit-lyra.css +2 -0
- fjkit/static/dist/fjkit-maia.css +2 -0
- fjkit/static/dist/fjkit-mira.css +2 -0
- fjkit/static/dist/fjkit-nova.css +2 -0
- fjkit/static/dist/fjkit-rhea.css +2 -0
- fjkit/static/dist/fjkit-sera.css +2 -0
- fjkit/static/dist/fjkit-vega.css +2 -0
- fjkit/static/icons/lucide.json +1 -0
- fjkit/static/js/errors.js +117 -0
- fjkit/static/js/multiselect.js +126 -0
- fjkit/static/js/reveal.js +51 -0
- fjkit/static/js/select.js +113 -0
- fjkit/static/src/fjkit.css +385 -0
- fjkit/static/vendor/basecoat/base/base.css +136 -0
- fjkit/static/vendor/basecoat/basecoat-base.css +2 -0
- fjkit/static/vendor/basecoat/basecoat-components.css +39 -0
- fjkit/static/vendor/basecoat/basecoat-luma.css +2 -0
- fjkit/static/vendor/basecoat/basecoat-lyra.css +2 -0
- fjkit/static/vendor/basecoat/basecoat-maia.css +2 -0
- fjkit/static/vendor/basecoat/basecoat-mira.css +2 -0
- fjkit/static/vendor/basecoat/basecoat-nova.css +2 -0
- fjkit/static/vendor/basecoat/basecoat-rhea.css +2 -0
- fjkit/static/vendor/basecoat/basecoat-sera.css +2 -0
- fjkit/static/vendor/basecoat/basecoat-vega.css +2 -0
- fjkit/static/vendor/basecoat/basecoat.all.css +1 -0
- fjkit/static/vendor/basecoat/basecoat.css +1 -0
- fjkit/static/vendor/basecoat/components/accordion.css +27 -0
- fjkit/static/vendor/basecoat/components/alert.css +38 -0
- fjkit/static/vendor/basecoat/components/avatar.css +47 -0
- fjkit/static/vendor/basecoat/components/badge.css +6 -0
- fjkit/static/vendor/basecoat/components/breadcrumb.css +30 -0
- fjkit/static/vendor/basecoat/components/button-group.css +54 -0
- fjkit/static/vendor/basecoat/components/button.css +6 -0
- fjkit/static/vendor/basecoat/components/card.css +26 -0
- fjkit/static/vendor/basecoat/components/chart.css +56 -0
- fjkit/static/vendor/basecoat/components/checkbox.css +12 -0
- fjkit/static/vendor/basecoat/components/collapsible.css +21 -0
- fjkit/static/vendor/basecoat/components/combobox.css +99 -0
- fjkit/static/vendor/basecoat/components/command.css +140 -0
- fjkit/static/vendor/basecoat/components/dialog.css +101 -0
- fjkit/static/vendor/basecoat/components/drawer.css +89 -0
- fjkit/static/vendor/basecoat/components/dropdown-menu.css +56 -0
- fjkit/static/vendor/basecoat/components/empty.css +26 -0
- fjkit/static/vendor/basecoat/components/field.css +82 -0
- fjkit/static/vendor/basecoat/components/form.css +9 -0
- fjkit/static/vendor/basecoat/components/input-group.css +74 -0
- fjkit/static/vendor/basecoat/components/input.css +32 -0
- fjkit/static/vendor/basecoat/components/item.css +50 -0
- fjkit/static/vendor/basecoat/components/kbd.css +6 -0
- fjkit/static/vendor/basecoat/components/label.css +13 -0
- fjkit/static/vendor/basecoat/components/native-select.css +12 -0
- fjkit/static/vendor/basecoat/components/popover.css +107 -0
- fjkit/static/vendor/basecoat/components/progress.css +14 -0
- fjkit/static/vendor/basecoat/components/radio.css +11 -0
- fjkit/static/vendor/basecoat/components/range.css +50 -0
- fjkit/static/vendor/basecoat/components/scrollbar.css +46 -0
- fjkit/static/vendor/basecoat/components/select.css +64 -0
- fjkit/static/vendor/basecoat/components/sidebar.css +101 -0
- fjkit/static/vendor/basecoat/components/skeleton.css +6 -0
- fjkit/static/vendor/basecoat/components/switch.css +8 -0
- fjkit/static/vendor/basecoat/components/table.css +34 -0
- fjkit/static/vendor/basecoat/components/tabs.css +31 -0
- fjkit/static/vendor/basecoat/components/textarea.css +7 -0
- fjkit/static/vendor/basecoat/components/toast.css +57 -0
- fjkit/static/vendor/basecoat/components/tooltip.css +82 -0
- fjkit/static/vendor/basecoat/js/all.min.js +1 -0
- fjkit/static/vendor/basecoat/styles/luma.css +1376 -0
- fjkit/static/vendor/basecoat/styles/lyra.css +1379 -0
- fjkit/static/vendor/basecoat/styles/maia.css +1364 -0
- fjkit/static/vendor/basecoat/styles/mira.css +1373 -0
- fjkit/static/vendor/basecoat/styles/nova.css +1387 -0
- fjkit/static/vendor/basecoat/styles/rhea.css +1381 -0
- fjkit/static/vendor/basecoat/styles/sera.css +1397 -0
- fjkit/static/vendor/basecoat/styles/vega.css +1386 -0
- fjkit/static/vendor/htmx/htmx.min.js +1 -0
- fjkit/static/vendor/htmx/json-enc.js +38 -0
- fjkit/styles.py +30 -0
- fjkit/templates/errors/page.html +92 -0
- fjkit/templates/ui/attrs.html +18 -0
- fjkit/templates/ui/button.html +64 -0
- fjkit/templates/ui/data.html +362 -0
- fjkit/templates/ui/disclosure.html +89 -0
- fjkit/templates/ui/feedback.html +313 -0
- fjkit/templates/ui/form.html +595 -0
- fjkit/templates/ui/icon.html +13 -0
- fjkit/templates/ui/layout.html +189 -0
- fjkit/templates/ui/nav.html +110 -0
- fjkit/templates/ui/overlay.html +624 -0
- fjkit/templates/ui/shell.html +170 -0
- fjkit/templates/ui/sidebar.html +170 -0
- fjkit/templates/ui/table.html +427 -0
- fjkit/templates/ui/tabs.html +133 -0
- fjkit/templating.py +365 -0
- fjkit/vendored.py +46 -0
- fjkit-0.1.0.dev0.dist-info/METADATA +119 -0
- fjkit-0.1.0.dev0.dist-info/RECORD +127 -0
- fjkit-0.1.0.dev0.dist-info/WHEEL +4 -0
- fjkit-0.1.0.dev0.dist-info/entry_points.txt +2 -0
- fjkit-0.1.0.dev0.dist-info/licenses/LICENSE +21 -0
fjkit/cli/ejected.py
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
"""The stamp `fjkit eject` writes, and how a stale copy is found again later.
|
|
2
|
+
|
|
3
|
+
An ejected component is a copy: the loader finds the app's file first, so the
|
|
4
|
+
copy shadows the kit's and no call site changes (CHARTER.md A5). The cost is
|
|
5
|
+
that the copy stops receiving upstream fixes, silently. A year later nobody
|
|
6
|
+
remembers which version a file was ejected from, or whether the kit has changed
|
|
7
|
+
it since.
|
|
8
|
+
|
|
9
|
+
So the copy carries its provenance in a Jinja comment on the first line, in one
|
|
10
|
+
of two shapes:
|
|
11
|
+
|
|
12
|
+
{# fjkit:eject button 0.2.1 sha256:6b1f0c9a2d34 #}
|
|
13
|
+
{# fjkit:eject data 0.2.1 macros:badge=1f0c9a2d3456 #}
|
|
14
|
+
|
|
15
|
+
The first is a copy of the whole file; the second owns the macros it names and
|
|
16
|
+
re-exports the rest from the kit (see `fjkit.cli.eject`). `name` is the
|
|
17
|
+
component, the version records when, and each digest is the kit's source at that
|
|
18
|
+
moment. The digest makes staleness detectable: compare it against the installed
|
|
19
|
+
kit, and a difference means upstream moved. Comparing versions instead would
|
|
20
|
+
report a false positive on every release, since most releases touch no component
|
|
21
|
+
the app has ejected.
|
|
22
|
+
|
|
23
|
+
Per macro, not per file, which is the point of the second shape. A file-wide
|
|
24
|
+
digest marks a copy of `badge` stale because the kit changed `avatar` — noise
|
|
25
|
+
that trains the reader to ignore the alert. The report can instead name `badge`,
|
|
26
|
+
a macro the app owns.
|
|
27
|
+
|
|
28
|
+
A macro's digest covers its `{% macro %}` block and not the signature comment
|
|
29
|
+
above it: rewording a paragraph should not report the copy as behind.
|
|
30
|
+
|
|
31
|
+
Never an error. Ejecting is a supported escape hatch and diverging is its
|
|
32
|
+
purpose. `fjkit check` reports these as a note beside the violation list and
|
|
33
|
+
leaves the exit code alone.
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
from __future__ import annotations
|
|
37
|
+
|
|
38
|
+
import hashlib
|
|
39
|
+
import re
|
|
40
|
+
from dataclasses import dataclass
|
|
41
|
+
from pathlib import Path
|
|
42
|
+
|
|
43
|
+
from fjkit.config import TEMPLATE_DIR
|
|
44
|
+
|
|
45
|
+
#: The first line of an ejected file. `[^\S\n]` rather than `\s` so the line
|
|
46
|
+
#: cannot swallow the newline and match into the template body.
|
|
47
|
+
STAMP = re.compile(
|
|
48
|
+
r"\{#[^\S\n]*fjkit:eject[^\S\n]+(?P<name>[\w-]+)[^\S\n]+(?P<version>\S+)[^\S\n]+"
|
|
49
|
+
r"(?:sha256:(?P<digest>[0-9a-f]+)"
|
|
50
|
+
r"|macros:(?P<macros>[\w-]+=[0-9a-f]+(?:,[\w-]+=[0-9a-f]+)*))"
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
#: Long enough to identify a revision, short enough to read in a diff.
|
|
54
|
+
#: Collisions need 2^24 component revisions before they matter.
|
|
55
|
+
DIGEST_LENGTH = 12
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def digest(source: str) -> str:
|
|
59
|
+
"""Fingerprint a component's source for the stamp.
|
|
60
|
+
|
|
61
|
+
Newlines are normalised because the stamp travels through git: without it, a
|
|
62
|
+
checkout with `core.autocrlf` on reports every component as changed.
|
|
63
|
+
"""
|
|
64
|
+
return hashlib.sha256(source.replace("\r\n", "\n").encode("utf-8")).hexdigest()[:DIGEST_LENGTH]
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def kit_source(name: str) -> str | None:
|
|
68
|
+
"""Read the kit's own version of a component, or None if it ships no such
|
|
69
|
+
name."""
|
|
70
|
+
path = TEMPLATE_DIR / "ui" / f"{name}.html"
|
|
71
|
+
return path.read_text(encoding="utf-8") if path.exists() else None
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def stamp_line(name: str, version: str, source: str) -> str:
|
|
75
|
+
"""Build the stamp for a copy of the whole file."""
|
|
76
|
+
return f"{{# fjkit:eject {name} {version} sha256:{digest(source)} #}}\n"
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def macro_stamp(name: str, version: str, digests: dict[str, str]) -> str:
|
|
80
|
+
"""Build the stamp for an override that owns some of a component's macros."""
|
|
81
|
+
listing = ",".join(f"{macro}={value}" for macro, value in digests.items())
|
|
82
|
+
return f"{{# fjkit:eject {name} {version} macros:{listing} #}}\n"
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
@dataclass(frozen=True, slots=True)
|
|
86
|
+
class Ejected:
|
|
87
|
+
"""One ejected component found in an app's template directory."""
|
|
88
|
+
|
|
89
|
+
path: Path
|
|
90
|
+
name: str
|
|
91
|
+
version: str
|
|
92
|
+
#: What this copy owns: macro name → the kit's digest when it was taken. A
|
|
93
|
+
#: whole-file copy holds one pseudo-entry named after the component, because
|
|
94
|
+
#: it took the imports and the lookup tables as well as the macros.
|
|
95
|
+
owned: tuple[tuple[str, str], ...]
|
|
96
|
+
#: The same names' digests in the installed kit now. A name missing here is
|
|
97
|
+
#: one the kit no longer ships.
|
|
98
|
+
current: tuple[tuple[str, str], ...]
|
|
99
|
+
#: False when the copy owns named macros rather than the file.
|
|
100
|
+
whole_file: bool
|
|
101
|
+
|
|
102
|
+
@property
|
|
103
|
+
def digest(self) -> str:
|
|
104
|
+
"""The stamped digest of a whole-file copy."""
|
|
105
|
+
return self.owned[0][1]
|
|
106
|
+
|
|
107
|
+
@property
|
|
108
|
+
def moved(self) -> tuple[str, ...]:
|
|
109
|
+
"""The owned macros the kit has changed since the eject."""
|
|
110
|
+
now = dict(self.current)
|
|
111
|
+
return tuple(name for name, was in self.owned if name in now and now[name] != was)
|
|
112
|
+
|
|
113
|
+
@property
|
|
114
|
+
def missing(self) -> tuple[str, ...]:
|
|
115
|
+
"""The owned macros the kit no longer ships."""
|
|
116
|
+
now = dict(self.current)
|
|
117
|
+
return tuple(name for name, _ in self.owned if name not in now)
|
|
118
|
+
|
|
119
|
+
@property
|
|
120
|
+
def is_stale(self) -> bool:
|
|
121
|
+
return bool(self.moved)
|
|
122
|
+
|
|
123
|
+
@property
|
|
124
|
+
def is_orphaned(self) -> bool:
|
|
125
|
+
return bool(self.missing)
|
|
126
|
+
|
|
127
|
+
def render(self, root: Path) -> str:
|
|
128
|
+
rel = self.path.relative_to(root).as_posix()
|
|
129
|
+
if self.whole_file:
|
|
130
|
+
if self.is_orphaned:
|
|
131
|
+
return (
|
|
132
|
+
f" {rel}\n ejected from fjkit {self.version}, which no longer ships "
|
|
133
|
+
f"a {self.name!r} component"
|
|
134
|
+
)
|
|
135
|
+
return (
|
|
136
|
+
f" {rel}\n"
|
|
137
|
+
f" ejected from fjkit {self.version}; the kit's {self.name!r} has changed since\n"
|
|
138
|
+
f" re-eject into a scratch file and diff, or delete this copy to go back to the kit's"
|
|
139
|
+
)
|
|
140
|
+
lines = [f" {rel}"]
|
|
141
|
+
if self.missing:
|
|
142
|
+
lines.append(
|
|
143
|
+
f" ejected from fjkit {self.version}, which no longer ships "
|
|
144
|
+
f"{_names(self.missing)} in {self.name!r}"
|
|
145
|
+
)
|
|
146
|
+
if self.moved:
|
|
147
|
+
lines.append(
|
|
148
|
+
f" ejected from fjkit {self.version}; the kit has since changed "
|
|
149
|
+
f"{_names(self.moved)}, and you own a copy\n"
|
|
150
|
+
f" re-eject into a scratch directory and diff that macro, or delete your copy of it"
|
|
151
|
+
)
|
|
152
|
+
return "\n".join(lines)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _names(names: tuple[str, ...]) -> str:
|
|
156
|
+
return ", ".join(repr(n) for n in names)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def find_ejected(template_dir: Path) -> list[Ejected]:
|
|
160
|
+
"""Collect every stamped copy under `template_dir`, in file order.
|
|
161
|
+
|
|
162
|
+
Only the first line is read. A stamp anywhere else is not a stamp: `eject`
|
|
163
|
+
writes it at the top, and scanning the whole file would match a stamp quoted
|
|
164
|
+
inside documentation about this feature.
|
|
165
|
+
"""
|
|
166
|
+
from fjkit.cli.eject import kit_macro_digests
|
|
167
|
+
|
|
168
|
+
found: list[Ejected] = []
|
|
169
|
+
for path in sorted(template_dir.rglob("*.html")):
|
|
170
|
+
with path.open(encoding="utf-8") as handle:
|
|
171
|
+
first = handle.readline()
|
|
172
|
+
match = STAMP.match(first.strip())
|
|
173
|
+
if match is None:
|
|
174
|
+
continue
|
|
175
|
+
name = match["name"]
|
|
176
|
+
|
|
177
|
+
if match["macros"]:
|
|
178
|
+
owned = tuple(tuple(entry.split("=", 1)) for entry in match["macros"].split(","))
|
|
179
|
+
current = tuple(sorted(kit_macro_digests(name, [m for m, _ in owned]).items()))
|
|
180
|
+
whole_file = False
|
|
181
|
+
else:
|
|
182
|
+
source = kit_source(name)
|
|
183
|
+
owned = ((name, match["digest"]),)
|
|
184
|
+
current = () if source is None else ((name, digest(source)),)
|
|
185
|
+
whole_file = True
|
|
186
|
+
|
|
187
|
+
found.append(
|
|
188
|
+
Ejected(
|
|
189
|
+
path=path,
|
|
190
|
+
name=name,
|
|
191
|
+
version=match["version"],
|
|
192
|
+
owned=owned, # type: ignore[arg-type]
|
|
193
|
+
current=current,
|
|
194
|
+
whole_file=whole_file,
|
|
195
|
+
)
|
|
196
|
+
)
|
|
197
|
+
return found
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def stale_ejects(template_dir: Path) -> list[Ejected]:
|
|
201
|
+
"""The ejects worth telling the app author about."""
|
|
202
|
+
return [e for e in find_ejected(template_dir) if e.is_stale or e.is_orphaned]
|
fjkit/cli/vocabulary.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""What classes an app is allowed to write.
|
|
2
|
+
|
|
3
|
+
There is no hand-maintained whitelist. The component vocabulary is derived from
|
|
4
|
+
the CSS that ships, so it cannot drift from reality and nobody has to update it
|
|
5
|
+
when a component lands.
|
|
6
|
+
|
|
7
|
+
Two sets matter:
|
|
8
|
+
|
|
9
|
+
* **Component classes** — `btn`, `card`, `badge`, `table`, `input`, … the public
|
|
10
|
+
vocabulary, harvested from Basecoat's component stylesheets and fjkit's own
|
|
11
|
+
component layer.
|
|
12
|
+
* **Everything else** — utility classes (`flex`, `gap-4`, `text-muted-
|
|
13
|
+
foreground`) and classes that do not exist at all.
|
|
14
|
+
|
|
15
|
+
App templates are refused utilities even though they work today. An app leaning
|
|
16
|
+
on `gap-4` because fjkit's shell emits it breaks silently the day the shell
|
|
17
|
+
stops emitting it. A class you did not put in the stylesheet is not yours to
|
|
18
|
+
depend on.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import re
|
|
24
|
+
from functools import cache
|
|
25
|
+
|
|
26
|
+
from fjkit.config import STATIC_DIR
|
|
27
|
+
from fjkit.vendored import DEFAULT_STYLE, STYLE_PACKS
|
|
28
|
+
|
|
29
|
+
#: `@apply flex gap-4;` inside a component definition names utilities, not
|
|
30
|
+
#: component classes. Strip those lines before harvesting.
|
|
31
|
+
_APPLY = re.compile(r"@apply[^;]*;")
|
|
32
|
+
_CLASS_SELECTOR = re.compile(r"\.(-?[A-Za-z_][\w-]*)")
|
|
33
|
+
|
|
34
|
+
#: Classes fjkit's own shell and layout macros emit that an app needs to write
|
|
35
|
+
#: itself. Kept tiny: every entry is a hole in the closed vocabulary, so adding
|
|
36
|
+
#: one should feel expensive.
|
|
37
|
+
EXTRA_ALLOWED: frozenset[str] = frozenset(
|
|
38
|
+
{
|
|
39
|
+
# Set by the shell's flash-guard script and read by Basecoat's dark
|
|
40
|
+
# variant. An app that renders its own <html> needs it.
|
|
41
|
+
"dark",
|
|
42
|
+
}
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@cache
|
|
47
|
+
def component_classes() -> frozenset[str]:
|
|
48
|
+
"""Collect every class name Basecoat and fjkit define as a component."""
|
|
49
|
+
names: set[str] = set(EXTRA_ALLOWED)
|
|
50
|
+
|
|
51
|
+
sources = [
|
|
52
|
+
*(STATIC_DIR / "vendor" / "basecoat" / "components").glob("*.css"),
|
|
53
|
+
*(STATIC_DIR / "vendor" / "basecoat" / "base").glob("*.css"),
|
|
54
|
+
STATIC_DIR / "src" / "fjkit.css",
|
|
55
|
+
]
|
|
56
|
+
for path in sources:
|
|
57
|
+
if not path.exists():
|
|
58
|
+
continue
|
|
59
|
+
names.update(_CLASS_SELECTOR.findall(_APPLY.sub("", path.read_text(encoding="utf-8"))))
|
|
60
|
+
|
|
61
|
+
return frozenset(names)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@cache
|
|
65
|
+
def emitted_classes() -> frozenset[str]:
|
|
66
|
+
"""Collect every class present in the built stylesheet.
|
|
67
|
+
|
|
68
|
+
Used only to tell two failures apart: a utility that exists, where the
|
|
69
|
+
message says to use a macro, from a name that exists nowhere, a typo. Before
|
|
70
|
+
the stylesheet is built, everything unknown is reported as a typo, which is
|
|
71
|
+
still actionable.
|
|
72
|
+
"""
|
|
73
|
+
# Any pack will do: the packs differ in declarations, not in which utilities
|
|
74
|
+
# Tailwind emitted, and this set only separates a utility from a typo. The
|
|
75
|
+
# default comes first, so the answer is stable when several are built.
|
|
76
|
+
built = next(
|
|
77
|
+
(p for p in (STATIC_DIR / "dist" / f"fjkit-{s}.css" for s in (DEFAULT_STYLE, *STYLE_PACKS)) if p.exists()),
|
|
78
|
+
None,
|
|
79
|
+
)
|
|
80
|
+
if built is None:
|
|
81
|
+
return frozenset()
|
|
82
|
+
# Escaped selectors in built Tailwind look like `.sm\:grid-cols-2`; the
|
|
83
|
+
# backslashes carry nothing this function needs.
|
|
84
|
+
text = built.read_text(encoding="utf-8").replace("\\", "")
|
|
85
|
+
return frozenset(_CLASS_SELECTOR.findall(text))
|
fjkit/config.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
"""Configuration for the kit.
|
|
2
|
+
|
|
3
|
+
A plain dataclass rather than `pydantic_settings.BaseSettings`, so the kit
|
|
4
|
+
imposes neither a settings framework nor an environment-variable prefix on the
|
|
5
|
+
apps that use it. An app that already uses pydantic-settings maps its own
|
|
6
|
+
settings onto this one.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from collections.abc import Callable
|
|
12
|
+
from dataclasses import dataclass, field
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import TYPE_CHECKING, Literal
|
|
15
|
+
|
|
16
|
+
from fjkit.vendored import StylePack
|
|
17
|
+
|
|
18
|
+
if TYPE_CHECKING:
|
|
19
|
+
from fastapi import Request
|
|
20
|
+
|
|
21
|
+
from fjkit.messages import Message
|
|
22
|
+
from fjkit.plugins import Plugin
|
|
23
|
+
|
|
24
|
+
#: What the user is told when `catch_unexpected_errors` catches something:
|
|
25
|
+
#: one fixed `Message`, or a callable taking the request and the exception
|
|
26
|
+
#: and returning the `Message` for it — so an app can word a `TimeoutError`
|
|
27
|
+
#: differently from a `KeyError`. Use the exception to choose the words;
|
|
28
|
+
#: putting `str(exc)` in them shows a visitor the inside of the app.
|
|
29
|
+
UnexpectedErrorMessage = Message | Callable[[Request, Exception], Message]
|
|
30
|
+
|
|
31
|
+
PACKAGE_DIR = Path(__file__).resolve().parent
|
|
32
|
+
TEMPLATE_DIR = PACKAGE_DIR / "templates"
|
|
33
|
+
STATIC_DIR = PACKAGE_DIR / "static"
|
|
34
|
+
|
|
35
|
+
#: What an `@render` route puts on the wire. `"html"` renders the template;
|
|
36
|
+
#: `"json"` hands the handler's return value back to FastAPI, which serialises
|
|
37
|
+
#: it through the route's `response_model`; `"auto"` renders whenever there is
|
|
38
|
+
#: markup to render for this caller and falls back to JSON when there is not.
|
|
39
|
+
RenderMode = Literal["html", "json", "auto"]
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(frozen=True, slots=True)
|
|
43
|
+
class FjkitConfig:
|
|
44
|
+
"""Everything tunable, in one object.
|
|
45
|
+
|
|
46
|
+
The defaults suit development. `for_production()` turns `auto_reload` and
|
|
47
|
+
`strict_undefined` off and `catch_unexpected_errors` on.
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
#: Where the app's own templates live. Searched before the kit's, so an app
|
|
51
|
+
#: shadows `ui/button.html` by dropping a file at the same path. That is the
|
|
52
|
+
#: mechanism behind `fjkit eject` (CHARTER.md A5).
|
|
53
|
+
template_dir: Path | None = None
|
|
54
|
+
|
|
55
|
+
#: URL prefix the kit's stylesheet and vendored JS are served from. Both
|
|
56
|
+
#: `mount_fjkit()` and the shell template read this, so they cannot disagree.
|
|
57
|
+
static_url: str = "/_fjkit"
|
|
58
|
+
|
|
59
|
+
#: Which Basecoat style pack the shell loads. All eight ship in the wheel
|
|
60
|
+
#: already built, so switching is a one-word change and a restart — no
|
|
61
|
+
#: Tailwind, no reinstall, and no template edit, because a pack changes
|
|
62
|
+
#: geometry (control heights, radii, borders, shadows) and never the class
|
|
63
|
+
#: names or tokens a template writes.
|
|
64
|
+
#:
|
|
65
|
+
#: `"auto"` is the default pack, so an app that never heard of style packs
|
|
66
|
+
#: keeps the stylesheet it always had. See `fjkit.styles`.
|
|
67
|
+
#:
|
|
68
|
+
#: Deliberately not a per-request value. Two packs on one page would send
|
|
69
|
+
#: two full stylesheets over the wire and let one silently lose the cascade,
|
|
70
|
+
#: so the app makes the choice once.
|
|
71
|
+
style: StylePack | Literal["auto"] = "auto"
|
|
72
|
+
|
|
73
|
+
#: Stats every template file on every render. Cheap per call, but the
|
|
74
|
+
#: syscalls sit on the hot path and buy nothing once the files cannot change.
|
|
75
|
+
auto_reload: bool = True
|
|
76
|
+
|
|
77
|
+
#: Compiled templates cached as Python bytecode on disk, so a fresh worker
|
|
78
|
+
#: skips parse+compile. Matters for cold starts and autoscaling.
|
|
79
|
+
bytecode_cache_dir: Path | None = None
|
|
80
|
+
|
|
81
|
+
#: In-memory LRU of compiled template objects. Jinja's default, already
|
|
82
|
+
#: larger than most apps' template count — sized so nothing is evicted.
|
|
83
|
+
cache_size: int = 400
|
|
84
|
+
|
|
85
|
+
#: Raises on a typo'd variable instead of rendering an empty string. Slower,
|
|
86
|
+
#: and it can 500 a page: on in development, off in production.
|
|
87
|
+
strict_undefined: bool = True
|
|
88
|
+
|
|
89
|
+
#: Whether an unhandled exception becomes a toast and an error page rather
|
|
90
|
+
#: than a traceback. Off by default, and that default is the useful one: in
|
|
91
|
+
#: development a traceback in the terminal beats a tidy apology in the
|
|
92
|
+
#: browser, and a handler that swallows one turns a real bug into a mystery.
|
|
93
|
+
#: `for_production()` turns it on. Validation failures (422) are handled
|
|
94
|
+
#: either way — a rejected form is not a bug.
|
|
95
|
+
catch_unexpected_errors: bool = False
|
|
96
|
+
|
|
97
|
+
#: The toast a caught exception raises, and the note on the error page's
|
|
98
|
+
#: toaster after a navigation. `None` uses the kit's own wording —
|
|
99
|
+
#: "Something went wrong", with a text saying nothing was saved. A `Message`
|
|
100
|
+
#: changes the words once; a callable `(request, exc) -> Message` picks them
|
|
101
|
+
#: per exception. Read only when `catch_unexpected_errors` is on. The
|
|
102
|
+
#: traceback is logged either way; this decides the sentence, not the
|
|
103
|
+
#: logging.
|
|
104
|
+
unexpected_error: UnexpectedErrorMessage | None = None
|
|
105
|
+
|
|
106
|
+
#: Extra values exposed to every template. Prefer this over threading the
|
|
107
|
+
#: same key through every route's context dict.
|
|
108
|
+
globals: dict[str, object] = field(default_factory=dict)
|
|
109
|
+
|
|
110
|
+
#: Extensions, applied in this order. A plugin can add middleware, an
|
|
111
|
+
#: exception handler, a template directory, or a value that every template
|
|
112
|
+
#: gets — see `fjkit.plugins`. Order matters twice: template directories are
|
|
113
|
+
#: searched in it, and Starlette runs middleware in reverse of it, so a
|
|
114
|
+
#: plugin listed later wraps the ones before it.
|
|
115
|
+
plugins: tuple[Plugin, ...] = ()
|
|
116
|
+
|
|
117
|
+
#: Default representation for every `@render` route; a single decorator
|
|
118
|
+
#: overrides it with `mode=`. `"auto"` gives a page to whoever navigates to
|
|
119
|
+
#: one and the fragment to whoever swaps it, and answers everybody else with
|
|
120
|
+
#: the model — so the htmx endpoints are the app's API without a route
|
|
121
|
+
#: saying so. `"json"` turns every route into JSON, which is how you see
|
|
122
|
+
#: exactly what a template was handed. `"html"` serialises nothing.
|
|
123
|
+
render_mode: RenderMode = "auto"
|
|
124
|
+
|
|
125
|
+
def for_production(self) -> FjkitConfig:
|
|
126
|
+
"""Return the same config with `auto_reload` and `strict_undefined` off
|
|
127
|
+
and `catch_unexpected_errors` on."""
|
|
128
|
+
from dataclasses import replace
|
|
129
|
+
|
|
130
|
+
return replace(self, auto_reload=False, strict_undefined=False, catch_unexpected_errors=True)
|
fjkit/errors.py
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
"""Exception handlers `mount_fjkit` installs for every route.
|
|
2
|
+
|
|
3
|
+
422 FastAPI refused the input
|
|
4
|
+
500 anything else that escaped (only with `catch_unexpected_errors`;
|
|
5
|
+
the words are `FjkitConfig.unexpected_error`)
|
|
6
|
+
|
|
7
|
+
What each caller gets:
|
|
8
|
+
|
|
9
|
+
htmx swap FastAPI's 422 as it is; `static/js/errors.js` draws it
|
|
10
|
+
under the fields of the form still on the page
|
|
11
|
+
navigation `errors/page.html`, rendered through the app's shell
|
|
12
|
+
JSON client FastAPI's own reply, untouched
|
|
13
|
+
|
|
14
|
+
A pydantic `ValidationError` raised inside a handler is not caught: it is the
|
|
15
|
+
shape of a bug, not of a rejected form. Declare the model in the signature.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import logging
|
|
21
|
+
from typing import TYPE_CHECKING, Any
|
|
22
|
+
|
|
23
|
+
from fastapi import FastAPI, Request, Response
|
|
24
|
+
from fastapi.exception_handlers import (
|
|
25
|
+
request_validation_exception_handler as _fastapi_validation_reply,
|
|
26
|
+
)
|
|
27
|
+
from fastapi.exceptions import RequestValidationError
|
|
28
|
+
|
|
29
|
+
from fjkit import htmx, messages
|
|
30
|
+
from fjkit.forms import FieldErrors, field_errors
|
|
31
|
+
|
|
32
|
+
if TYPE_CHECKING:
|
|
33
|
+
from fjkit.config import FjkitConfig
|
|
34
|
+
|
|
35
|
+
__all__ = ["ERROR_TEMPLATE", "install_error_handlers"]
|
|
36
|
+
|
|
37
|
+
#: The page a failed navigation lands on. An app replaces it with a file at the
|
|
38
|
+
#: same path in its own template directory — the shadowing that makes `fjkit
|
|
39
|
+
#: eject` work, so there is no separate "custom error page" mechanism to learn.
|
|
40
|
+
ERROR_TEMPLATE = "errors/page.html"
|
|
41
|
+
|
|
42
|
+
_log = logging.getLogger("fjkit.errors")
|
|
43
|
+
|
|
44
|
+
#: Addressed to the user, not the developer. A 500 means the app is in a state
|
|
45
|
+
#: nobody predicted, so the honest thing to show is that something broke and
|
|
46
|
+
#: nothing about what. An app changes the words with
|
|
47
|
+
#: `FjkitConfig.unexpected_error`.
|
|
48
|
+
_UNEXPECTED = messages.Message(
|
|
49
|
+
"Something went wrong", "The action was not completed. Nothing was saved.", category="error"
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def install_error_handlers(app: FastAPI, config: FjkitConfig) -> None:
|
|
54
|
+
"""Install the 422 handler, and the 500 handler when
|
|
55
|
+
`catch_unexpected_errors` is on. Called by `mount_fjkit`."""
|
|
56
|
+
app.add_exception_handler(RequestValidationError, _on_request_validation)
|
|
57
|
+
if config.catch_unexpected_errors:
|
|
58
|
+
choose = config.unexpected_error
|
|
59
|
+
|
|
60
|
+
async def on_unexpected(request: Request, exc: Exception) -> Response:
|
|
61
|
+
return await _on_unexpected(request, exc, _message_for(choose, request, exc))
|
|
62
|
+
|
|
63
|
+
app.add_exception_handler(Exception, on_unexpected)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _message_for(choose: Any, request: Request, exc: Exception) -> messages.Message:
|
|
67
|
+
"""Choose the words for this failure.
|
|
68
|
+
|
|
69
|
+
A `choose` callable that itself raises is logged and falls back to the kit's
|
|
70
|
+
own wording: the handler it runs inside is the last one there is."""
|
|
71
|
+
if choose is None:
|
|
72
|
+
return _UNEXPECTED
|
|
73
|
+
if callable(choose):
|
|
74
|
+
try:
|
|
75
|
+
return choose(request, exc)
|
|
76
|
+
except Exception: # noqa: BLE001 — see docstring
|
|
77
|
+
_log.exception("FjkitConfig.unexpected_error raised; using the default message")
|
|
78
|
+
return _UNEXPECTED
|
|
79
|
+
return choose
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
# --------------------------------------------------------------------------- #
|
|
83
|
+
# 422 — a form was rejected
|
|
84
|
+
# --------------------------------------------------------------------------- #
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
async def _on_request_validation(request: Request, exc: Exception) -> Response:
|
|
88
|
+
"""Answer a rejected input: FastAPI's reply unchanged for a swap or a JSON
|
|
89
|
+
client, `ERROR_TEMPLATE` for a navigation."""
|
|
90
|
+
if htmx.is_swap(request) or not _wants_markup(request, _plan_for(request)):
|
|
91
|
+
return await _fastapi_validation_reply(request, exc)
|
|
92
|
+
return _error_page(request, status_code=422, errors=field_errors(exc, request_scoped=True))
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
# --------------------------------------------------------------------------- #
|
|
96
|
+
# 500 — something else entirely
|
|
97
|
+
# --------------------------------------------------------------------------- #
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
async def _on_unexpected(request: Request, exc: Exception, message: messages.Message) -> Response:
|
|
101
|
+
"""Log the exception in full and show `message` to the user."""
|
|
102
|
+
_log.exception("unhandled error on %s %s", request.method, request.url.path, exc_info=exc)
|
|
103
|
+
|
|
104
|
+
if not _wants_markup(request, _plan_for(request)):
|
|
105
|
+
# This caller was not reading a page, so hand back Starlette's own
|
|
106
|
+
# answer. Not a re-raise: raising inside `ServerErrorMiddleware`'s
|
|
107
|
+
# handler replaces the original traceback with one from this line.
|
|
108
|
+
return Response("Internal Server Error", status_code=500, media_type="text/plain")
|
|
109
|
+
|
|
110
|
+
messages.extend(request, (message,))
|
|
111
|
+
if htmx.is_swap(request):
|
|
112
|
+
# The reply carries no markup, so htmx must not swap an empty body into
|
|
113
|
+
# the target. The toast rides the header instead, which htmx reads
|
|
114
|
+
# before it decides on swapping at all.
|
|
115
|
+
response = Response(status_code=500)
|
|
116
|
+
trigger = messages.trigger_header(request, None)
|
|
117
|
+
if trigger is not None:
|
|
118
|
+
response.headers["HX-Trigger"] = trigger
|
|
119
|
+
return response
|
|
120
|
+
return _error_page(request, status_code=500, errors=None)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
# --------------------------------------------------------------------------- #
|
|
124
|
+
# shared
|
|
125
|
+
# --------------------------------------------------------------------------- #
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _error_page(request: Request, *, status_code: int, errors: FieldErrors | None) -> Response:
|
|
129
|
+
"""Render `ERROR_TEMPLATE` through the app's own `Templates`, falling back
|
|
130
|
+
to plain text when that render fails too."""
|
|
131
|
+
templates = getattr(request.app.state, "templates", None)
|
|
132
|
+
if templates is None: # pragma: no cover — mount_fjkit always sets it
|
|
133
|
+
return Response(_UNEXPECTED.title, status_code=status_code, media_type="text/plain")
|
|
134
|
+
context = {"status_code": status_code, "errors": errors}
|
|
135
|
+
try:
|
|
136
|
+
return templates.page(request, ERROR_TEMPLATE, context, status_code=status_code)
|
|
137
|
+
except Exception: # noqa: BLE001 — the last line of defence, deliberately broad
|
|
138
|
+
_log.exception("fjkit could not render %s", ERROR_TEMPLATE)
|
|
139
|
+
return Response(_UNEXPECTED.title, status_code=status_code, media_type="text/plain")
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _wants_markup(request: Request, plan: Any) -> bool:
|
|
143
|
+
"""True for htmx, for a route whose `@render` serves a page, or for an
|
|
144
|
+
`Accept` that names HTML (a route with no `@render` at all)."""
|
|
145
|
+
if htmx.is_htmx(request):
|
|
146
|
+
return True
|
|
147
|
+
if plan is not None and getattr(plan, "serves_a_page", False):
|
|
148
|
+
return True
|
|
149
|
+
accept = request.headers.get("accept", "")
|
|
150
|
+
return "text/html" in accept or "application/xhtml+xml" in accept
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _plan_for(request: Request) -> Any:
|
|
154
|
+
"""The `@render` plan stamped on the route's endpoint, if any."""
|
|
155
|
+
route = request.scope.get("route")
|
|
156
|
+
return getattr(getattr(route, "endpoint", None), "__fjkit_plan__", None)
|