nat20-bridge 0.3.1__tar.gz

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 (33) hide show
  1. nat20_bridge-0.3.1/.gitignore +30 -0
  2. nat20_bridge-0.3.1/LICENSE +21 -0
  3. nat20_bridge-0.3.1/Makefile +14 -0
  4. nat20_bridge-0.3.1/PKG-INFO +39 -0
  5. nat20_bridge-0.3.1/README.md +28 -0
  6. nat20_bridge-0.3.1/pyproject.toml +86 -0
  7. nat20_bridge-0.3.1/src/nat20_bridge/__init__.py +3 -0
  8. nat20_bridge-0.3.1/src/nat20_bridge/app.py +257 -0
  9. nat20_bridge-0.3.1/src/nat20_bridge/cli.py +25 -0
  10. nat20_bridge-0.3.1/src/nat20_bridge/forge.py +94 -0
  11. nat20_bridge-0.3.1/src/nat20_bridge/homebrew.py +148 -0
  12. nat20_bridge-0.3.1/src/nat20_bridge/models.py +82 -0
  13. nat20_bridge-0.3.1/src/nat20_bridge/narrate.py +172 -0
  14. nat20_bridge-0.3.1/src/nat20_bridge/overlay.py +89 -0
  15. nat20_bridge-0.3.1/src/nat20_bridge/routes_combat.py +411 -0
  16. nat20_bridge-0.3.1/src/nat20_bridge/routes_content.py +168 -0
  17. nat20_bridge-0.3.1/src/nat20_bridge/sheet.py +105 -0
  18. nat20_bridge-0.3.1/src/nat20_bridge/slots.py +126 -0
  19. nat20_bridge-0.3.1/src/nat20_bridge/state.py +47 -0
  20. nat20_bridge-0.3.1/tests/conftest.py +12 -0
  21. nat20_bridge-0.3.1/tests/test_cli.py +48 -0
  22. nat20_bridge-0.3.1/tests/test_combat_e2e.py +107 -0
  23. nat20_bridge-0.3.1/tests/test_forge.py +55 -0
  24. nat20_bridge-0.3.1/tests/test_health.py +9 -0
  25. nat20_bridge-0.3.1/tests/test_homebrew.py +155 -0
  26. nat20_bridge-0.3.1/tests/test_name_sanitizer.py +26 -0
  27. nat20_bridge-0.3.1/tests/test_narrate.py +117 -0
  28. nat20_bridge-0.3.1/tests/test_overlay.py +110 -0
  29. nat20_bridge-0.3.1/tests/test_rest.py +93 -0
  30. nat20_bridge-0.3.1/tests/test_roll_check.py +106 -0
  31. nat20_bridge-0.3.1/tests/test_sheet.py +115 -0
  32. nat20_bridge-0.3.1/tests/test_slots.py +39 -0
  33. nat20_bridge-0.3.1/tests/test_srd_browse.py +97 -0
