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/cli/eject.py ADDED
@@ -0,0 +1,562 @@
1
+ """`fjkit eject` — take one macro out of the kit's reach, and only one.
2
+
3
+ A component template is a file of macros: `ui/data.html` holds fifteen. The
4
+ loader searches the app's directory first (CHARTER.md A5), so a file the app
5
+ writes at `ui/data.html` shadows the kit's and every call site keeps working.
6
+ That is the escape hatch. Copying the whole file used to be the only way to walk
7
+ it, so changing `badge` silently cost the other fourteen macros' upstream fixes,
8
+ permanently.
9
+
10
+ So the file an eject writes owns only what was asked for, and re-exports the
11
+ rest:
12
+
13
+ {# fjkit:eject data 0.2.1 macros:badge=1f0c9a2d3456 #}
14
+ {% import "fjkit/ui/data.html" as _fjkit %}
15
+ …
16
+ {% set card = _fjkit.card %}
17
+ {% macro badge(label, variant="default") %}…your version…{% endmacro %}
18
+ {% set stat = _fjkit.stat %}
19
+ …
20
+
21
+ `{% set card = _fjkit.card %}` binds the kit's macro object under the name the
22
+ module exports, so `{% from "ui/data.html" import card %}` at a call site still
23
+ reaches the kit's implementation, including through `{% call %}` blocks and
24
+ `**kwargs`, because it is the same object rather than a wrapper. When the kit
25
+ fixes `card`, the app gets the fix on its next upgrade. Only the macro taken
26
+ diverges.
27
+
28
+ Three details make it work.
29
+
30
+ **The reserved namespace.** The override is `ui/data.html`, so it cannot import
31
+ `ui/data.html` to reach what it shadows. `fjkit/ui/data.html` is a second name
32
+ for the package's own copy that nothing can shadow — see
33
+ `fjkit.templating._ReservedNamespace`.
34
+
35
+ **Private macros are copied, not borrowed.** Jinja keeps a name starting with
36
+ `_` out of a module's namespace, so `_fjkit._message` does not exist, and a
37
+ macro that calls one takes a copy. Across the kit that is one macro,
38
+ `form.html`'s `_message`. Dropping the underscore would fix the tooling by
39
+ promoting an implementation detail to public API, which is the wrong trade.
40
+
41
+ **Source order is preserved.** Every kept statement — the imports, the lookup
42
+ tables, the macros — appears where it did upstream, with a one-line re-export
43
+ standing in for each macro not taken. A diff against the kit's file then shows
44
+ only what changed.
45
+
46
+ Measured on the kit's worst case: `eject text_field` writes 81 lines against
47
+ `form.html`'s 327, seventeen of them the header explaining itself, and the app
48
+ diverges from upstream on two of twelve macros instead of all twelve.
49
+ """
50
+
51
+ from __future__ import annotations
52
+
53
+ import sys
54
+ from dataclasses import dataclass
55
+ from functools import cache
56
+ from pathlib import Path
57
+
58
+ from jinja2 import Environment, nodes
59
+
60
+ # `ejected` reaches back the other way for `kit_macro_digests`, but only from
61
+ # inside a function, so this stays one-directional at module level.
62
+ from fjkit.cli.ejected import STAMP, digest, macro_stamp, stamp_line
63
+ from fjkit.config import TEMPLATE_DIR
64
+
65
+ #: Where components live, inside the kit and inside an app's template dir alike.
66
+ UI = "ui"
67
+
68
+
69
+ @dataclass(frozen=True, slots=True)
70
+ class Macro:
71
+ """One `{% macro %}` in a component file, with the lines it occupies."""
72
+
73
+ name: str
74
+ #: `{% macro … %}` … `{% endmacro %}`, verbatim.
75
+ body: str
76
+ #: The `{# … #}` block directly above it — the signature contract. Carried
77
+ #: along on an eject, and kept out of the digest: a reworded paragraph
78
+ #: should not report the copy as behind.
79
+ doc: str
80
+ #: Every name its body reads, locals and parameters included. Those match
81
+ #: nothing the file binds at the top level, so they cost nothing.
82
+ uses: frozenset[str]
83
+
84
+ @property
85
+ def is_private(self) -> bool:
86
+ """Jinja keeps `_`-prefixed names out of the module namespace, so this
87
+ macro cannot be re-exported and has to be copied."""
88
+ return self.name.startswith("_")
89
+
90
+
91
+ @dataclass(frozen=True, slots=True)
92
+ class Statement:
93
+ """A top-level `{% from %}`, `{% import %}` or `{% set %}` — the imports and
94
+ the closed lookup tables a component's macros read."""
95
+
96
+ #: Verbatim, all of its lines. `{% set _ROWS = { … } %}` spans seven, which
97
+ #: is why a tag's end is found by pairing and not by `lineno`.
98
+ text: str
99
+ #: The `{# … #}` block directly above. A lookup table's comment is often the
100
+ #: signature contract of the macro that reads it: `field_row`'s explanation
101
+ #: of why `template` is a key and not a raw grid string sits above `_ROWS`,
102
+ #: not above the macro.
103
+ doc: str
104
+ binds: frozenset[str]
105
+ uses: frozenset[str]
106
+
107
+
108
+ @dataclass(frozen=True, slots=True)
109
+ class Component:
110
+ """One `ui/*.html`, taken apart far enough to rebuild a subset of it."""
111
+
112
+ name: str
113
+ path: Path
114
+ source: str
115
+ #: Every top-level statement in source order, macros and the rest mixed,
116
+ #: because the override reproduces that order and a diff against the kit's
117
+ #: file then shows only what changed.
118
+ items: tuple[Macro | Statement, ...]
119
+ macros: dict[str, Macro]
120
+
121
+ @property
122
+ def template(self) -> str:
123
+ return f"{UI}/{self.name}.html"
124
+
125
+ def closure(self, name: str) -> list[str]:
126
+ """List `name` plus every private macro it needs, transitively.
127
+
128
+ Public siblings are left out because they are re-exported: an owned
129
+ macro calling one still calls the kit's.
130
+ """
131
+ taken: list[str] = []
132
+ pending = [name]
133
+ while pending:
134
+ current = pending.pop(0)
135
+ if current in taken:
136
+ continue
137
+ taken.append(current)
138
+ macro = self.macros[current]
139
+ pending.extend(n for n in sorted(macro.uses) if n in self.macros and self.macros[n].is_private)
140
+ return taken
141
+
142
+ def needed_statements(self, owned: list[str]) -> set[int]:
143
+ """Select the imports and lookup tables the owned macros read.
144
+
145
+ Copying all of them is simpler, and wrong: `_ROWS` copied beside a
146
+ `text_field` that never reads it falls silently behind the kit's, while
147
+ the macro that does read it — re-exported `field_row` — goes on using
148
+ the kit's. Dead weight that looks live.
149
+ """
150
+ statements = {i: item for i, item in enumerate(self.items) if isinstance(item, Statement)}
151
+ wanted: set[str] = set()
152
+ for name in owned:
153
+ wanted |= self.macros[name].uses
154
+ keep: set[int] = set()
155
+ changed = True
156
+ while changed:
157
+ changed = False
158
+ for index, statement in statements.items():
159
+ if index not in keep and statement.binds & wanted:
160
+ keep.add(index)
161
+ wanted |= statement.uses
162
+ changed = True
163
+ return keep
164
+
165
+
166
+ def _tag_ends(env: Environment, source: str) -> dict[int, int]:
167
+ """Map the first line of each `{% … %}` to the line its `%}` is on.
168
+
169
+ A tag is not a line: `{% set _ROWS = { … } %}` spans seven, and slicing on
170
+ `lineno` alone would cut a dict in half. The lexer already knows where every
171
+ tag closes, so pair the tokens rather than guess from the text.
172
+ """
173
+ ends: dict[int, int] = {}
174
+ start: int | None = None
175
+ for lineno, token, _ in env.lex(source):
176
+ if token == "block_begin":
177
+ start = lineno
178
+ elif token == "block_end" and start is not None:
179
+ ends.setdefault(start, lineno)
180
+ start = None
181
+ return ends
182
+
183
+
184
+ def _comment_ends(env: Environment, source: str) -> dict[int, int]:
185
+ """Map the last line of each `{# … #}` to the line it opened on."""
186
+ ends: dict[int, int] = {}
187
+ start: int | None = None
188
+ for lineno, token, _ in env.lex(source):
189
+ if token == "comment_begin":
190
+ start = lineno
191
+ elif token == "comment_end" and start is not None:
192
+ ends[lineno] = start
193
+ start = None
194
+ return ends
195
+
196
+
197
+ def _is_blank(node: nodes.Node) -> bool:
198
+ return isinstance(node, nodes.Output) and all(
199
+ isinstance(child, nodes.TemplateData) and not child.data.strip() for child in node.nodes
200
+ )
201
+
202
+
203
+ def _macro_end(env: Environment, source: str, ends: dict[int, int], start: int) -> int:
204
+ """Find the `{% endmacro %}` closing the macro that opens at `start`.
205
+
206
+ Counted rather than searched: Jinja allows a macro inside a macro, so the
207
+ first `{% endmacro %}` after the opening can be the wrong one.
208
+ """
209
+ depth = 0
210
+ opening: int | None = None
211
+ for lineno, token, value in env.lex(source):
212
+ if token == "block_begin":
213
+ opening = lineno
214
+ elif token == "name" and opening is not None and opening >= start:
215
+ if value == "macro":
216
+ depth += 1
217
+ elif value == "endmacro":
218
+ depth -= 1
219
+ if depth == 0:
220
+ return ends[opening]
221
+ opening = None
222
+ raise ValueError(f"unterminated {{% macro %}} at line {start}")
223
+
224
+
225
+ def parse(path: Path, env: Environment | None = None) -> Component:
226
+ """Split one component file into its statements and macros."""
227
+ env = env or _env()
228
+ source = path.read_text(encoding="utf-8")
229
+ lines = source.splitlines(keepends=True)
230
+ tag_ends = _tag_ends(env, source)
231
+ comment_ends = _comment_ends(env, source)
232
+
233
+ def slice_lines(first: int, last: int) -> str:
234
+ return "".join(lines[first - 1 : last])
235
+
236
+ def doc_above(first: int) -> str:
237
+ """Return the comment block directly above, skipping blank lines only."""
238
+ above = first - 1
239
+ while above >= 1 and not lines[above - 1].strip():
240
+ above -= 1
241
+ if above in comment_ends:
242
+ return slice_lines(comment_ends[above], above)
243
+ return ""
244
+
245
+ items: list[Macro | Statement] = []
246
+ macros: dict[str, Macro] = {}
247
+
248
+ for node in env.parse(source).body:
249
+ if _is_blank(node):
250
+ continue
251
+ if isinstance(node, nodes.Macro):
252
+ last = _macro_end(env, source, tag_ends, node.lineno)
253
+ macro = Macro(
254
+ name=node.name,
255
+ body=slice_lines(node.lineno, last),
256
+ doc=doc_above(node.lineno),
257
+ uses=frozenset(_reads(node)),
258
+ )
259
+ macros[node.name] = macro
260
+ items.append(macro)
261
+ elif isinstance(node, nodes.FromImport | nodes.Import | nodes.Assign) and node.lineno in tag_ends:
262
+ items.append(
263
+ Statement(
264
+ text=slice_lines(node.lineno, tag_ends[node.lineno]),
265
+ doc=doc_above(node.lineno),
266
+ binds=frozenset(_binds(node)),
267
+ uses=frozenset(_reads(node)),
268
+ )
269
+ )
270
+ else:
271
+ # Output, {% block %} or {% if %} at the top level: `shell.html` is
272
+ # a page skeleton, not a macro library. There is no macro to take,
273
+ # so `eject shell` stays a whole-file copy and never reaches here.
274
+ raise Unsplittable(path.stem)
275
+
276
+ return Component(name=path.stem, path=path, source=source, items=tuple(items), macros=macros)
277
+
278
+
279
+ def _reads(node: nodes.Node) -> set[str]:
280
+ return {n.name for n in node.find_all(nodes.Name) if n.ctx == "load"}
281
+
282
+
283
+ def _binds(node: nodes.Node) -> set[str]:
284
+ """Collect the names a top-level statement puts into the module namespace."""
285
+ if isinstance(node, nodes.FromImport):
286
+ return {n[1] if isinstance(n, tuple) else n for n in node.names}
287
+ if isinstance(node, nodes.Import):
288
+ return {node.target}
289
+ # `find_all` walks descendants, and `{% set _ROWS = … %}`'s target is a bare
290
+ # `Name` with no descendants, so it has to be read directly.
291
+ target = node.target
292
+ if isinstance(target, nodes.Name):
293
+ return {target.name}
294
+ return {n.name for n in target.find_all(nodes.Name)}
295
+
296
+
297
+ class Unsplittable(Exception):
298
+ """A component file that is not purely a macro library."""
299
+
300
+
301
+ @cache
302
+ def _env() -> Environment:
303
+ """Build a bare Environment for parsing only.
304
+
305
+ Not `build_environment()`: parsing needs the same syntax settings, not the
306
+ loaders, the globals or a plugin's `extend` hook. `eject` runs in a CLI with
307
+ no app.
308
+ """
309
+ return Environment(trim_blocks=True, lstrip_blocks=True, autoescape=True)
310
+
311
+
312
+ @cache
313
+ def components() -> dict[str, Path]:
314
+ return {p.stem: p for p in sorted((TEMPLATE_DIR / UI).glob("*.html"))}
315
+
316
+
317
+ def resolve(name: str) -> tuple[str, str | None]:
318
+ """Turn what was typed into `(component, macro)`; macro None means the file.
319
+
320
+ `fjkit eject data` still means the whole of `data.html`: a file name wins
321
+ over a macro name, so nothing that worked before changes meaning. `fjkit
322
+ eject badge` means that one macro, found by searching every component. A
323
+ name two components both define is refused rather than guessed at, and
324
+ `data.badge` says which.
325
+ """
326
+ if "." in name:
327
+ component, _, macro = name.partition(".")
328
+ if component not in components():
329
+ raise Unknown(name)
330
+ if macro not in parse_or_none(components()[component]):
331
+ raise Unknown(name)
332
+ return component, macro
333
+
334
+ if name in components():
335
+ return name, None
336
+
337
+ holders = [component for component, path in components().items() if name in parse_or_none(path)]
338
+ if not holders:
339
+ raise Unknown(name)
340
+ if len(holders) > 1:
341
+ raise Ambiguous(name, holders)
342
+ return holders[0], name
343
+
344
+
345
+ class Unknown(Exception):
346
+ def __init__(self, name: str) -> None:
347
+ self.name = name
348
+
349
+ def __str__(self) -> str:
350
+ macros = sorted({m for p in components().values() for m in parse_or_none(p) if not m.startswith("_")})
351
+ return (
352
+ f"fjkit eject: nothing named {self.name!r}.\n"
353
+ f"Components: {', '.join(components())}\n"
354
+ f"Macros: {', '.join(macros)}"
355
+ )
356
+
357
+
358
+ class Ambiguous(Exception):
359
+ def __init__(self, name: str, holders: list[str]) -> None:
360
+ self.name = name
361
+ self.holders = holders
362
+
363
+ def __str__(self) -> str:
364
+ options = ", ".join(f"{c}.{self.name}" for c in self.holders)
365
+ return f"fjkit eject: {self.name!r} is defined by {len(self.holders)} components. Say which: {options}"
366
+
367
+
368
+ def render_override(component: Component, owned: list[str], version: str) -> str:
369
+ """Render the override: the kit's structure, holes filled by re-exports.
370
+
371
+ `owned` is every macro this copy takes — what was asked for, plus the
372
+ private helpers Jinja will not let it borrow.
373
+ """
374
+ taken = [n for n in component.macros if n in owned]
375
+ asked = [n for n in taken if not n.startswith("_")]
376
+ borrowed = [n for n in component.macros if n not in owned and not component.macros[n].is_private]
377
+ keep = component.needed_statements(taken)
378
+
379
+ parts = [
380
+ macro_stamp(component.name, version, {n: digest_of(component, n) for n in taken}),
381
+ _header(component, asked, taken, borrowed, version),
382
+ f'{{% import "fjkit/{component.template}" as _fjkit %}}\n',
383
+ ]
384
+ for index, item in enumerate(component.items):
385
+ if isinstance(item, Statement):
386
+ if index in keep:
387
+ parts.append("\n" + item.doc + item.text)
388
+ elif item.name in owned:
389
+ parts.append("\n" + item.doc + item.body)
390
+ elif not item.is_private:
391
+ parts.append(f"\n{{% set {item.name} = _fjkit.{item.name} %}}\n")
392
+ # An unowned private macro is dropped: nothing left in this file calls
393
+ # it, and the kit's own macros keep using the kit's copy.
394
+ return "".join(parts)
395
+
396
+
397
+ def _header(component: Component, asked: list[str], taken: list[str], borrowed: list[str], version: str) -> str:
398
+ copied = [n for n in taken if n not in asked]
399
+ lines = [
400
+ "{#",
401
+ f" Ejected from fjkit {version}: your copy of {_and(asked)},",
402
+ f" shadowing the kit's {component.template}. Edit {'them' if len(asked) > 1 else 'it'} freely.",
403
+ "",
404
+ f" The other {len(borrowed)} macro(s) below are re-exported from the kit, and still get",
405
+ " its fixes. Call sites do not know the difference either way —",
406
+ f' {{% from "{component.template}" import … %}} keeps working.',
407
+ "",
408
+ ]
409
+ if copied:
410
+ lines += [
411
+ f" {_and(copied)} is here as a copy rather than a re-export because Jinja",
412
+ " keeps a `_`-prefixed macro out of a module's namespace, so there is no way to",
413
+ " borrow it. The kit's own macros go on using the kit's copy, not this one.",
414
+ "",
415
+ ]
416
+ lines += [
417
+ " `fjkit check` names the macro when the kit's version of one you own moves on.",
418
+ " To take another macro, run `fjkit eject` again — it rewrites this file. To give",
419
+ " one back, delete it here and re-run. To give all of them back, delete this file.",
420
+ "#}",
421
+ "",
422
+ ]
423
+ return "\n".join(lines)
424
+
425
+
426
+ def _and(names: list[str]) -> str:
427
+ quoted = [f"`{n}`" for n in names]
428
+ if len(quoted) < 2:
429
+ return "".join(quoted)
430
+ return ", ".join(quoted[:-1]) + " and " + quoted[-1]
431
+
432
+
433
+ def digest_of(component: Component, macro: str) -> str:
434
+ """Fingerprint one of the kit's macros: the `{% macro %}` block, no doc."""
435
+ return digest(component.macros[macro].body)
436
+
437
+
438
+ def kit_macro_digests(name: str, wanted: list[str]) -> dict[str, str]:
439
+ """Hash the installed kit's versions of `wanted`, skipping any it lacks."""
440
+ path = components().get(name)
441
+ if path is None:
442
+ return {}
443
+ macros = parse_or_none(path)
444
+ return {m: digest(macros[m].body) for m in wanted if m in macros}
445
+
446
+
447
+ def main(name: str, into: Path) -> int:
448
+ """Run the `fjkit eject` command."""
449
+ try:
450
+ component_name, macro = resolve(name)
451
+ except (Unknown, Ambiguous) as exc:
452
+ print(str(exc), file=sys.stderr)
453
+ return 1
454
+
455
+ component_path = components()[component_name]
456
+ target = into / UI / f"{component_name}.html"
457
+ existing = target.read_text(encoding="utf-8") if target.exists() else None
458
+ stamp = STAMP.match(existing.splitlines()[0].strip()) if existing else None
459
+
460
+ if existing is not None and stamp is None:
461
+ print(f"fjkit eject: {target} already exists and fjkit did not write it", file=sys.stderr)
462
+ return 1
463
+
464
+ if macro is None:
465
+ if existing is not None:
466
+ print(
467
+ f"fjkit eject: {target} already exists — it is a copy of the whole component,\n"
468
+ f"so there is nothing left to take. Edit it, or delete it to go back to the kit's.",
469
+ file=sys.stderr,
470
+ )
471
+ return 1
472
+ source = component_path.read_text(encoding="utf-8")
473
+ _write(target, stamp_line(component_name, _version(), source) + source)
474
+ held = parse_or_none(component_path)
475
+ advice = (
476
+ f"All {len(held)} of its macros stop receiving upstream fixes. To take one and\n"
477
+ f"keep the rest on the kit's, delete this and run `fjkit eject <macro>` instead."
478
+ if held
479
+ else f"{component_name}.html is a page skeleton rather than a macro library, so the\n"
480
+ f"whole file is the only thing there is to take."
481
+ )
482
+ print(
483
+ f"copied the whole of {component_name}.html to {target}\n"
484
+ f"It now shadows fjkit's version — no import changes needed.\n" + advice
485
+ )
486
+ return 0
487
+
488
+ if stamp is not None and not stamp["macros"]:
489
+ # A copy of the whole file already owns this macro, along with every
490
+ # other one in it, which someone may have spent a week editing.
491
+ # Rewriting it into a one-macro override would delete that unasked.
492
+ print(
493
+ f"fjkit eject: {target} is a copy of the whole component, so it already owns\n"
494
+ f"{macro!r} — and every other macro in the file. Edit it there. To narrow it down\n"
495
+ f"to one macro, delete it first and re-run; that discards every edit in it.",
496
+ file=sys.stderr,
497
+ )
498
+ return 1
499
+
500
+ component = parse(component_path)
501
+
502
+ # A second eject from the same file rewrites the override: the macro moves
503
+ # out of the re-export list into the owned section, and everything already
504
+ # owned stays owned. Refusing would leave hand-editing as the only way to
505
+ # take a second macro.
506
+ already = _stamped_macros(stamp["macros"]) if stamp else []
507
+ if macro in already:
508
+ print(f"fjkit eject: {target} already owns {macro!r}", file=sys.stderr)
509
+ return 1
510
+
511
+ owned = list(dict.fromkeys([*already, *component.closure(macro)]))
512
+ unknown = [n for n in owned if n not in component.macros]
513
+ if unknown:
514
+ print(
515
+ f"fjkit eject: {target} claims macro(s) {', '.join(unknown)} the kit no longer ships.\n"
516
+ f"Sort that out first — `fjkit check` explains it.",
517
+ file=sys.stderr,
518
+ )
519
+ return 1
520
+
521
+ _write(target, render_override(component, owned, _version()))
522
+ extra = [n for n in component.closure(macro) if n != macro]
523
+ print(
524
+ f"{'rewrote' if existing else 'wrote'} {target}\n"
525
+ f"It owns {_and([n for n in owned if not n.startswith('_')])}"
526
+ + (f", and copies {_and(extra)} because a private macro cannot be re-exported" if extra else "")
527
+ + f".\nThe other {len(component.macros) - len(owned)} macro(s) are re-exported from the kit and still"
528
+ f" get upstream fixes.\nNothing at any call site changes."
529
+ )
530
+ return 0
531
+
532
+
533
+ def parse_or_none(path: Path) -> dict[str, Macro]:
534
+ try:
535
+ return parse(path).macros
536
+ except Unsplittable:
537
+ return {}
538
+
539
+
540
+ def _stamped_macros(raw: str) -> list[str]:
541
+ return [entry.split("=", 1)[0] for entry in raw.split(",")]
542
+
543
+
544
+ def _write(target: Path, text: str) -> None:
545
+ target.parent.mkdir(parents=True, exist_ok=True)
546
+ target.write_text(text, encoding="utf-8")
547
+
548
+
549
+ def _version() -> str:
550
+ """Read the installed fjkit version, for the eject stamp.
551
+
552
+ Taken from the installed distribution rather than a `__version__` constant,
553
+ because that is the single source hatchling already builds the wheel from.
554
+ Running from a source tree with nothing installed does not fail the eject:
555
+ the digest detects staleness, and the version is a readable note beside it.
556
+ """
557
+ from importlib.metadata import PackageNotFoundError, version
558
+
559
+ try:
560
+ return version("fjkit")
561
+ except PackageNotFoundError: # pragma: no cover - only outside an install
562
+ return "unknown"