react-router-routes 0.2.0__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.
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
Metadata-Version: 2.3
|
|
2
|
+
Name: react-router-routes
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Generate strongly-typed Python helpers (TypedDict param classes + path/url builders) from a React Router v6+ route tree so Python code can build frontend URLs safely.
|
|
5
|
+
Keywords: react-router,router,routes,url-generation,typed-routes,typed,cli,backend,frontend,integration
|
|
6
|
+
Author: Michael Bianco
|
|
7
|
+
Author-email: Michael Bianco <mike@mikebian.co>
|
|
8
|
+
Requires-Dist: typer>=0.12.5
|
|
9
|
+
Requires-Dist: jinja2>=3.1.4
|
|
10
|
+
Requires-Python: >=3.11
|
|
11
|
+
Project-URL: Repository, https://github.com/iloveitaly/react-router-routes
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
|
|
14
|
+
# Generate Typed Python URL helpers from React Router routes
|
|
15
|
+
|
|
16
|
+
Generate strongly-typed Python helpers (TypedDict param objects + overloads) from a React Router v6+ route tree. This is useful when a Python backend, worker, or test suite needs to construct URLs that stay in sync with a JavaScript/TypeScript frontend using React Router.
|
|
17
|
+
|
|
18
|
+
## What you get
|
|
19
|
+
|
|
20
|
+
Given a React Router project, the CLI either:
|
|
21
|
+
|
|
22
|
+
* Runs `pnpm react-router routes --json` (if you pass `--directory`), or
|
|
23
|
+
* Reads a pre-generated JSON file (if you pass `--json-file`)
|
|
24
|
+
|
|
25
|
+
It walks the returned route objects and produces a Python module containing:
|
|
26
|
+
|
|
27
|
+
* `RoutePaths` Literal of every concrete route pattern (e.g. `/users/:userId?`, `/files/*`).
|
|
28
|
+
* Per-route `TypedDict` classes containing snake_case parameter keys.
|
|
29
|
+
* Overloaded `react_router_path()` to build a relative path with validation + percent-encoding.
|
|
30
|
+
* Overloaded `react_router_url()` to prepend a base URL (explicit argument or `BASE_URL` env var).
|
|
31
|
+
|
|
32
|
+
## Installation
|
|
33
|
+
|
|
34
|
+
Requires Python 3.11+.
|
|
35
|
+
|
|
36
|
+
Using uv (recommended):
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
uv add react-router-routes
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Or with pip:
|
|
43
|
+
|
|
44
|
+
```bash
|
|
45
|
+
pip install react-router-routes
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
## Prerequisites
|
|
49
|
+
|
|
50
|
+
Your JS project must have `react-router` and the `pnpm react-router routes --json` command available (React Router v6+ data APIs). The Python process must run inside (or have access to) that project directory so the CLI can execute the command.
|
|
51
|
+
|
|
52
|
+
## CLI Usage
|
|
53
|
+
|
|
54
|
+
The script entry point is named `react-router-routes` (see `pyproject.toml`).
|
|
55
|
+
|
|
56
|
+
Two ways to supply routes:
|
|
57
|
+
|
|
58
|
+
1. Have the tool invoke `pnpm react-router routes --json` by providing a directory:
|
|
59
|
+
|
|
60
|
+
```bash
|
|
61
|
+
react-router-routes ./routes_typing.py --directory ./frontend
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
1. Provide an existing JSON file (output of `pnpm react-router routes --json`):
|
|
65
|
+
|
|
66
|
+
```bash
|
|
67
|
+
react-router-routes ./routes_typing.py --json-file tests/react-router.json
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
Then import the generated module in Python code:
|
|
71
|
+
|
|
72
|
+
```python
|
|
73
|
+
from routes_typing import react_router_path, react_router_url, RoutePaths
|
|
74
|
+
|
|
75
|
+
react_router_path('/users/:userId', {'user_id': 123}) # -> '/users/123'
|
|
76
|
+
react_router_url('/files/*', {'splat': 'docs/readme.md'}, base_url='https://example.com')
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
## Environment Variables
|
|
81
|
+
|
|
82
|
+
* `BASE_URL` (optional) – If set and you omit `base_url` when calling `react_router_url`, this value is prepended. If missing the function returns the path and logs a warning.
|
|
83
|
+
* `LOG_LEVEL` (optional) – Standard Python logging level (INFO, DEBUG, etc.).
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
## Development
|
|
87
|
+
|
|
88
|
+
Clone and install dev deps:
|
|
89
|
+
|
|
90
|
+
```bash
|
|
91
|
+
uv sync --group dev
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
Run tests:
|
|
95
|
+
|
|
96
|
+
```bash
|
|
97
|
+
uv run pytest
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
## Release process
|
|
102
|
+
|
|
103
|
+
This project uses `uv` for building and publishing. Adjust version in `pyproject.toml`, then build and publish as desired.
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
## License
|
|
107
|
+
|
|
108
|
+
MIT (see repository).
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
# Generate Typed Python URL helpers from React Router routes
|
|
2
|
+
|
|
3
|
+
Generate strongly-typed Python helpers (TypedDict param objects + overloads) from a React Router v6+ route tree. This is useful when a Python backend, worker, or test suite needs to construct URLs that stay in sync with a JavaScript/TypeScript frontend using React Router.
|
|
4
|
+
|
|
5
|
+
## What you get
|
|
6
|
+
|
|
7
|
+
Given a React Router project, the CLI either:
|
|
8
|
+
|
|
9
|
+
* Runs `pnpm react-router routes --json` (if you pass `--directory`), or
|
|
10
|
+
* Reads a pre-generated JSON file (if you pass `--json-file`)
|
|
11
|
+
|
|
12
|
+
It walks the returned route objects and produces a Python module containing:
|
|
13
|
+
|
|
14
|
+
* `RoutePaths` Literal of every concrete route pattern (e.g. `/users/:userId?`, `/files/*`).
|
|
15
|
+
* Per-route `TypedDict` classes containing snake_case parameter keys.
|
|
16
|
+
* Overloaded `react_router_path()` to build a relative path with validation + percent-encoding.
|
|
17
|
+
* Overloaded `react_router_url()` to prepend a base URL (explicit argument or `BASE_URL` env var).
|
|
18
|
+
|
|
19
|
+
## Installation
|
|
20
|
+
|
|
21
|
+
Requires Python 3.11+.
|
|
22
|
+
|
|
23
|
+
Using uv (recommended):
|
|
24
|
+
|
|
25
|
+
```bash
|
|
26
|
+
uv add react-router-routes
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Or with pip:
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
pip install react-router-routes
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## Prerequisites
|
|
36
|
+
|
|
37
|
+
Your JS project must have `react-router` and the `pnpm react-router routes --json` command available (React Router v6+ data APIs). The Python process must run inside (or have access to) that project directory so the CLI can execute the command.
|
|
38
|
+
|
|
39
|
+
## CLI Usage
|
|
40
|
+
|
|
41
|
+
The script entry point is named `react-router-routes` (see `pyproject.toml`).
|
|
42
|
+
|
|
43
|
+
Two ways to supply routes:
|
|
44
|
+
|
|
45
|
+
1. Have the tool invoke `pnpm react-router routes --json` by providing a directory:
|
|
46
|
+
|
|
47
|
+
```bash
|
|
48
|
+
react-router-routes ./routes_typing.py --directory ./frontend
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
1. Provide an existing JSON file (output of `pnpm react-router routes --json`):
|
|
52
|
+
|
|
53
|
+
```bash
|
|
54
|
+
react-router-routes ./routes_typing.py --json-file tests/react-router.json
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
Then import the generated module in Python code:
|
|
58
|
+
|
|
59
|
+
```python
|
|
60
|
+
from routes_typing import react_router_path, react_router_url, RoutePaths
|
|
61
|
+
|
|
62
|
+
react_router_path('/users/:userId', {'user_id': 123}) # -> '/users/123'
|
|
63
|
+
react_router_url('/files/*', {'splat': 'docs/readme.md'}, base_url='https://example.com')
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
## Environment Variables
|
|
68
|
+
|
|
69
|
+
* `BASE_URL` (optional) – If set and you omit `base_url` when calling `react_router_url`, this value is prepended. If missing the function returns the path and logs a warning.
|
|
70
|
+
* `LOG_LEVEL` (optional) – Standard Python logging level (INFO, DEBUG, etc.).
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
## Development
|
|
74
|
+
|
|
75
|
+
Clone and install dev deps:
|
|
76
|
+
|
|
77
|
+
```bash
|
|
78
|
+
uv sync --group dev
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
Run tests:
|
|
82
|
+
|
|
83
|
+
```bash
|
|
84
|
+
uv run pytest
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
## Release process
|
|
89
|
+
|
|
90
|
+
This project uses `uv` for building and publishing. Adjust version in `pyproject.toml`, then build and publish as desired.
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
## License
|
|
94
|
+
|
|
95
|
+
MIT (see repository).
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "react-router-routes"
|
|
3
|
+
version = "0.2.0"
|
|
4
|
+
description = "Generate strongly-typed Python helpers (TypedDict param classes + path/url builders) from a React Router v6+ route tree so Python code can build frontend URLs safely."
|
|
5
|
+
keywords = [
|
|
6
|
+
"react-router",
|
|
7
|
+
"router",
|
|
8
|
+
"routes",
|
|
9
|
+
"url-generation",
|
|
10
|
+
"typed-routes",
|
|
11
|
+
"typed",
|
|
12
|
+
"cli",
|
|
13
|
+
"backend",
|
|
14
|
+
"frontend",
|
|
15
|
+
"integration",
|
|
16
|
+
]
|
|
17
|
+
readme = "README.md"
|
|
18
|
+
requires-python = ">=3.11"
|
|
19
|
+
dependencies = ["typer>=0.12.5", "jinja2>=3.1.4"]
|
|
20
|
+
authors = [{ name = "Michael Bianco", email = "mike@mikebian.co" }]
|
|
21
|
+
urls = { "Repository" = "https://github.com/iloveitaly/react-router-routes" }
|
|
22
|
+
|
|
23
|
+
# additional packaging information: https://packaging.python.org/en/latest/specifications/core-metadata/#license
|
|
24
|
+
[project.scripts]
|
|
25
|
+
react-router-routes = "react_router_routes:main"
|
|
26
|
+
|
|
27
|
+
[build-system]
|
|
28
|
+
requires = ["uv_build>=0.8.11,<0.9.0"]
|
|
29
|
+
build-backend = "uv_build"
|
|
30
|
+
|
|
31
|
+
[tool.uv.build-backend]
|
|
32
|
+
# avoids the src/ directory structure
|
|
33
|
+
module-root = ""
|
|
34
|
+
|
|
35
|
+
[dependency-groups]
|
|
36
|
+
dev = ["pytest>=8.3.3"]
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"""Package entrypoint for the react-router-routes CLI.
|
|
2
|
+
|
|
3
|
+
Running the installed script (configured via [project.scripts]) will
|
|
4
|
+
invoke Typer's CLI defined in `generate.py`.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import logging
|
|
8
|
+
import os
|
|
9
|
+
|
|
10
|
+
from .generate import app
|
|
11
|
+
|
|
12
|
+
logging.basicConfig(
|
|
13
|
+
level=os.environ.get("LOG_LEVEL", "INFO").upper(),
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
logger = logging.getLogger(__name__)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def main() -> None: # console_scripts entry point
|
|
20
|
+
"""Dispatch to the Typer application.
|
|
21
|
+
|
|
22
|
+
Example:
|
|
23
|
+
react-router-routes generate-route-types ./js-app ./routes_typing.py
|
|
24
|
+
"""
|
|
25
|
+
app()
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
__all__ = ["main", "app"]
|
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
"""
|
|
2
|
+
py app/lib/react_router_generate.py web/ ./react_router_routes.py
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import re
|
|
7
|
+
import subprocess
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
import typer
|
|
11
|
+
from jinja2 import Environment
|
|
12
|
+
|
|
13
|
+
app = typer.Typer()
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def collect_route_patterns(routes: list[dict], parent_path: str = "") -> list[str]:
|
|
17
|
+
patterns: list[str] = []
|
|
18
|
+
for route in routes:
|
|
19
|
+
# Clean up path by collapsing repeated slashes and removing trailing slashes
|
|
20
|
+
raw = f"{parent_path}/{route.get('path', '')}"
|
|
21
|
+
current_path = re.sub(r"/{2,}", "/", raw).rstrip("/") or "/"
|
|
22
|
+
if "file" in route and ("path" in route or "index" in route):
|
|
23
|
+
patterns.append(current_path)
|
|
24
|
+
if "children" in route:
|
|
25
|
+
patterns.extend(collect_route_patterns(route["children"], current_path))
|
|
26
|
+
|
|
27
|
+
# De-duplicate while preserving order
|
|
28
|
+
deduped: list[str] = []
|
|
29
|
+
seen: set[str] = set()
|
|
30
|
+
for p in patterns:
|
|
31
|
+
if p not in seen:
|
|
32
|
+
seen.add(p)
|
|
33
|
+
deduped.append(p)
|
|
34
|
+
return deduped
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def camel_to_snake(name: str) -> str:
|
|
38
|
+
out: list[str] = []
|
|
39
|
+
for ch in name:
|
|
40
|
+
if ch.isupper():
|
|
41
|
+
if out:
|
|
42
|
+
out.append("_")
|
|
43
|
+
out.append(ch.lower())
|
|
44
|
+
else:
|
|
45
|
+
out.append(ch)
|
|
46
|
+
return "".join(out)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def segment_to_pascal(segment: str) -> str:
|
|
50
|
+
if not segment:
|
|
51
|
+
return ""
|
|
52
|
+
parts = re.split(r"[^A-Za-z0-9]+", segment)
|
|
53
|
+
return "".join(s[:1].upper() + s[1:] for s in parts if s)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def pattern_to_class_name(pattern: str) -> str:
|
|
57
|
+
if pattern == "/":
|
|
58
|
+
return "RootParams"
|
|
59
|
+
name_parts: list[str] = []
|
|
60
|
+
for seg in pattern.strip("/").split("/"):
|
|
61
|
+
if not seg:
|
|
62
|
+
continue
|
|
63
|
+
if seg == "*":
|
|
64
|
+
name_parts.append("Splat")
|
|
65
|
+
continue
|
|
66
|
+
if seg.startswith(":"):
|
|
67
|
+
token = seg.lstrip(":").rstrip("?")
|
|
68
|
+
name_parts.append(segment_to_pascal(token))
|
|
69
|
+
continue
|
|
70
|
+
name_parts.append(segment_to_pascal(seg))
|
|
71
|
+
base = "".join(name_parts) or "Root"
|
|
72
|
+
return f"{base}Params"
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def parse_params(pattern: str) -> tuple[list[tuple[str, bool]], bool]:
|
|
76
|
+
"""Return ([(param_name, is_optional)], has_splat). param_name is the token as written (camelCase)."""
|
|
77
|
+
params: list[tuple[str, bool]] = []
|
|
78
|
+
for m in re.finditer(r":([A-Za-z0-9_]+)(\?)?", pattern):
|
|
79
|
+
name = m.group(1)
|
|
80
|
+
is_optional = m.group(2) is not None
|
|
81
|
+
params.append((name, is_optional))
|
|
82
|
+
has_splat = "*" in pattern
|
|
83
|
+
return params, has_splat
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
JINJA_TEMPLATE = r'''
|
|
87
|
+
"""AUTOGENERATED FILE: Do not edit manually.
|
|
88
|
+
Generated by react-router-routes from the React Router config.
|
|
89
|
+
|
|
90
|
+
- RoutePaths is a Literal of route patterns
|
|
91
|
+
- Per-route TypedDicts define snake_case keys for params
|
|
92
|
+
- react_router_path builds a path from a pattern and params
|
|
93
|
+
- react_router_url prepends BASE_URL (env) or an explicit base_url
|
|
94
|
+
"""
|
|
95
|
+
from typing import Literal, overload, TypedDict, Mapping, NotRequired
|
|
96
|
+
import re
|
|
97
|
+
from urllib.parse import quote
|
|
98
|
+
import os
|
|
99
|
+
import logging
|
|
100
|
+
|
|
101
|
+
logger = logging.getLogger("react_router_routes.generated")
|
|
102
|
+
|
|
103
|
+
RoutePaths = Literal[{% for p in patterns %}{% if not loop.first %}, {% endif %}"{{ p }}"{% endfor %}]
|
|
104
|
+
|
|
105
|
+
{% for r in routes if r.params or r.has_splat %}
|
|
106
|
+
class {{ r.class_name }}(TypedDict):
|
|
107
|
+
{% if r.has_splat %}
|
|
108
|
+
splat: str
|
|
109
|
+
{% endif %}
|
|
110
|
+
{% for p in r.params %}
|
|
111
|
+
{{ p.snake }}: {% if p.optional %}NotRequired[str]{% else %}str{% endif %}
|
|
112
|
+
{% endfor %}
|
|
113
|
+
|
|
114
|
+
{% endfor %}
|
|
115
|
+
|
|
116
|
+
ALIAS_MAP: dict[str, dict[str, str]] = {
|
|
117
|
+
{% for r in routes if r.alias_map %}
|
|
118
|
+
"{{ r.pattern }}": {
|
|
119
|
+
{% for k,v in r.alias_map.items() %}"{{ k }}": "{{ v }}"{% if not loop.last %},
|
|
120
|
+
{% endif %}{% endfor %}
|
|
121
|
+
},
|
|
122
|
+
{% endfor %}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
# overloads for path
|
|
126
|
+
{% for r in routes %}
|
|
127
|
+
{% if r.params or r.has_splat %}
|
|
128
|
+
@overload
|
|
129
|
+
def react_router_path(path: Literal["{{ r.pattern }}"], params: {{ r.class_name }}, /) -> str: ...
|
|
130
|
+
@overload
|
|
131
|
+
def react_router_path(path: Literal["{{ r.pattern }}"], params: Mapping[str, object], /) -> str: ...
|
|
132
|
+
{% else %}
|
|
133
|
+
@overload
|
|
134
|
+
def react_router_path(path: Literal["{{ r.pattern }}"], params: None | Mapping[str, object] = None, /) -> str: ...
|
|
135
|
+
{% endif %}
|
|
136
|
+
{% endfor %}
|
|
137
|
+
@overload
|
|
138
|
+
def react_router_path(path: RoutePaths, params: None | Mapping[str, object] = None, /) -> str: ...
|
|
139
|
+
|
|
140
|
+
def react_router_path(path: RoutePaths, params: Mapping[str, object] | None = None) -> str:
|
|
141
|
+
"""Render a URL path from a typed pattern and params.
|
|
142
|
+
|
|
143
|
+
- Accepts snake_case or original token keys (via ALIAS_MAP)
|
|
144
|
+
- Replaces required ":name" and optional ":name?" tokens
|
|
145
|
+
- Replaces "*" with the "splat" param
|
|
146
|
+
- Percent-encodes values (splat keeps "/")
|
|
147
|
+
"""
|
|
148
|
+
values: dict[str, object] = {} if params is None else dict(params)
|
|
149
|
+
alias = ALIAS_MAP.get(path, {})
|
|
150
|
+
# accept both snake_case and original token keys
|
|
151
|
+
for k, v in list(values.items()):
|
|
152
|
+
if k in alias:
|
|
153
|
+
values[alias[k]] = v
|
|
154
|
+
|
|
155
|
+
rendered = path
|
|
156
|
+
|
|
157
|
+
def _replace_optional(match: re.Match[str]) -> str:
|
|
158
|
+
name = match.group(1)
|
|
159
|
+
if name in values:
|
|
160
|
+
return quote(str(values[name]), safe="")
|
|
161
|
+
return ""
|
|
162
|
+
|
|
163
|
+
rendered = re.sub(r":([A-Za-z0-9_]+)\?", _replace_optional, rendered)
|
|
164
|
+
|
|
165
|
+
def _replace_required(match: re.Match[str]) -> str:
|
|
166
|
+
name = match.group(1)
|
|
167
|
+
assert name in values, f"missing required param: {name}"
|
|
168
|
+
return quote(str(values[name]), safe="")
|
|
169
|
+
|
|
170
|
+
rendered = re.sub(r":([A-Za-z0-9_]+)(?!\?)", _replace_required, rendered)
|
|
171
|
+
|
|
172
|
+
if "*" in rendered:
|
|
173
|
+
assert "splat" in values, "missing required param: splat"
|
|
174
|
+
rendered = rendered.replace("*", quote(str(values["splat"]), safe="/"))
|
|
175
|
+
|
|
176
|
+
rendered = re.sub(r"/{2,}", "/", rendered)
|
|
177
|
+
if rendered != "/" and rendered.endswith("/"):
|
|
178
|
+
rendered = rendered[:-1]
|
|
179
|
+
return rendered
|
|
180
|
+
|
|
181
|
+
# overloads for url
|
|
182
|
+
{% for r in routes %}
|
|
183
|
+
{% if r.params or r.has_splat %}
|
|
184
|
+
@overload
|
|
185
|
+
def react_router_url(path: Literal["{{ r.pattern }}"], params: {{ r.class_name }}, base_url: str | None = None, /) -> str: ...
|
|
186
|
+
@overload
|
|
187
|
+
def react_router_url(path: Literal["{{ r.pattern }}"], params: Mapping[str, object], base_url: str | None = None, /) -> str: ...
|
|
188
|
+
{% else %}
|
|
189
|
+
@overload
|
|
190
|
+
def react_router_url(path: Literal["{{ r.pattern }}"], params: None | Mapping[str, object] = None, base_url: str | None = None, /) -> str: ...
|
|
191
|
+
{% endif %}
|
|
192
|
+
{% endfor %}
|
|
193
|
+
@overload
|
|
194
|
+
def react_router_url(path: RoutePaths, params: None | Mapping[str, object] = None, base_url: str | None = None, /) -> str: ...
|
|
195
|
+
|
|
196
|
+
def react_router_url(path: RoutePaths, params: Mapping[str, object] | None = None, base_url: str | None = None) -> str:
|
|
197
|
+
"""Build a full URL by prepending base_url or ENV BASE_URL to the path."""
|
|
198
|
+
built = react_router_path(path, params)
|
|
199
|
+
base = base_url if base_url is not None else os.environ.get("BASE_URL")
|
|
200
|
+
if not base:
|
|
201
|
+
logger.warning("BASE_URL missing; returning path only: %s", path)
|
|
202
|
+
return built
|
|
203
|
+
|
|
204
|
+
return base.rstrip("/") + built
|
|
205
|
+
'''
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def render_routes_module(patterns: list[str]) -> str:
|
|
209
|
+
# Build context for Jinja
|
|
210
|
+
routes = []
|
|
211
|
+
for pattern in patterns:
|
|
212
|
+
params, has_splat = parse_params(pattern)
|
|
213
|
+
route = {
|
|
214
|
+
"pattern": pattern,
|
|
215
|
+
"class_name": pattern_to_class_name(pattern),
|
|
216
|
+
"has_splat": has_splat,
|
|
217
|
+
"params": [
|
|
218
|
+
{
|
|
219
|
+
"name": token,
|
|
220
|
+
"snake": camel_to_snake(token),
|
|
221
|
+
"optional": is_optional,
|
|
222
|
+
}
|
|
223
|
+
for token, is_optional in params
|
|
224
|
+
],
|
|
225
|
+
"alias_map": {camel_to_snake(token): token for token, _ in params},
|
|
226
|
+
}
|
|
227
|
+
routes.append(route)
|
|
228
|
+
|
|
229
|
+
env = Environment()
|
|
230
|
+
template = env.from_string(JINJA_TEMPLATE)
|
|
231
|
+
return template.render(patterns=patterns, routes=routes) + "\n"
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
@app.command()
|
|
235
|
+
def generate_route_types(
|
|
236
|
+
output_file: Path = typer.Argument(
|
|
237
|
+
..., help="Path to output routes_typing.py file"
|
|
238
|
+
),
|
|
239
|
+
directory: Path | None = typer.Option(
|
|
240
|
+
None,
|
|
241
|
+
"--directory",
|
|
242
|
+
"-d",
|
|
243
|
+
help="Path to React Router project directory (used to invoke 'pnpm react-router routes --json')",
|
|
244
|
+
),
|
|
245
|
+
json_file: Path | None = typer.Option(
|
|
246
|
+
None,
|
|
247
|
+
"--json-file",
|
|
248
|
+
"-j",
|
|
249
|
+
help="Path to an existing react-router routes JSON file (skips invoking pnpm)",
|
|
250
|
+
),
|
|
251
|
+
):
|
|
252
|
+
"""Generate Python route typings and helpers from React Router routes.
|
|
253
|
+
|
|
254
|
+
You must supply either --json-file or --directory. If both are supplied, --json-file wins.
|
|
255
|
+
"""
|
|
256
|
+
|
|
257
|
+
if json_file is None and directory is None:
|
|
258
|
+
raise typer.BadParameter("Provide either --json-file or --directory")
|
|
259
|
+
|
|
260
|
+
if json_file is not None:
|
|
261
|
+
routes_json = json.loads(json_file.read_text())
|
|
262
|
+
else:
|
|
263
|
+
# Fallback to invoking the CLI
|
|
264
|
+
result = subprocess.run(
|
|
265
|
+
["pnpm", "react-router", "routes", "--json"],
|
|
266
|
+
cwd=directory,
|
|
267
|
+
capture_output=True,
|
|
268
|
+
text=True,
|
|
269
|
+
)
|
|
270
|
+
|
|
271
|
+
if result.returncode != 0:
|
|
272
|
+
typer.echo(f"Error running react-router: {result.stderr}")
|
|
273
|
+
raise typer.Exit(1)
|
|
274
|
+
routes_json = json.loads(result.stdout)
|
|
275
|
+
|
|
276
|
+
patterns = collect_route_patterns(routes_json)
|
|
277
|
+
content = render_routes_module(patterns)
|
|
278
|
+
output_file.write_text(content)
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
if __name__ == "__main__":
|
|
282
|
+
app()
|