resource-engine-devtools 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. resource_engine_devtools/__init__.py +6 -0
  2. resource_engine_devtools/ai/__init__.py +1 -0
  3. resource_engine_devtools/ai/example.py +66 -0
  4. resource_engine_devtools/ai/installer.py +424 -0
  5. resource_engine_devtools/ai/skill/SKILL.md +130 -0
  6. resource_engine_devtools/ai/skill/examples/README.md +7 -0
  7. resource_engine_devtools/ai/skill/examples/invoices/__init__.py +0 -0
  8. resource_engine_devtools/ai/skill/examples/invoices/app.py +245 -0
  9. resource_engine_devtools/ai/skill/examples/invoices/application/__init__.py +0 -0
  10. resource_engine_devtools/ai/skill/examples/invoices/application/actions.py +61 -0
  11. resource_engine_devtools/ai/skill/examples/invoices/application/balances.py +51 -0
  12. resource_engine_devtools/ai/skill/examples/invoices/application/customers.py +35 -0
  13. resource_engine_devtools/ai/skill/examples/invoices/application/hooks.py +61 -0
  14. resource_engine_devtools/ai/skill/examples/invoices/application/processes.py +80 -0
  15. resource_engine_devtools/ai/skill/examples/invoices/application/resource.py +112 -0
  16. resource_engine_devtools/ai/skill/examples/invoices/application/schemas.py +164 -0
  17. resource_engine_devtools/ai/skill/examples/invoices/application/tags.py +77 -0
  18. resource_engine_devtools/ai/skill/examples/invoices/authz.py +126 -0
  19. resource_engine_devtools/ai/skill/examples/invoices/bootstrap.py +80 -0
  20. resource_engine_devtools/ai/skill/examples/invoices/domain/__init__.py +0 -0
  21. resource_engine_devtools/ai/skill/examples/invoices/domain/entities.py +112 -0
  22. resource_engine_devtools/ai/skill/examples/invoices/domain/events.py +22 -0
  23. resource_engine_devtools/ai/skill/examples/invoices/domain/state_machine.py +88 -0
  24. resource_engine_devtools/ai/skill/examples/invoices/infrastructure/__init__.py +0 -0
  25. resource_engine_devtools/ai/skill/examples/invoices/infrastructure/persistence.py +121 -0
  26. resource_engine_devtools/ai/skill/examples/invoices/locale/en/LC_MESSAGES/messages.po +682 -0
  27. resource_engine_devtools/ai/skill/examples/invoices/locale/es/LC_MESSAGES/messages.po +685 -0
  28. resource_engine_devtools/ai/skill/examples/invoices/notifications.py +47 -0
  29. resource_engine_devtools/ai/skill/examples/invoices/templates/email/base.html +7 -0
  30. resource_engine_devtools/ai/skill/examples/invoices/templates/email/invoice_approved.html +5 -0
  31. resource_engine_devtools/ai/skill/examples/invoices/templates/email/invoice_approved.subject.txt +1 -0
  32. resource_engine_devtools/ai/skill/examples/invoices/templates/email/invoice_approved.txt +5 -0
  33. resource_engine_devtools/ai/skill/examples/invoices/tests/conftest.py +40 -0
  34. resource_engine_devtools/ai/skill/examples/invoices/tests/test_invoices_engine.py +241 -0
  35. resource_engine_devtools/ai/skill/examples/invoices/worker.py +53 -0
  36. resource_engine_devtools/ai/skill/llms.txt +25 -0
  37. resource_engine_devtools/ai/skill/references/anti-patterns.md +209 -0
  38. resource_engine_devtools/ai/skill/references/docstrings.md +97 -0
  39. resource_engine_devtools/ai/skill/references/errors.md +81 -0
  40. resource_engine_devtools/ai/skill/references/lifecycle.md +118 -0
  41. resource_engine_devtools/ai/skill/references/permissions.md +111 -0
  42. resource_engine_devtools/ai/skill/references/resource.md +301 -0
  43. resource_engine_devtools/ai/skill/references/state-machines.md +126 -0
  44. resource_engine_devtools/ai/skill/references/testing.md +80 -0
  45. resource_engine_devtools/ai/templates/agents_block.md +26 -0
  46. resource_engine_devtools/ai/templates/cursor_rule.mdc +7 -0
  47. resource_engine_devtools/check.py +67 -0
  48. resource_engine_devtools/cli.py +1112 -0
  49. resource_engine_devtools/consumer_scaffold.py +715 -0
  50. resource_engine_devtools/contracts.py +471 -0
  51. resource_engine_devtools/db.py +132 -0
  52. resource_engine_devtools/declarations_check.py +116 -0
  53. resource_engine_devtools/documentation/__init__.py +10 -0
  54. resource_engine_devtools/documentation/docstrings.py +72 -0
  55. resource_engine_devtools/documentation/generators/__init__.py +9 -0
  56. resource_engine_devtools/documentation/generators/ai_context.py +121 -0
  57. resource_engine_devtools/documentation/generators/api.py +63 -0
  58. resource_engine_devtools/documentation/generators/json.py +12 -0
  59. resource_engine_devtools/documentation/generators/markdown.py +687 -0
  60. resource_engine_devtools/documentation/generators/mermaid.py +22 -0
  61. resource_engine_devtools/documentation/generators/site.py +379 -0
  62. resource_engine_devtools/documentation/generators/site_assets/site.css +62 -0
  63. resource_engine_devtools/documentation/generators/site_assets/site.js +54 -0
  64. resource_engine_devtools/documentation/i18n.py +185 -0
  65. resource_engine_devtools/documentation/introspector.py +563 -0
  66. resource_engine_devtools/documentation/locale/ca/LC_MESSAGES/docs.po +628 -0
  67. resource_engine_devtools/documentation/locale/es/LC_MESSAGES/docs.po +627 -0
  68. resource_engine_devtools/documentation/model.py +311 -0
  69. resource_engine_devtools/documentation/validator.py +128 -0
  70. resource_engine_devtools/emails.py +172 -0
  71. resource_engine_devtools/events_check.py +124 -0
  72. resource_engine_devtools/gates_check.py +133 -0
  73. resource_engine_devtools/hooks_check.py +287 -0
  74. resource_engine_devtools/i18n.py +312 -0
  75. resource_engine_devtools/loader.py +93 -0
  76. resource_engine_devtools/logic_check.py +136 -0
  77. resource_engine_devtools/mcp_server.py +685 -0
  78. resource_engine_devtools/py.typed +0 -0
  79. resource_engine_devtools/scaffold.py +805 -0
  80. resource_engine_devtools/scaffold_parts.py +637 -0
  81. resource_engine_devtools/source_edit.py +424 -0
  82. resource_engine_devtools/templates_check.py +59 -0
  83. resource_engine_devtools/worker.py +68 -0
  84. resource_engine_devtools-0.1.0.dist-info/METADATA +38 -0
  85. resource_engine_devtools-0.1.0.dist-info/RECORD +88 -0
  86. resource_engine_devtools-0.1.0.dist-info/WHEEL +4 -0
  87. resource_engine_devtools-0.1.0.dist-info/entry_points.txt +2 -0
  88. resource_engine_devtools-0.1.0.dist-info/licenses/LICENSE +202 -0