@@ -0,0 +1,30 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *.egg-info/
5
+ .venv/
6
+ dist/
7
+ build/
8
+
9
+ # uv
10
+ # (uv.lock at root IS tracked; member uv.lock files are removed)
11
+
12
+ # Tooling caches
13
+ .pytest_cache/
14
+ .mypy_cache/
15
+ .ruff_cache/
16
+ .coverage
17
+ htmlcov/
18
+
19
+ # Docs build output
20
+ site/
21
+
22
+ # Editors / OS
23
+ .DS_Store
24
+ .idea/
25
+ .vscode/
26
+
27
+ # Upstream raw sources (regenerated locally via `make refresh-upstream`; never committed)
28
+ packages/dnd5e-srd-data/raw_sources/foundry/
29
+ packages/dnd5e-srd-data/raw_sources/open5e/
30
+ packages/dnd5e-srd-data/raw_sources/five_e_bits/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Tapestria contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
@@ -0,0 +1,14 @@
1
+ .PHONY: install test check
2
+
3
+ install:
4
+ uv pip install -e ".[dev]"
5
+
6
+ test:
7
+ uv run pytest -v
8
+
9
+ check:
10
+ uv run ruff check src tests
11
+ uv run ruff format --check src tests
12
+ uv run mypy src
13
+ uv run pytest -q --cov=nat20_bridge --cov-report=term-missing --cov-fail-under=85
14
+ uv run bandit -r src/ -c pyproject.toml -q
@@ -0,0 +1,39 @@
1
+ Metadata-Version: 2.5
2
+ Name: nat20-bridge
3
+ Version: 0.3.1
4
+ Summary: Localhost HTTP sidecar exposing dnd5e-engine to the SillyTavern nat20 extension
5
+ License: MIT License
6
+
7
+ Copyright (c) 2026 Tapestria contributors
8
+
9
+ Permission is hereby granted, free of charge, to any person obtaining a copy
10
+ of this software and associated documentation files (the "Software"), to deal
11
+ in the Software without restriction, including without limitation the rights
12
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13
+ copies of the Software, and to permit persons to whom the Software is
14
+ furnished to do so, subject to the following conditions:
15
+
16
+ The above copyright notice and this permission notice shall be included in
17
+ all copies or substantial portions of the Software.
18
+
19
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25
+ THE SOFTWARE.
26
+ License-File: LICENSE
27
+ Requires-Python: >=3.12
28
+ Requires-Dist: dnd5e-engine>=0.3.0
29
+ Requires-Dist: dnd5e-srd-data>=0.3.0
30
+ Requires-Dist: fastapi>=0.115
31
+ Requires-Dist: uvicorn>=0.30
32
+ Provides-Extra: dev
33
+ Requires-Dist: bandit>=1.8.0; extra == 'dev'
34
+ Requires-Dist: httpx>=0.27; extra == 'dev'
35
+ Requires-Dist: mypy>=1.10; extra == 'dev'
36
+ Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
37
+ Requires-Dist: pytest-cov>=6.0.0; extra == 'dev'
38
+ Requires-Dist: pytest>=8.0; extra == 'dev'
39
+ Requires-Dist: ruff>=0.5; extra == 'dev'
@@ -0,0 +1,28 @@
1
+ # nat20-bridge
2
+
3
+ A localhost HTTP sidecar that exposes the [`dnd5e-engine`](../dnd5e-engine) rules
4
+ engine (backed by [`dnd5e-srd-data`](../dnd5e-srd-data)) to the SillyTavern nat20
5
+ extension over a small FastAPI surface.
6
+
7
+ The bridge binds to `127.0.0.1` by default — it is not intended to be exposed on
8
+ the network. CORS is permissive because the SillyTavern browser page fetches it
9
+ cross-origin from a loopback address.
10
+
11
+ ## Running
12
+
13
+ ```bash
14
+ uv run nat20-bridge
15
+ ```
16
+
17
+ Options:
18
+
19
+ - `--host` (default `127.0.0.1`)
20
+ - `--port` (default `8020`)
21
+ - `--data-dir` (default `~/.nat20-bridge`) — where `homebrew.json` persists.
22
+
23
+ ## Development
24
+
25
+ ```bash
26
+ uv sync --extra dev
27
+ make check
28
+ ```
@@ -0,0 +1,86 @@
1
+ [project]
2
+ name = "nat20-bridge"
3
+ version = "0.3.1"
4
+ description = "Localhost HTTP sidecar exposing dnd5e-engine to the SillyTavern nat20 extension"
5
+ requires-python = ">=3.12"
6
+ license = { file = "LICENSE" }
7
+ dependencies = [
8
+ "dnd5e-engine>=0.3.0",
9
+ "dnd5e-srd-data>=0.3.0",
10
+ "fastapi>=0.115",
11
+ "uvicorn>=0.30",
12
+ ]
13
+
14
+ [project.scripts]
15
+ nat20-bridge = "nat20_bridge.cli:main"
16
+
17
+ [project.optional-dependencies]
18
+ dev = [
19
+ "httpx>=0.27",
20
+ "pytest>=8.0",
21
+ "pytest-asyncio>=0.23",
22
+ "pytest-cov>=6.0.0",
23
+ "mypy>=1.10",
24
+ "ruff>=0.5",
25
+ "bandit>=1.8.0",
26
+ ]
27
+
28
+ [tool.uv.sources]
29
+ dnd5e-engine = { workspace = true }
30
+ dnd5e-srd-data = { workspace = true }
31
+
32
+ [build-system]
33
+ requires = ["hatchling"]
34
+ build-backend = "hatchling.build"
35
+
36
+ [tool.hatch.build.targets.wheel]
37
+ packages = ["src/nat20_bridge"]
38
+
39
+ [tool.ruff]
40
+ line-length = 100
41
+ target-version = "py312"
42
+
43
+ [tool.ruff.lint]
44
+ select = [
45
+ "E", "F", "I", "N", "UP", "B", "SIM", "T20", "BLE",
46
+ "C90", "ASYNC", "PT", "RUF", "TRY",
47
+ ]
48
+ ignore = [
49
+ "TRY003",
50
+ "RUF001", "RUF002", "RUF003",
51
+ ]
52
+
53
+ [tool.ruff.lint.mccabe]
54
+ max-complexity = 10
55
+
56
+ [tool.ruff.lint.per-file-ignores]
57
+ "tests/**/*.py" = [
58
+ "E501", "F841", "PT006", "PT011", "C901",
59
+ "PT018", "N806", "BLE001", "SIM102",
60
+ ]
61
+
62
+ [tool.mypy]
63
+ strict = true
64
+ python_version = "3.12"
65
+
66
+ [tool.pytest.ini_options]
67
+ testpaths = ["tests"]
68
+ pythonpath = [".", "src"]
69
+ asyncio_mode = "auto"
70
+
71
+ [tool.coverage.run]
72
+ source = ["nat20_bridge"]
73
+
74
+ [tool.coverage.report]
75
+ exclude_also = [
76
+ "if TYPE_CHECKING:",
77
+ "@overload",
78
+ "raise NotImplementedError",
79
+ ]
80
+
81
+ # tests carry asserts (B101); the roll/check/rest routes seed the stdlib
82
+ # RNG (`random.seed`/`random.Random`) to reach the engine's dice-rolling
83
+ # seams deterministically (B311) — game dice, not a security concern.
84
+ [tool.bandit]
85
+ exclude_dirs = ["tests"]
86
+ skips = ["B101", "B311"]
@@ -0,0 +1,3 @@
1
+ """nat20-bridge — localhost HTTP host for the dnd5e-engine (SillyTavern sidecar)."""
2
+
3
+ __version__ = "0.3.1"
@@ -0,0 +1,257 @@
1
+ from __future__ import annotations
2
+
3
+ import dataclasses
4
+ import random
5
+ from importlib.metadata import version
6
+ from typing import Any, Literal
7
+
8
+ from dnd5e_engine import (
9
+ CheckSpec,
10
+ HitDicePool,
11
+ configure_lib_loader,
12
+ make_build_spec,
13
+ resolve_check,
14
+ resolve_long_rest,
15
+ resolve_short_rest,
16
+ roll_dice_str,
17
+ )
18
+ from dnd5e_srd_data.loader import BundledAssetLoader
19
+ from fastapi import FastAPI, HTTPException
20
+ from fastapi.middleware.cors import CORSMiddleware
21
+ from pydantic import BaseModel, Field
22
+
23
+ from nat20_bridge import __version__
24
+ from nat20_bridge.homebrew import HomebrewStore
25
+ from nat20_bridge.models import (
26
+ ABILITY_ALIASES,
27
+ AbilityScoresModel,
28
+ PartyValidateRequest,
29
+ full_ability,
30
+ resolve_seed,
31
+ slugify,
32
+ )
33
+ from nat20_bridge.overlay import OverlayAssetLoader
34
+ from nat20_bridge.routes_combat import build_combat_router
35
+ from nat20_bridge.routes_content import build_content_router
36
+ from nat20_bridge.sheet import derive_sheet
37
+ from nat20_bridge.state import BridgeState
38
+
39
+
40
+ def _do_roll(req: _RollRequest) -> dict[str, Any]:
41
+ seed = resolve_seed(req.seed)
42
+ # `roll_dice_str` is the engine's standalone narrator-time dice seam
43
+ # (rules/effects.py) — it draws from the stdlib global `random` module
44
+ # by design ("Public test seam: callers monkeypatch this symbol (or
45
+ # random.randint) for determinism"), not an injectable `random.Random`.
46
+ # Seeding the global module is the sanctioned way to make this call
47
+ # reproducible.
48
+ random.seed(seed)
49
+ try:
50
+ total = roll_dice_str(req.dice)
51
+ except ValueError as exc:
52
+ raise HTTPException(
53
+ status_code=422, detail=f"invalid dice expression {req.dice!r}: {exc}"
54
+ ) from exc
55
+ return {"total": total, "dice": req.dice, "seed": seed}
56
+
57
+
58
+ def _check_summary(result: Any) -> str:
59
+ label = result.skill or result.ability
60
+ if result.dc is None:
61
+ return f"{label} check: {result.roll_total}"
62
+ outcome = "success" if result.success else "failure"
63
+ return f"{label} check: {result.roll_total} vs DC {result.dc} -> {outcome}"
64
+
65
+
66
+ def _do_check(req: _CheckRequest) -> dict[str, Any]:
67
+ seed = resolve_seed(req.seed)
68
+ short_scores = req.ability_scores.model_dump(by_alias=True)
69
+ ability_scores = {full: short_scores[short] for short, full in ABILITY_ALIASES.items()}
70
+ spec = CheckSpec(
71
+ kind=req.kind,
72
+ ability_scores=ability_scores,
73
+ proficient_skills=req.proficient_skills,
74
+ proficient_saves=tuple(full_ability(s) for s in req.proficient_saves),
75
+ proficiency_bonus=req.proficiency_bonus,
76
+ skill=req.skill,
77
+ ability=full_ability(req.ability) if req.ability else None,
78
+ dc=req.dc,
79
+ advantage=req.advantage,
80
+ disadvantage=req.disadvantage,
81
+ )
82
+ random.seed(seed)
83
+ try:
84
+ result = resolve_check(spec)
85
+ except ValueError as exc:
86
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
87
+
88
+ body = dataclasses.asdict(result)
89
+ body["seed"] = seed
90
+ body["summary"] = _check_summary(result)
91
+ return body
92
+
93
+
94
+ def _do_rest_short(req: _ShortRestRequest) -> dict[str, Any]:
95
+ seed = resolve_seed(req.seed)
96
+ pool = HitDicePool(
97
+ hit_die_size=req.hit_die_size,
98
+ dice_remaining=req.dice_remaining,
99
+ dice_total=req.dice_total,
100
+ )
101
+ rng = random.Random(seed)
102
+ try:
103
+ outcome = resolve_short_rest(pool, req.dice_to_spend, req.con_modifier, rng=rng)
104
+ except ValueError as exc:
105
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
106
+
107
+ hp_current = min(req.hp_current + outcome.healed, req.hp_max)
108
+ return {
109
+ "healed": outcome.healed,
110
+ "dice_spent": outcome.dice_spent,
111
+ "hp_current": hp_current,
112
+ "dice_remaining": outcome.dice_remaining,
113
+ "seed": seed,
114
+ }
115
+
116
+
117
+ def _do_rest_long(req: _LongRestRequest) -> dict[str, Any]:
118
+ seed = resolve_seed(req.seed)
119
+ pool = HitDicePool(
120
+ hit_die_size=req.hit_die_size,
121
+ dice_remaining=req.dice_remaining,
122
+ dice_total=req.dice_total,
123
+ )
124
+ outcome = resolve_long_rest(pool, req.hp_current, req.hp_max)
125
+ return {
126
+ "healed": outcome.healed,
127
+ "dice_spent": outcome.dice_spent,
128
+ "hp_current": outcome.hp_current,
129
+ "dice_remaining": outcome.dice_remaining,
130
+ "seed": seed,
131
+ }
132
+
133
+
134
+ class _RollRequest(BaseModel):
135
+ dice: str
136
+ seed: int | None = None
137
+
138
+
139
+ class _CheckRequest(BaseModel):
140
+ kind: Literal["skill", "ability", "saving_throw"]
141
+ ability: str | None = None
142
+ skill: str | None = None
143
+ dc: int | None = None
144
+ ability_scores: AbilityScoresModel = Field(default_factory=lambda: AbilityScoresModel())
145
+ proficient_skills: tuple[str, ...] = ()
146
+ proficient_saves: tuple[str, ...] = ()
147
+ proficiency_bonus: int = 0
148
+ advantage: bool = False
149
+ disadvantage: bool = False
150
+ seed: int | None = None
151
+
152
+
153
+ class _ShortRestRequest(BaseModel):
154
+ hit_die_size: int
155
+ dice_remaining: int
156
+ dice_total: int
157
+ dice_to_spend: int
158
+ con_modifier: int
159
+ hp_current: int
160
+ hp_max: int
161
+ seed: int | None = None
162
+
163
+
164
+ class _LongRestRequest(BaseModel):
165
+ hit_die_size: int
166
+ dice_remaining: int
167
+ dice_total: int
168
+ hp_current: int
169
+ hp_max: int
170
+ seed: int | None = None
171
+
172
+
173
+ def create_app(state: BridgeState) -> FastAPI:
174
+ app = FastAPI(title="nat20-bridge", version=__version__)
175
+ # The ST extension fetches cross-origin from the SillyTavern page; the
176
+ # bridge binds loopback so permissive CORS is acceptable here.
177
+ app.add_middleware(
178
+ CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"]
179
+ )
180
+
181
+ # Homebrew overlay is installed ONCE here, at app creation, over the
182
+ # engine's module-global lib loader singleton (`configure_lib_loader`).
183
+ # `combat` routes (routes_combat.py) resolve monsters/spells/weapons
184
+ # through this same overlay via `state.loader`; Task 10's homebrew
185
+ # mutation routes call `state.refresh_loader()` to rebuild the overlay's
186
+ # in-memory layer after an add/remove without restarting the process.
187
+ store = HomebrewStore(state.homebrew_path)
188
+ state.homebrew_store = store
189
+
190
+ def _refresh_loader() -> None:
191
+ loader = OverlayAssetLoader(base=BundledAssetLoader(), overlay=store.as_memory_loader())
192
+ state.loader = loader
193
+ configure_lib_loader(loader)
194
+
195
+ state.refresh_loader = _refresh_loader
196
+ _refresh_loader()
197
+
198
+ @app.get("/v1/health")
199
+ def health() -> dict[str, str]:
200
+ return {
201
+ "bridge": __version__,
202
+ "engine": version("dnd5e-engine"),
203
+ "data": version("dnd5e-srd-data"),
204
+ }
205
+
206
+ @app.post("/v1/party/validate")
207
+ def party_validate(req: PartyValidateRequest) -> dict[str, Any]:
208
+ entity_id = req.entity_id or f"char:{slugify(req.name)}"
209
+ assert state.loader is not None
210
+ try:
211
+ build_spec = make_build_spec(
212
+ species_slug=req.build.species_slug,
213
+ class_slug=req.build.class_slug,
214
+ level=req.build.level,
215
+ subclass_slug=req.build.subclass_slug,
216
+ ability_scores=req.build.ability_scores.model_dump(by_alias=True),
217
+ equipment=req.build.equipment,
218
+ )
219
+ member = derive_sheet(
220
+ build_spec,
221
+ name=req.name,
222
+ entity_id=entity_id,
223
+ loader=state.loader,
224
+ hp_current=req.hp_current,
225
+ spells_known=req.spells_known,
226
+ )
227
+ except ValueError as exc:
228
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
229
+
230
+ slots = ",".join(f"{lvl}:{count}" for lvl, count in member.spell_slots.items())
231
+ summary = (
232
+ f"{member.name} — lvl {member.character_level} {member.species_slug} "
233
+ f"{member.class_slug}, HP {member.hp_current}/{member.hp_max}, "
234
+ f"AC {member.ac}, slots {{{slots}}}"
235
+ )
236
+ return {"member": member.model_dump(), "summary": summary}
237
+
238
+ @app.post("/v1/roll")
239
+ def roll(req: _RollRequest) -> dict[str, Any]:
240
+ return _do_roll(req)
241
+
242
+ @app.post("/v1/check")
243
+ def check(req: _CheckRequest) -> dict[str, Any]:
244
+ return _do_check(req)
245
+
246
+ @app.post("/v1/rest/short")
247
+ def rest_short(req: _ShortRestRequest) -> dict[str, Any]:
248
+ return _do_rest_short(req)
249
+
250
+ @app.post("/v1/rest/long")
251
+ def rest_long(req: _LongRestRequest) -> dict[str, Any]:
252
+ return _do_rest_long(req)
253
+
254
+ app.include_router(build_combat_router(state))
255
+ app.include_router(build_content_router(state))
256
+
257
+ return app
@@ -0,0 +1,25 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ from pathlib import Path
5
+
6
+ import uvicorn
7
+
8
+ from nat20_bridge.app import create_app
9
+ from nat20_bridge.state import BridgeState
10
+
11
+
12
+ def main() -> None:
13
+ parser = argparse.ArgumentParser(prog="nat20-bridge")
14
+ parser.add_argument("--host", default="127.0.0.1")
15
+ parser.add_argument("--port", type=int, default=8020)
16
+ parser.add_argument(
17
+ "--data-dir",
18
+ type=Path,
19
+ default=Path.home() / ".nat20-bridge",
20
+ help="where homebrew.json persists",
21
+ )
22
+ args = parser.parse_args()
23
+ args.data_dir.mkdir(parents=True, exist_ok=True)
24
+ app = create_app(BridgeState(homebrew_path=args.data_dir / "homebrew.json"))
25
+ uvicorn.run(app, host=args.host, port=args.port) # pragma: no cover
@@ -0,0 +1,94 @@
1
+ """forge_item — compact weapon recipes → schema-valid, round-trippable raw dicts.
2
+
3
+ Takes a canonical weapon base slug plus a small set of overrides (name,
4
+ magical bonus, one extra damage part) and produces a raw dict shaped exactly
5
+ like the ones :class:`~nat20_bridge.homebrew.HomebrewStore` persists — i.e.
6
+ ``json.loads(Weapon.model_dump_json())`` — so callers can hand the result
7
+ straight to ``HomebrewStore.add("items", raw)``.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import re
14
+ from typing import TYPE_CHECKING, Any
15
+
16
+ from dnd5e_srd_data.schema.common import DamagePart
17
+ from dnd5e_srd_data.schema.item import Weapon
18
+ from pydantic import ValidationError
19
+
20
+ if TYPE_CHECKING:
21
+ from dnd5e_srd_data.loader import AssetLoader
22
+
23
+ _EXTRA_DAMAGE_RE = re.compile(r"^(\d+d\d+(?:[+-]\d+)?):([a-z]+)$")
24
+
25
+ _SLUG_SANITIZE_RE = re.compile(r"[^a-z0-9]+")
26
+
27
+ _HB_PREFIX = "hb-"
28
+
29
+
30
+ class ForgeError(Exception):
31
+ """Raised when a forge recipe is invalid (unknown base, malformed damage, ...)."""
32
+
33
+
34
+ def _slugify(name: str) -> str:
35
+ sanitized = _SLUG_SANITIZE_RE.sub("-", name.strip().lower()).strip("-")
36
+ if not sanitized:
37
+ raise ForgeError(f"name {name!r} does not yield a usable slug")
38
+ return f"{_HB_PREFIX}{sanitized}"
39
+
40
+
41
+ def _parse_extra_damage(extra_damage: str) -> DamagePart:
42
+ match = _EXTRA_DAMAGE_RE.match(extra_damage)
43
+ if match is None:
44
+ raise ForgeError(
45
+ f"malformed extra_damage {extra_damage!r}; expected format 'NdM[+/-B]:type'"
46
+ )
47
+ dice, damage_type = match.groups()
48
+ return DamagePart(dice=dice, damage_type=damage_type)
49
+
50
+
51
+ def forge_item(
52
+ *,
53
+ name: str,
54
+ base: str,
55
+ loader: AssetLoader,
56
+ bonus: int = 0,
57
+ extra_damage: str | None = None,
58
+ ) -> dict[str, Any]:
59
+ """Build a raw, schema-valid weapon dict from a canonical base weapon.
60
+
61
+ Raises:
62
+ ForgeError: ``base`` is not a known weapon slug, or ``extra_damage``
63
+ doesn't match the ``"NdM[+/-B]:type"`` format.
64
+ """
65
+ weapon = loader.get_weapon(base)
66
+ if weapon is None:
67
+ raise ForgeError(f"unknown weapon base slug {base!r}")
68
+
69
+ damage_parts = list(weapon.damage_parts)
70
+ if extra_damage is not None:
71
+ damage_parts.append(_parse_extra_damage(extra_damage))
72
+
73
+ slug = _slugify(name)
74
+ try:
75
+ new_weapon = weapon.model_copy(
76
+ update={
77
+ "slug": slug,
78
+ "name": name,
79
+ "magical_bonus": weapon.magical_bonus + bonus,
80
+ "damage_parts": damage_parts,
81
+ }
82
+ )
83
+ dumped: dict[str, Any] = json.loads(new_weapon.model_dump_json())
84
+ # ``model_copy(update=...)`` and ``model_dump_json`` don't re-validate
85
+ # constrained fields (e.g. ``magical_bonus: NonNegativeInt``), so a
86
+ # negative ``bonus`` would otherwise silently produce an
87
+ # out-of-schema dict that only blows up later (as an uncaught
88
+ # ``ValidationError`` -> 500) when ``HomebrewStore.add`` validates
89
+ # it. Re-validate here so bad recipes fail as ``ForgeError`` (-> 422)
90
+ # at the source.
91
+ Weapon.model_validate(dumped)
92
+ except ValidationError as exc:
93
+ raise ForgeError(f"invalid forged item: {exc}") from exc
94
+ return dumped