@@ -0,0 +1,311 @@
1
+ """Format-independent functional documentation model."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import asdict, dataclass, field
6
+ from typing import Any
7
+
8
+ from resource_engine_devtools.documentation.docstrings import DocText
9
+
10
+
11
+ @dataclass
12
+ class FieldDoc:
13
+ """A field of a schema, as documented."""
14
+
15
+ name: str
16
+ type: str
17
+ required: bool
18
+ description: str | None = None
19
+
20
+
21
+ @dataclass
22
+ class SchemaDoc:
23
+ """A schema of a resource (create, update, read, an action's input...), as documented."""
24
+
25
+ name: str
26
+ role: str
27
+ fields: list[FieldDoc]
28
+ doc: DocText
29
+
30
+
31
+ @dataclass
32
+ class HookDoc:
33
+ """A hook of a resource, as documented."""
34
+
35
+ point: str
36
+ name: str
37
+ qualname: str
38
+ external_effect: bool
39
+ doc: DocText
40
+
41
+
42
+ @dataclass
43
+ class OperationDoc:
44
+ """An operation of a resource (CRUD, transition or action), as documented."""
45
+
46
+ name: str
47
+ kind: str # crud | transition | action
48
+ method: str
49
+ path: str
50
+ doc: DocText
51
+ input_schema: str | None = None
52
+ output_schema: str | None = None
53
+
54
+
55
+ @dataclass
56
+ class StateDoc:
57
+ """A state of a state machine, as documented."""
58
+
59
+ id: str
60
+ name: str
61
+ initial: bool
62
+ final: bool
63
+ description: str | None
64
+
65
+
66
+ @dataclass
67
+ class TransitionDoc:
68
+ """A transition of a state machine, as documented."""
69
+
70
+ event: str
71
+ source: str
72
+ target: str
73
+ description: str | None
74
+
75
+
76
+ @dataclass
77
+ class TimerDoc:
78
+ """A timed transition (``Resource.timers``)."""
79
+
80
+ event: str
81
+ after: str
82
+ since: str
83
+ states: list[str]
84
+ description: str | None = None
85
+
86
+
87
+ @dataclass
88
+ class StateMachineDoc:
89
+ """A resource's state machine, as documented."""
90
+
91
+ name: str
92
+ qualname: str
93
+ state_field: str
94
+ doc: DocText
95
+ states: list[StateDoc]
96
+ transitions: list[TransitionDoc]
97
+ timers: list[TimerDoc] = field(default_factory=list)
98
+ since_field: str | None = None
99
+ machine: str = "" # its name on the resource (Resource.machines)
100
+
101
+
102
+ @dataclass
103
+ class ActionDoc:
104
+ """An action of a resource, as documented."""
105
+
106
+ name: str
107
+ qualname: str
108
+ instance: bool
109
+ doc: DocText
110
+ input_schema: str | None
111
+ output_schema: str | None
112
+
113
+
114
+ @dataclass
115
+ class ReferenceDoc:
116
+ """A reference to another resource (``Resource.references``)."""
117
+
118
+ name: str
119
+ field: str
120
+ resource: str
121
+ on_delete: str
122
+ description: str | None = None
123
+ related_name: str | None = None
124
+
125
+
126
+ @dataclass
127
+ class ReactionDoc:
128
+ """An event a process reacts to (``Process.reacts``)."""
129
+
130
+ event: str
131
+ when: str
132
+ key: str
133
+ start: bool
134
+ handler: str
135
+ description: str | None = None
136
+
137
+
138
+ @dataclass
139
+ class EventDoc:
140
+ """A domain event the resource declares (``Resource.events``)."""
141
+
142
+ name: str
143
+ qualname: str
144
+ doc: DocText
145
+ fields: list[FieldDoc]
146
+
147
+
148
+ @dataclass
149
+ class SlotDoc:
150
+ """A document slot of a resource, as documented."""
151
+
152
+ name: str
153
+ description: str | None
154
+ content_types: list[str]
155
+ max_bytes: int
156
+ multiple: bool
157
+ upload: str
158
+ required_for: list[str]
159
+ processing: bool
160
+
161
+
162
+ @dataclass
163
+ class EmailUseDoc:
164
+ """An email a hook or action of the resource requests."""
165
+
166
+ template: str | None # None: computed at runtime
167
+ point: str # hook point, or action:<name>
168
+ function: str
169
+ locale: str | None
170
+ to: str # the recipients as written in the code
171
+
172
+
173
+ @dataclass
174
+ class EmailVariantDoc:
175
+ """A template set rendered for one locale, variables as placeholders."""
176
+
177
+ locale: str | None # None: the unlocalised (fallback) templates
178
+ subject: str | None
179
+ text: str | None
180
+ html: str | None
181
+
182
+
183
+ @dataclass
184
+ class EmailTemplateDoc:
185
+ """An email template, the resources that send it and its locale variants."""
186
+
187
+ template: str
188
+ used_by: list[str] # "<resource> <point>"
189
+ variants: list[EmailVariantDoc] = field(default_factory=list)
190
+ missing: list[str] = field(default_factory=list) # files the requests need
191
+
192
+
193
+ @dataclass
194
+ class PrintoutDoc:
195
+ """A document the resource renders on request (``Resource.printouts``)."""
196
+
197
+ name: str
198
+ template: str
199
+ formats: list[str]
200
+ description: str | None
201
+
202
+
203
+ @dataclass
204
+ class DocumentUseDoc:
205
+ """A document a hook or action generates and attaches (``DocumentGenerator.attach``)."""
206
+
207
+ template: str | None # None: computed at runtime
208
+ slot: str | None
209
+ point: str # hook point, or action:<name>
210
+ function: str
211
+ format: str | None
212
+
213
+
214
+ @dataclass
215
+ class DocumentVariantDoc:
216
+ """A document template rendered for one locale, variables as placeholders."""
217
+
218
+ locale: str | None # None: the unlocalised (fallback) template
219
+ html: str | None
220
+ text: str | None # the Markdown or text template
221
+
222
+
223
+ @dataclass
224
+ class DocumentTemplateDoc:
225
+ """A document template, the resources that render it and its locale variants."""
226
+
227
+ template: str
228
+ used_by: list[str] # "<resource> printout <name>" / "<resource> <point>"
229
+ variants: list[DocumentVariantDoc] = field(default_factory=list)
230
+
231
+
232
+ @dataclass
233
+ class ResourceDoc:
234
+ """Everything documented about one resource."""
235
+
236
+ name: str
237
+ qualname: str
238
+ module: str
239
+ model: str
240
+ doc: DocText
241
+ operations: list[OperationDoc]
242
+ schemas: list[SchemaDoc]
243
+ hooks: list[HookDoc]
244
+ actions: list[ActionDoc]
245
+ state_machines: list[StateMachineDoc]
246
+ filterable: list[str] = field(default_factory=list)
247
+ sortable: list[str] = field(default_factory=list)
248
+ documents: list[SlotDoc] = field(default_factory=list)
249
+ restricted_fields: list[str] = field(default_factory=list)
250
+ tenant_field: str | None = None
251
+ version_field: str | None = None
252
+ require_version: bool = False
253
+ audit: bool = True
254
+ audit_reads: bool = False
255
+ audit_exclude: list[str] = field(default_factory=list)
256
+ events: list[EventDoc] = field(default_factory=list)
257
+ references: list[ReferenceDoc] = field(default_factory=list)
258
+ referenced_by: list[ReferenceDoc] = field(default_factory=list)
259
+ #: Many-to-many relations: ``name`` lists ``resource`` through the join ``field``.
260
+ links: list[ReferenceDoc] = field(default_factory=list)
261
+ #: For process managers: the correlation field and the events they react to.
262
+ correlation: str | None = None
263
+ reacts: list[ReactionDoc] = field(default_factory=list)
264
+ #: Polymorphic resources: a base's discriminator and subtypes (by identity),
265
+ #: or the base a subtype extends and its identity.
266
+ discriminator: str | None = None
267
+ subtypes: dict[str, str] = field(default_factory=dict)
268
+ extends: str | None = None
269
+ identity: str | None = None
270
+ #: View resources: "custom", or the source of an aggregate, its groups and values.
271
+ view: str | None = None
272
+ view_group_by: list[str] = field(default_factory=list)
273
+ view_values: dict[str, str] = field(default_factory=dict)
274
+ emails: list[EmailUseDoc] = field(default_factory=list)
275
+ printouts: list[PrintoutDoc] = field(default_factory=list)
276
+ generated: list[DocumentUseDoc] = field(default_factory=list)
277
+
278
+
279
+ @dataclass
280
+ class SystemRoleDoc:
281
+ """A system role, as documented."""
282
+
283
+ name: str
284
+ description: str | None
285
+ grants: list[str]
286
+ actions: list[str] # catalogue actions the grants cover
287
+
288
+
289
+ @dataclass
290
+ class DocumentationModel:
291
+ """The documentation of a whole application: resources, actions, roles, events and templates."""
292
+
293
+ resources: list[ResourceDoc]
294
+ engine_version: str
295
+ actions: list[str] = field(default_factory=list)
296
+ system_roles: list[SystemRoleDoc] = field(default_factory=list)
297
+ audit_resource: str | None = None
298
+ emails: list[EmailTemplateDoc] = field(default_factory=list)
299
+ documents: list[DocumentTemplateDoc] = field(default_factory=list)
300
+
301
+ def to_dict(self) -> dict[str, Any]:
302
+ """The model as JSON-ready data."""
303
+ return asdict(self)
304
+
305
+
306
+ def _first_machine(self: ResourceDoc) -> StateMachineDoc | None:
307
+ """The first (or only) state machine."""
308
+ return self.state_machines[0] if self.state_machines else None
309
+
310
+
311
+ ResourceDoc.state_machine = property(_first_machine) # type: ignore[attr-defined]
@@ -0,0 +1,128 @@
1
+ """Documentation coverage rules. Every finding has a stable rule code (RE-D0xx)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from dataclasses import asdict, dataclass
7
+ from typing import Any
8
+
9
+ from resource_engine_devtools.documentation.model import DocumentationModel
10
+
11
+
12
+ @dataclass(frozen=True)
13
+ class Finding:
14
+ """A documentation check's result for one target."""
15
+
16
+ level: str # "error" | "warning" | "ok"
17
+ code: str
18
+ target: str
19
+ message: str
20
+
21
+ def to_dict(self) -> dict[str, str]:
22
+ """The finding as JSON-ready data."""
23
+ return asdict(self)
24
+
25
+
26
+ def validate(model: DocumentationModel) -> list[Finding]:
27
+ """Check the documentation model for missing descriptions and docstrings."""
28
+ findings: list[Finding] = []
29
+
30
+ def check(ok: bool, level: str, code: str, target: str, message: str) -> None:
31
+ findings.append(Finding("ok" if ok else level, code, target, message))
32
+
33
+ for r in model.resources:
34
+ check(r.doc.present, "error", "RE-D001", r.qualname, "resource has a description")
35
+ for op in r.operations:
36
+ if op.kind == "crud":
37
+ check(
38
+ op.doc.present,
39
+ "error",
40
+ "RE-D002",
41
+ f"{r.name}.{op.name}",
42
+ "CRUD operation is documented (operation_docs)",
43
+ )
44
+ for sm in r.state_machines:
45
+ check(
46
+ sm.doc.present, "error", "RE-D003", sm.qualname, "state machine has a description"
47
+ )
48
+ for s in sm.states:
49
+ check(
50
+ bool(s.description),
51
+ "warning",
52
+ "RE-D004",
53
+ f"{sm.name}.{s.id}",
54
+ "state is documented (States: section)",
55
+ )
56
+ for event in dict.fromkeys(t.event for t in sm.transitions):
57
+ documented = any(t.description for t in sm.transitions if t.event == event)
58
+ check(
59
+ documented,
60
+ "warning",
61
+ "RE-D005",
62
+ f"{sm.name}.{event}",
63
+ "transition is documented (Transitions: section)",
64
+ )
65
+ for a in r.actions:
66
+ check(a.doc.present, "error", "RE-D006", a.qualname, "action has a description")
67
+ if a.doc.present:
68
+ check(
69
+ "postconditions" in a.doc.sections,
70
+ "warning",
71
+ "RE-D007",
72
+ a.qualname,
73
+ "action documents its Postconditions",
74
+ )
75
+ for e in r.events:
76
+ check(e.doc.present, "warning", "RE-D011", e.qualname, "domain event is documented")
77
+ for slot in r.documents:
78
+ check(
79
+ bool(slot.description),
80
+ "warning",
81
+ "RE-D009",
82
+ f"{r.qualname}.documents.{slot.name}",
83
+ "document slot has a description",
84
+ )
85
+ for h in r.hooks:
86
+ check(
87
+ h.doc.present, "warning", "RE-D008", h.qualname, f"hook at {h.point} is documented"
88
+ )
89
+ for target, text in _texts(r):
90
+ if PLACEHOLDER.search(text):
91
+ findings.append(
92
+ Finding("warning", "RE-D010", target, "documentation is a TODO placeholder")
93
+ )
94
+ return findings
95
+
96
+
97
+ #: Placeholder text left by ``resource-engine scaffold``.
98
+ PLACEHOLDER = re.compile(r"\bTODO\b")
99
+
100
+
101
+ def _doc_texts(target: str, doc: Any) -> list[tuple[str, str]]:
102
+ texts = [doc.summary or "", doc.description or "", *doc.sections.values()]
103
+ texts += [d for items in doc.items.values() for d in items.values()]
104
+ return [(target, t) for t in texts if t]
105
+
106
+
107
+ def _texts(r: Any) -> list[tuple[str, str]]:
108
+ """Every documentation text of a resource, with the element it describes."""
109
+ found = _doc_texts(r.qualname, r.doc)
110
+ for op in r.operations:
111
+ found += _doc_texts(f"{r.name}.{op.name}", op.doc)
112
+ for sm in r.state_machines:
113
+ found += _doc_texts(sm.qualname, sm.doc)
114
+ found += [(f"{sm.name}.{s.id}", s.description or "") for s in sm.states]
115
+ found += [(f"{sm.name}.{t.event}", t.description or "") for t in sm.transitions]
116
+ for a in r.actions:
117
+ found += _doc_texts(a.qualname, a.doc)
118
+ for h in r.hooks:
119
+ found += _doc_texts(h.qualname, h.doc)
120
+ for e in getattr(r, "events", []) or []:
121
+ found += _doc_texts(e.qualname, e.doc)
122
+ for slot in r.documents:
123
+ found.append((f"{r.qualname}.documents.{slot.name}", slot.description or ""))
124
+ for schema in getattr(r, "schemas", []) or []:
125
+ doc = getattr(schema, "doc", None)
126
+ if doc is not None:
127
+ found += _doc_texts(getattr(schema, "qualname", r.qualname), doc)
128
+ return list(dict.fromkeys(x for x in found if x[1])) # without repeats, in order
@@ -0,0 +1,172 @@
1
+ """Where the application requests emails: every ``EmailRequested(...)`` in the
2
+ hooks and actions of the registered resources (and the application functions
3
+ they call), read from the source. Used by ``check`` (RE-C007) and the
4
+ generated docs. ``find_document_renders`` does the same for the documents
5
+ they generate (``DocumentGenerator.attach``).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import ast
11
+ import inspect
12
+ import types
13
+ from collections.abc import Callable, Iterator
14
+ from dataclasses import dataclass
15
+ from typing import Any
16
+
17
+ from resource_engine import ResourceDefinition, ResourceRegistry
18
+ from resource_engine.email import EmailRequested
19
+
20
+ from resource_engine_devtools.hooks_check import (
21
+ _UNRESOLVED,
22
+ MAX_DEPTH,
23
+ _is_application,
24
+ _parse,
25
+ _resolve,
26
+ _scope,
27
+ )
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class EmailUse:
32
+ """One ``EmailRequested`` call.
33
+
34
+ Attributes:
35
+ resource: The resource whose hook or action requests it.
36
+ point: The hook point (``after_transition:approve``) or ``action:<name>``.
37
+ function: The hook or action that requests it (or calls the helper that does).
38
+ template: The template set, ``None`` when computed at runtime.
39
+ locale: A literal locale, if any.
40
+ to: The recipients as written (``[customer.email]``).
41
+ path / line: Where the call is.
42
+ """
43
+
44
+ resource: str
45
+ point: str
46
+ function: str
47
+ template: str | None
48
+ locale: str | None
49
+ to: str
50
+ path: str
51
+ line: int
52
+
53
+
54
+ def find_email_requests(registry: ResourceRegistry) -> list[EmailUse]:
55
+ """The emails hooks and actions request (``EmailRequested``), found in their source."""
56
+ uses: list[EmailUse] = []
57
+ for definition in registry:
58
+ if definition.resource_cls.__module__.startswith("resource_engine."):
59
+ continue
60
+ for point, fn, extra in _code(definition):
61
+ name = getattr(fn, "__qualname__", repr(fn))
62
+ for path, line, call in _calls(fn, 0, set(), extra):
63
+ keywords = {k.arg: k.value for k in call.keywords if k.arg}
64
+ uses.append(
65
+ EmailUse(
66
+ resource=definition.name,
67
+ point=point,
68
+ function=name,
69
+ template=_literal(keywords.get("template")),
70
+ locale=_literal(keywords.get("locale")),
71
+ to=ast.unparse(keywords["to"]) if "to" in keywords else "",
72
+ path=path,
73
+ line=line,
74
+ )
75
+ )
76
+ return uses
77
+
78
+
79
+ @dataclass(frozen=True)
80
+ class DocumentUse:
81
+ """One ``DocumentGenerator.attach(ctx, slot, template, ...)`` call."""
82
+
83
+ resource: str
84
+ point: str
85
+ function: str
86
+ template: str | None
87
+ slot: str | None
88
+ format: str | None
89
+ path: str
90
+ line: int
91
+
92
+
93
+ def _is_attach(target: Any) -> bool:
94
+ from resource_engine.generation import DocumentGenerator
95
+
96
+ func = getattr(target, "__func__", target)
97
+ return func is DocumentGenerator.attach
98
+
99
+
100
+ def find_document_renders(registry: ResourceRegistry) -> list[DocumentUse]:
101
+ """The documents hooks and actions render, found in their source."""
102
+ uses: list[DocumentUse] = []
103
+ for definition in registry:
104
+ if definition.resource_cls.__module__.startswith("resource_engine."):
105
+ continue
106
+ for point, fn, extra in _code(definition):
107
+ name = getattr(fn, "__qualname__", repr(fn))
108
+ for path, line, call in _calls(fn, 0, set(), extra, match=_is_attach):
109
+ keywords = {k.arg: k.value for k in call.keywords if k.arg}
110
+ args = list(call.args) # (ctx, slot, template)
111
+ slot = keywords.get("slot") or (args[1] if len(args) > 1 else None)
112
+ template = keywords.get("template") or (args[2] if len(args) > 2 else None)
113
+ uses.append(
114
+ DocumentUse(
115
+ resource=definition.name,
116
+ point=point,
117
+ function=name,
118
+ template=_literal(template),
119
+ slot=_literal(slot),
120
+ format=_literal(keywords.get("format")) or "pdf",
121
+ path=path,
122
+ line=line,
123
+ )
124
+ )
125
+ return uses
126
+
127
+
128
+ def _code(definition: ResourceDefinition) -> Iterator[tuple[str, Callable[..., Any], Any]]:
129
+ for key, hooks in definition.hooks.items():
130
+ for hook in hooks:
131
+ yield str(key), hook, None
132
+ for action in definition.actions.values():
133
+ execute = getattr(action.action_cls, "execute", None)
134
+ if execute is not None:
135
+ yield f"action:{action.name}", execute, {"self": action.action_cls}
136
+
137
+
138
+ def _literal(node: ast.expr | None) -> str | None:
139
+ if isinstance(node, ast.Constant) and isinstance(node.value, str):
140
+ return node.value
141
+ return None
142
+
143
+
144
+ def _calls(
145
+ fn: Callable[..., Any],
146
+ depth: int,
147
+ visited: set[int],
148
+ extra: dict[str, Any] | None,
149
+ *,
150
+ match: Callable[[Any], bool] = lambda target: target is EmailRequested,
151
+ ) -> Iterator[tuple[str, int, ast.Call]]:
152
+ fn = inspect.unwrap(fn)
153
+ if id(fn) in visited or depth > MAX_DEPTH:
154
+ return
155
+ visited.add(id(fn))
156
+ parsed = _parse(fn)
157
+ if parsed is None:
158
+ return
159
+ tree, path, first_line = parsed
160
+ scope = _scope(fn) | (extra or {})
161
+ for node in ast.walk(tree):
162
+ if not isinstance(node, ast.Call):
163
+ continue
164
+ target = _resolve(node.func, scope)
165
+ if match(target):
166
+ yield path, first_line + node.lineno - 1, node
167
+ continue
168
+ if target is _UNRESOLVED:
169
+ continue
170
+ if isinstance(target, types.FunctionType | types.MethodType) and _is_application(target):
171
+ inner = {"self": extra["self"]} if extra and "self" in extra else None
172
+ yield from _calls(target, depth + 1, visited, inner, match=match)