jongo 0.2.3__tar.gz → 0.4.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.
- {jongo-0.2.3 → jongo-0.4.0}/PKG-INFO +102 -3
- {jongo-0.2.3 → jongo-0.4.0}/README.md +98 -2
- {jongo-0.2.3 → jongo-0.4.0}/jongo/__init__.py +6 -2
- {jongo-0.2.3 → jongo-0.4.0}/jongo/app.py +50 -4
- {jongo-0.2.3 → jongo-0.4.0}/jongo/cli.py +62 -1
- {jongo-0.2.3 → jongo-0.4.0}/jongo/compiler/bundle.py +1 -0
- {jongo-0.2.3 → jongo-0.4.0}/jongo/compiler/dom.js +100 -0
- {jongo-0.2.3 → jongo-0.4.0}/jongo/compiler/pyrt.js +55 -17
- {jongo-0.2.3 → jongo-0.4.0}/jongo/compiler/transpile.py +2 -1
- {jongo-0.2.3 → jongo-0.4.0}/jongo/db/__init__.py +8 -3
- {jongo-0.2.3 → jongo-0.4.0}/jongo/db/connection.py +162 -31
- jongo-0.4.0/jongo/db/dialect.py +243 -0
- {jongo-0.2.3 → jongo-0.4.0}/jongo/db/migrate.py +197 -11
- {jongo-0.2.3 → jongo-0.4.0}/jongo/db/models.py +11 -5
- {jongo-0.2.3 → jongo-0.4.0}/jongo/db/query.py +76 -34
- jongo-0.4.0/jongo/introspect.py +505 -0
- jongo-0.4.0/jongo/live.py +234 -0
- {jongo-0.2.3 → jongo-0.4.0}/jongo/rpc.py +47 -1
- jongo-0.4.0/jongo/scaffold/AGENTS.md.tmpl +31 -0
- jongo-0.4.0/jongo/scaffold/CLAUDE.md.tmpl +1 -0
- {jongo-0.2.3 → jongo-0.4.0}/jongo/testing.py +23 -1
- {jongo-0.2.3 → jongo-0.4.0}/jongo/vdom.py +183 -55
- {jongo-0.2.3 → jongo-0.4.0}/jongo.egg-info/PKG-INFO +102 -3
- {jongo-0.2.3 → jongo-0.4.0}/jongo.egg-info/SOURCES.txt +12 -0
- jongo-0.4.0/jongo.egg-info/requires.txt +3 -0
- {jongo-0.2.3 → jongo-0.4.0}/pyproject.toml +6 -1
- jongo-0.4.0/tests/test_agentic.py +231 -0
- {jongo-0.2.3 → jongo-0.4.0}/tests/test_app.py +27 -0
- {jongo-0.2.3 → jongo-0.4.0}/tests/test_compiler.py +81 -0
- {jongo-0.2.3 → jongo-0.4.0}/tests/test_db.py +79 -29
- jongo-0.4.0/tests/test_docs_site.py +71 -0
- jongo-0.4.0/tests/test_guide_api.py +343 -0
- jongo-0.4.0/tests/test_live.py +287 -0
- jongo-0.4.0/tests/test_patterns.py +65 -0
- jongo-0.4.0/tests/test_postgres.py +220 -0
- {jongo-0.2.3 → jongo-0.4.0}/tests/test_stress_fixes.py +3 -1
- {jongo-0.2.3 → jongo-0.4.0}/tests/test_stress_fixes_022.py +3 -1
- {jongo-0.2.3 → jongo-0.4.0}/LICENSE +0 -0
- {jongo-0.2.3 → jongo-0.4.0}/jongo/__main__.py +0 -0
- {jongo-0.2.3 → jongo-0.4.0}/jongo/admin.py +0 -0
- {jongo-0.2.3 → jongo-0.4.0}/jongo/auth.py +0 -0
- {jongo-0.2.3 → jongo-0.4.0}/jongo/compiler/__init__.py +0 -0
- {jongo-0.2.3 → jongo-0.4.0}/jongo/compiler/scope.py +0 -0
- {jongo-0.2.3 → jongo-0.4.0}/jongo/db/fields.py +0 -0
- {jongo-0.2.3 → jongo-0.4.0}/jongo/errors.py +0 -0
- {jongo-0.2.3 → jongo-0.4.0}/jongo/errors_page.py +0 -0
- {jongo-0.2.3 → jongo-0.4.0}/jongo/html.py +0 -0
- {jongo-0.2.3 → jongo-0.4.0}/jongo/http.py +0 -0
- {jongo-0.2.3 → jongo-0.4.0}/jongo/log.py +0 -0
- {jongo-0.2.3 → jongo-0.4.0}/jongo/routing.py +0 -0
- {jongo-0.2.3 → jongo-0.4.0}/jongo/scaffold/app.py.tmpl +0 -0
- {jongo-0.2.3 → jongo-0.4.0}/jongo/scaffold/dot-gitignore.tmpl +0 -0
- {jongo-0.2.3 → jongo-0.4.0}/jongo/server.py +0 -0
- {jongo-0.2.3 → jongo-0.4.0}/jongo/styles.py +0 -0
- {jongo-0.2.3 → jongo-0.4.0}/jongo.egg-info/dependency_links.txt +0 -0
- {jongo-0.2.3 → jongo-0.4.0}/jongo.egg-info/entry_points.txt +0 -0
- {jongo-0.2.3 → jongo-0.4.0}/jongo.egg-info/top_level.txt +0 -0
- {jongo-0.2.3 → jongo-0.4.0}/setup.cfg +0 -0
- {jongo-0.2.3 → jongo-0.4.0}/tests/test_admin.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: jongo
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.4.0
|
|
4
4
|
Summary: A full-stack Python web framework: routes, server code and reactive UI in one language.
|
|
5
5
|
Author: Joshua Harty
|
|
6
6
|
License: AGPL-3.0-or-later
|
|
@@ -19,6 +19,7 @@ Classifier: Programming Language :: Python :: 3.11
|
|
|
19
19
|
Classifier: Programming Language :: Python :: 3.12
|
|
20
20
|
Classifier: Programming Language :: Python :: 3.13
|
|
21
21
|
Classifier: Topic :: Database
|
|
22
|
+
Classifier: Topic :: Database :: Front-Ends
|
|
22
23
|
Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
|
|
23
24
|
Classifier: Topic :: Internet :: WWW/HTTP :: WSGI :: Application
|
|
24
25
|
Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
|
|
@@ -26,6 +27,8 @@ Classifier: Typing :: Typed
|
|
|
26
27
|
Requires-Python: >=3.10
|
|
27
28
|
Description-Content-Type: text/markdown
|
|
28
29
|
License-File: LICENSE
|
|
30
|
+
Provides-Extra: postgres
|
|
31
|
+
Requires-Dist: psycopg[binary]>=3.1; extra == "postgres"
|
|
29
32
|
Dynamic: license-file
|
|
30
33
|
|
|
31
34
|
# Jongo
|
|
@@ -84,6 +87,18 @@ def home():
|
|
|
84
87
|
jongo dev # → http://localhost:8000, reloads when you save
|
|
85
88
|
```
|
|
86
89
|
|
|
90
|
+
## Documentation
|
|
91
|
+
|
|
92
|
+
- **[The guide](docs/guide.md)** — the long version: the request model, routing, components,
|
|
93
|
+
every hook, server functions, the ORM, migrations, PostgreSQL, channels, auth, security,
|
|
94
|
+
testing, deployment, exactly what compiles to the browser, and a troubleshooting table.
|
|
95
|
+
- **[Patterns](examples/patterns/)** — thirteen complete, runnable apps: CRUD, auth, search
|
|
96
|
+
as you type, pagination, optimistic UI, live chat, a live dashboard, modals with server
|
|
97
|
+
validation, master-detail, uploads, background work, testing, deployment.
|
|
98
|
+
- **[Benchmarks](benchmarks/)** — against Django and FastAPI, with the harness and the
|
|
99
|
+
caveats.
|
|
100
|
+
- The docs site is itself a Jongo app: `jongo dev docs/docs_site.py --port 8790`.
|
|
101
|
+
|
|
87
102
|
## Why
|
|
88
103
|
|
|
89
104
|
In Django, one feature is spread across `models.py`, `urls.py`, `views.py`, a template, a form class and usually some JavaScript. In Jongo it's one idea in one place:
|
|
@@ -212,6 +227,41 @@ def rename(request, todo: Todo, title: str) -> dict: # `todo: Todo` loads the
|
|
|
212
227
|
- **Options:** `@server(login_required=True)`, `@server(admin_required=True)`, and `@server(refresh=True)` to re-run the page loader after each call.
|
|
213
228
|
- **Security:** every call is CSRF-protected. Only functions you decorate are exposed.
|
|
214
229
|
|
|
230
|
+
## Real-time
|
|
231
|
+
|
|
232
|
+
Push from a server function straight into a mounted component. Declare the channel, and
|
|
233
|
+
the declaring function authorises each subscription — an undeclared channel cannot be
|
|
234
|
+
subscribed to at all, the same rule that keeps undecorated functions off the RPC boundary.
|
|
235
|
+
|
|
236
|
+
```python
|
|
237
|
+
@app.channel("room:<int:id>")
|
|
238
|
+
def room(request, id):
|
|
239
|
+
return id in request.session.get("rooms", [])
|
|
240
|
+
|
|
241
|
+
@server
|
|
242
|
+
def post(request, room: int, text: str) -> dict:
|
|
243
|
+
message = Message.create(room_id=room, text=text).to_dict()
|
|
244
|
+
broadcast(f"room:{room}", message) # -> every subscribed browser
|
|
245
|
+
return message
|
|
246
|
+
|
|
247
|
+
@component
|
|
248
|
+
def Chat(room):
|
|
249
|
+
messages = state([])
|
|
250
|
+
live(f"room:{room}", lambda message: messages.set([*messages.value, message]))
|
|
251
|
+
return ul([li(m["text"], key=m["id"]) for m in messages.value])
|
|
252
|
+
```
|
|
253
|
+
|
|
254
|
+
`live()` is a hook like `state()` and `effect()`: the subscription opens when the component
|
|
255
|
+
mounts, moves when the channel changes, and closes when it unmounts. One SSE connection per
|
|
256
|
+
tab carries every channel the page asked for, and reconnects with backoff if it drops.
|
|
257
|
+
|
|
258
|
+
- It is a **live feed, not a queue**: a browser that reconnects sees what happens next, not
|
|
259
|
+
what it missed, and a connection that falls more than 100 messages behind sheds its oldest.
|
|
260
|
+
- The hub is **per process**. With one worker and threads (the default `jongo run`) a
|
|
261
|
+
broadcast reaches every connection. Across multiple worker processes, each worker only
|
|
262
|
+
reaches its own connections — put a shared bus in front if you need that.
|
|
263
|
+
- Each streaming connection holds a worker thread, so raise `--threads` for a chatty app.
|
|
264
|
+
|
|
215
265
|
## Styles
|
|
216
266
|
|
|
217
267
|
```python
|
|
@@ -250,12 +300,41 @@ with db.transaction():
|
|
|
250
300
|
|
|
251
301
|
- **Fields:** `Text Int Float Bool DateTime Date JSON ForeignKey`.
|
|
252
302
|
- **Lookups:** `exact iexact contains icontains startswith endswith gt gte lt lte in isnull ne`, plus relation traversal with `__`.
|
|
253
|
-
- **Migrations have no files.** `jongo migrate` compares your models to the live
|
|
254
|
-
- It creates tables, adds columns and indexes, and
|
|
303
|
+
- **Migrations have no files.** `jongo migrate` compares your models to the live schema.
|
|
304
|
+
- It creates tables, adds columns and indexes, and changes a column when its type changes.
|
|
255
305
|
- It only drops columns when you pass `--allow-destructive`.
|
|
256
306
|
- `jongo migrate --plan` shows the SQL first.
|
|
257
307
|
- `jongo dev` applies the safe changes automatically.
|
|
258
308
|
|
|
309
|
+
### SQLite or PostgreSQL
|
|
310
|
+
|
|
311
|
+
SQLite is the default and needs no setup. Point the same models at PostgreSQL with a URL:
|
|
312
|
+
|
|
313
|
+
```python
|
|
314
|
+
app = Jongo(__name__, database="postgres://user:pw@localhost/app")
|
|
315
|
+
# or: JONGO_DATABASE=postgres://user:pw@localhost/app
|
|
316
|
+
```
|
|
317
|
+
|
|
318
|
+
```bash
|
|
319
|
+
pip install "jongo[postgres]" # adds the psycopg driver; the core stays dependency-free
|
|
320
|
+
```
|
|
321
|
+
|
|
322
|
+
Nothing else changes — the same models, queries, migrations and tests run on both, and the
|
|
323
|
+
test suite is run against both. The backends differ only where the database does:
|
|
324
|
+
|
|
325
|
+
| | SQLite | PostgreSQL |
|
|
326
|
+
|---|---|---|
|
|
327
|
+
| Changing a column | rebuilds the table | `ALTER TABLE … ALTER COLUMN` |
|
|
328
|
+
| Dropping a column | rebuilds when the column is referenced | drops in place |
|
|
329
|
+
| Case-sensitive `contains` | `GLOB` | `LIKE` |
|
|
330
|
+
| Case-insensitive `icontains` | `LIKE` | `ILIKE` |
|
|
331
|
+
| New row ids | `AUTOINCREMENT` | identity column, kept in step with explicit ids |
|
|
332
|
+
|
|
333
|
+
Both store the same representations — datetimes and dates as ISO-8601 text, booleans as
|
|
334
|
+
integers, JSON as text — so a model behaves identically on either one. That is a deliberate
|
|
335
|
+
trade for consistency: it means no value changes meaning when you move an app from SQLite to
|
|
336
|
+
PostgreSQL, at the cost of not using `timestamptz`/`jsonb` natively.
|
|
337
|
+
|
|
259
338
|
## Auth and admin
|
|
260
339
|
|
|
261
340
|
```python
|
|
@@ -285,6 +364,26 @@ def test_add(app):
|
|
|
285
364
|
assert client.navigate("/")["title"] == "Todos"
|
|
286
365
|
```
|
|
287
366
|
|
|
367
|
+
## AI coding agents
|
|
368
|
+
|
|
369
|
+
The author of a web app is increasingly a model, and a model needs what a new colleague
|
|
370
|
+
needs: the map of the app in one document it can load at once, and a feedback loop whose
|
|
371
|
+
output it can act on. Jongo generates both from the running code, so neither can go stale:
|
|
372
|
+
|
|
373
|
+
```bash
|
|
374
|
+
jongo context # the rules of the framework, then this app's map: models, server
|
|
375
|
+
# functions with their signatures, pages, components, channels
|
|
376
|
+
jongo context -o AGENTS.md # write it for the agent jongo context --json # as data
|
|
377
|
+
jongo check --json # compile every component, resolve every server function's type
|
|
378
|
+
# hints, plan migrations; problems as {kind, message, file, line, hint}
|
|
379
|
+
```
|
|
380
|
+
|
|
381
|
+
`jongo new` writes an `AGENTS.md` for the project (the convention Codex, Cursor and most
|
|
382
|
+
agents read) and a `CLAUDE.md` that imports it, so Claude Code knows the rules the moment it
|
|
383
|
+
opens the folder. The reasons this shape suits agents are the reasons it suits people: one
|
|
384
|
+
language, one file, type-checked boundaries, and compile errors at start-up instead of
|
|
385
|
+
surprises in a browser. From Python: `jongo.describe(app)` and `jongo.context(app)`.
|
|
386
|
+
|
|
288
387
|
## CLI
|
|
289
388
|
|
|
290
389
|
| Command | |
|
|
@@ -54,6 +54,18 @@ def home():
|
|
|
54
54
|
jongo dev # → http://localhost:8000, reloads when you save
|
|
55
55
|
```
|
|
56
56
|
|
|
57
|
+
## Documentation
|
|
58
|
+
|
|
59
|
+
- **[The guide](docs/guide.md)** — the long version: the request model, routing, components,
|
|
60
|
+
every hook, server functions, the ORM, migrations, PostgreSQL, channels, auth, security,
|
|
61
|
+
testing, deployment, exactly what compiles to the browser, and a troubleshooting table.
|
|
62
|
+
- **[Patterns](examples/patterns/)** — thirteen complete, runnable apps: CRUD, auth, search
|
|
63
|
+
as you type, pagination, optimistic UI, live chat, a live dashboard, modals with server
|
|
64
|
+
validation, master-detail, uploads, background work, testing, deployment.
|
|
65
|
+
- **[Benchmarks](benchmarks/)** — against Django and FastAPI, with the harness and the
|
|
66
|
+
caveats.
|
|
67
|
+
- The docs site is itself a Jongo app: `jongo dev docs/docs_site.py --port 8790`.
|
|
68
|
+
|
|
57
69
|
## Why
|
|
58
70
|
|
|
59
71
|
In Django, one feature is spread across `models.py`, `urls.py`, `views.py`, a template, a form class and usually some JavaScript. In Jongo it's one idea in one place:
|
|
@@ -182,6 +194,41 @@ def rename(request, todo: Todo, title: str) -> dict: # `todo: Todo` loads the
|
|
|
182
194
|
- **Options:** `@server(login_required=True)`, `@server(admin_required=True)`, and `@server(refresh=True)` to re-run the page loader after each call.
|
|
183
195
|
- **Security:** every call is CSRF-protected. Only functions you decorate are exposed.
|
|
184
196
|
|
|
197
|
+
## Real-time
|
|
198
|
+
|
|
199
|
+
Push from a server function straight into a mounted component. Declare the channel, and
|
|
200
|
+
the declaring function authorises each subscription — an undeclared channel cannot be
|
|
201
|
+
subscribed to at all, the same rule that keeps undecorated functions off the RPC boundary.
|
|
202
|
+
|
|
203
|
+
```python
|
|
204
|
+
@app.channel("room:<int:id>")
|
|
205
|
+
def room(request, id):
|
|
206
|
+
return id in request.session.get("rooms", [])
|
|
207
|
+
|
|
208
|
+
@server
|
|
209
|
+
def post(request, room: int, text: str) -> dict:
|
|
210
|
+
message = Message.create(room_id=room, text=text).to_dict()
|
|
211
|
+
broadcast(f"room:{room}", message) # -> every subscribed browser
|
|
212
|
+
return message
|
|
213
|
+
|
|
214
|
+
@component
|
|
215
|
+
def Chat(room):
|
|
216
|
+
messages = state([])
|
|
217
|
+
live(f"room:{room}", lambda message: messages.set([*messages.value, message]))
|
|
218
|
+
return ul([li(m["text"], key=m["id"]) for m in messages.value])
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
`live()` is a hook like `state()` and `effect()`: the subscription opens when the component
|
|
222
|
+
mounts, moves when the channel changes, and closes when it unmounts. One SSE connection per
|
|
223
|
+
tab carries every channel the page asked for, and reconnects with backoff if it drops.
|
|
224
|
+
|
|
225
|
+
- It is a **live feed, not a queue**: a browser that reconnects sees what happens next, not
|
|
226
|
+
what it missed, and a connection that falls more than 100 messages behind sheds its oldest.
|
|
227
|
+
- The hub is **per process**. With one worker and threads (the default `jongo run`) a
|
|
228
|
+
broadcast reaches every connection. Across multiple worker processes, each worker only
|
|
229
|
+
reaches its own connections — put a shared bus in front if you need that.
|
|
230
|
+
- Each streaming connection holds a worker thread, so raise `--threads` for a chatty app.
|
|
231
|
+
|
|
185
232
|
## Styles
|
|
186
233
|
|
|
187
234
|
```python
|
|
@@ -220,12 +267,41 @@ with db.transaction():
|
|
|
220
267
|
|
|
221
268
|
- **Fields:** `Text Int Float Bool DateTime Date JSON ForeignKey`.
|
|
222
269
|
- **Lookups:** `exact iexact contains icontains startswith endswith gt gte lt lte in isnull ne`, plus relation traversal with `__`.
|
|
223
|
-
- **Migrations have no files.** `jongo migrate` compares your models to the live
|
|
224
|
-
- It creates tables, adds columns and indexes, and
|
|
270
|
+
- **Migrations have no files.** `jongo migrate` compares your models to the live schema.
|
|
271
|
+
- It creates tables, adds columns and indexes, and changes a column when its type changes.
|
|
225
272
|
- It only drops columns when you pass `--allow-destructive`.
|
|
226
273
|
- `jongo migrate --plan` shows the SQL first.
|
|
227
274
|
- `jongo dev` applies the safe changes automatically.
|
|
228
275
|
|
|
276
|
+
### SQLite or PostgreSQL
|
|
277
|
+
|
|
278
|
+
SQLite is the default and needs no setup. Point the same models at PostgreSQL with a URL:
|
|
279
|
+
|
|
280
|
+
```python
|
|
281
|
+
app = Jongo(__name__, database="postgres://user:pw@localhost/app")
|
|
282
|
+
# or: JONGO_DATABASE=postgres://user:pw@localhost/app
|
|
283
|
+
```
|
|
284
|
+
|
|
285
|
+
```bash
|
|
286
|
+
pip install "jongo[postgres]" # adds the psycopg driver; the core stays dependency-free
|
|
287
|
+
```
|
|
288
|
+
|
|
289
|
+
Nothing else changes — the same models, queries, migrations and tests run on both, and the
|
|
290
|
+
test suite is run against both. The backends differ only where the database does:
|
|
291
|
+
|
|
292
|
+
| | SQLite | PostgreSQL |
|
|
293
|
+
|---|---|---|
|
|
294
|
+
| Changing a column | rebuilds the table | `ALTER TABLE … ALTER COLUMN` |
|
|
295
|
+
| Dropping a column | rebuilds when the column is referenced | drops in place |
|
|
296
|
+
| Case-sensitive `contains` | `GLOB` | `LIKE` |
|
|
297
|
+
| Case-insensitive `icontains` | `LIKE` | `ILIKE` |
|
|
298
|
+
| New row ids | `AUTOINCREMENT` | identity column, kept in step with explicit ids |
|
|
299
|
+
|
|
300
|
+
Both store the same representations — datetimes and dates as ISO-8601 text, booleans as
|
|
301
|
+
integers, JSON as text — so a model behaves identically on either one. That is a deliberate
|
|
302
|
+
trade for consistency: it means no value changes meaning when you move an app from SQLite to
|
|
303
|
+
PostgreSQL, at the cost of not using `timestamptz`/`jsonb` natively.
|
|
304
|
+
|
|
229
305
|
## Auth and admin
|
|
230
306
|
|
|
231
307
|
```python
|
|
@@ -255,6 +331,26 @@ def test_add(app):
|
|
|
255
331
|
assert client.navigate("/")["title"] == "Todos"
|
|
256
332
|
```
|
|
257
333
|
|
|
334
|
+
## AI coding agents
|
|
335
|
+
|
|
336
|
+
The author of a web app is increasingly a model, and a model needs what a new colleague
|
|
337
|
+
needs: the map of the app in one document it can load at once, and a feedback loop whose
|
|
338
|
+
output it can act on. Jongo generates both from the running code, so neither can go stale:
|
|
339
|
+
|
|
340
|
+
```bash
|
|
341
|
+
jongo context # the rules of the framework, then this app's map: models, server
|
|
342
|
+
# functions with their signatures, pages, components, channels
|
|
343
|
+
jongo context -o AGENTS.md # write it for the agent jongo context --json # as data
|
|
344
|
+
jongo check --json # compile every component, resolve every server function's type
|
|
345
|
+
# hints, plan migrations; problems as {kind, message, file, line, hint}
|
|
346
|
+
```
|
|
347
|
+
|
|
348
|
+
`jongo new` writes an `AGENTS.md` for the project (the convention Codex, Cursor and most
|
|
349
|
+
agents read) and a `CLAUDE.md` that imports it, so Claude Code knows the rules the moment it
|
|
350
|
+
opens the folder. The reasons this shape suits agents are the reasons it suits people: one
|
|
351
|
+
language, one file, type-checked boundaries, and compile errors at start-up instead of
|
|
352
|
+
surprises in a browser. From Python: `jongo.describe(app)` and `jongo.context(app)`.
|
|
353
|
+
|
|
258
354
|
## CLI
|
|
259
355
|
|
|
260
356
|
| Command | |
|
|
@@ -18,6 +18,8 @@ that renders on the server and compiles to JavaScript for the browser.
|
|
|
18
18
|
from .app import Jongo, Page
|
|
19
19
|
from .errors import CompileError, Forbidden, HTTPError, JongoError, NotFound, ServerError
|
|
20
20
|
from .http import Request, Response, json_response, redirect
|
|
21
|
+
from .introspect import context, describe
|
|
22
|
+
from .live import broadcast
|
|
21
23
|
from .rpc import server
|
|
22
24
|
from .styles import css, global_css
|
|
23
25
|
from .vdom import (
|
|
@@ -28,6 +30,7 @@ from .vdom import (
|
|
|
28
30
|
fragment,
|
|
29
31
|
h,
|
|
30
32
|
js,
|
|
33
|
+
live,
|
|
31
34
|
navigate,
|
|
32
35
|
raw,
|
|
33
36
|
ref,
|
|
@@ -35,11 +38,12 @@ from .vdom import (
|
|
|
35
38
|
state,
|
|
36
39
|
)
|
|
37
40
|
|
|
38
|
-
__version__ = "0.
|
|
41
|
+
__version__ = "0.4.0"
|
|
39
42
|
|
|
40
43
|
__all__ = [
|
|
41
44
|
"Jongo", "Page", "Request", "Response", "redirect", "json_response",
|
|
42
|
-
"component", "state", "effect", "ref", "navigate", "refresh", "form_values", "js",
|
|
45
|
+
"component", "state", "effect", "live", "ref", "navigate", "refresh", "form_values", "js",
|
|
46
|
+
"broadcast", "describe", "context",
|
|
43
47
|
"server", "css", "global_css", "h", "raw", "fragment", "VNode",
|
|
44
48
|
"HTTPError", "NotFound", "Forbidden", "ServerError", "CompileError", "JongoError",
|
|
45
49
|
]
|
|
@@ -17,6 +17,7 @@ import typing
|
|
|
17
17
|
import urllib.parse
|
|
18
18
|
from pathlib import Path
|
|
19
19
|
|
|
20
|
+
from . import live as live_module
|
|
20
21
|
from . import vdom
|
|
21
22
|
from . import log as jlog
|
|
22
23
|
from .errors import CompileError, HTTPError, NotFound
|
|
@@ -33,7 +34,7 @@ from .http import (
|
|
|
33
34
|
from .routing import Route, Router
|
|
34
35
|
from .rpc import SERVER_FUNCTIONS, coerce
|
|
35
36
|
from .styles import collect_css
|
|
36
|
-
from .vdom import VNode,
|
|
37
|
+
from .vdom import VNode, render_to_string, serialize
|
|
37
38
|
|
|
38
39
|
log = logging.getLogger("jongo")
|
|
39
40
|
SAFE_METHODS = frozenset(("GET", "HEAD", "OPTIONS"))
|
|
@@ -87,6 +88,7 @@ class Jongo:
|
|
|
87
88
|
self.before_request_hooks: list = []
|
|
88
89
|
self.after_request_hooks: list = []
|
|
89
90
|
self.error_handlers: dict[int, typing.Callable] = {}
|
|
91
|
+
self.channels: list[live_module.Channel] = []
|
|
90
92
|
self.layout_component = None
|
|
91
93
|
self.layout_props = None
|
|
92
94
|
self._bundle: tuple[str, str] | None = None
|
|
@@ -134,6 +136,26 @@ class Jongo:
|
|
|
134
136
|
def post(self, path: str, **options):
|
|
135
137
|
return self.route(path, methods=("POST",), **options)
|
|
136
138
|
|
|
139
|
+
def channel(self, pattern: str):
|
|
140
|
+
"""Declare a channel components may subscribe to with ``live()``.
|
|
141
|
+
|
|
142
|
+
The decorated function authorises each subscription: return False (or raise
|
|
143
|
+
Forbidden) to refuse it. Pattern parameters work as they do in routes::
|
|
144
|
+
|
|
145
|
+
@app.channel("room:<int:id>")
|
|
146
|
+
def room(request, id):
|
|
147
|
+
return id in request.session.get("rooms", [])
|
|
148
|
+
|
|
149
|
+
A channel that is not declared cannot be subscribed to at all — the same rule
|
|
150
|
+
that keeps undecorated functions off the RPC boundary.
|
|
151
|
+
"""
|
|
152
|
+
|
|
153
|
+
def decorator(fn):
|
|
154
|
+
self.channels.append(live_module.Channel(pattern, fn))
|
|
155
|
+
return fn
|
|
156
|
+
|
|
157
|
+
return decorator
|
|
158
|
+
|
|
137
159
|
def layout(self, component=None, *, props=None):
|
|
138
160
|
"""Wrap every page in ``component``. ``props(request)`` may supply extra props."""
|
|
139
161
|
|
|
@@ -261,9 +283,14 @@ class Jongo:
|
|
|
261
283
|
extra = self.layout_props(request) if self.layout_props else {}
|
|
262
284
|
tree = self.layout_component(tree, **extra)
|
|
263
285
|
|
|
286
|
+
# Render the HTML from the *serialised* tree, not the original one, so the server
|
|
287
|
+
# and the browser start from identical data and cannot diverge. The renderer walks
|
|
288
|
+
# that data directly: rebuilding a second VNode tree to render from was a full
|
|
289
|
+
# extra pass and an extra tree per request, and reading the data itself is the
|
|
290
|
+
# stronger guarantee anyway.
|
|
264
291
|
data = serialize(tree)
|
|
265
292
|
encoded = json.dumps(data, separators=(",", ":"))
|
|
266
|
-
body_html = render_to_string(
|
|
293
|
+
body_html = render_to_string(data)
|
|
267
294
|
_, build_hash = self.bundle()
|
|
268
295
|
headers = {"Vary": "X-Jongo-Nav", "Cache-Control": "no-store"}
|
|
269
296
|
if request.is_navigation:
|
|
@@ -463,16 +490,35 @@ class Jongo:
|
|
|
463
490
|
return json_response({"ok": result})
|
|
464
491
|
|
|
465
492
|
def live(request):
|
|
493
|
+
"""Two streams on one route: dev live-reload, and declared channels."""
|
|
494
|
+
channels = live_module.parse_channels(request.query.get("channels"))
|
|
495
|
+
if channels:
|
|
496
|
+
allowed = live_module.authorize(channels, app.channels, request)
|
|
497
|
+
subscriber = live_module.hub.subscribe(allowed)
|
|
498
|
+
|
|
499
|
+
def stream():
|
|
500
|
+
try:
|
|
501
|
+
yield from live_module.event_stream(subscriber)
|
|
502
|
+
finally: # the WSGI server closes the iterator when the client goes
|
|
503
|
+
live_module.hub.unsubscribe(subscriber)
|
|
504
|
+
|
|
505
|
+
return Response(
|
|
506
|
+
stream(),
|
|
507
|
+
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
|
|
508
|
+
content_type="text/event-stream",
|
|
509
|
+
)
|
|
510
|
+
|
|
466
511
|
if not app.dev:
|
|
467
512
|
raise NotFound()
|
|
468
513
|
|
|
469
|
-
def
|
|
514
|
+
def reload_stream():
|
|
470
515
|
yield f"retry: 400\ndata: {app.boot_id}\n\n"
|
|
471
516
|
while True:
|
|
472
517
|
time.sleep(15)
|
|
473
518
|
yield ": ping\n\n"
|
|
474
519
|
|
|
475
|
-
return Response(
|
|
520
|
+
return Response(reload_stream(), headers={"Cache-Control": "no-cache"},
|
|
521
|
+
content_type="text/event-stream")
|
|
476
522
|
|
|
477
523
|
def static(request, path: str):
|
|
478
524
|
base = (app.root / "static").resolve()
|
|
@@ -111,6 +111,14 @@ def cmd_migrate(args):
|
|
|
111
111
|
|
|
112
112
|
def cmd_routes(args):
|
|
113
113
|
app = load_app(args.app)
|
|
114
|
+
if getattr(args, "json", False):
|
|
115
|
+
import json
|
|
116
|
+
|
|
117
|
+
from .introspect import describe
|
|
118
|
+
|
|
119
|
+
d = describe(app)
|
|
120
|
+
print(json.dumps({"pages": d["pages"], "routes": d["routes"]}, indent=2))
|
|
121
|
+
return
|
|
114
122
|
rows = [
|
|
115
123
|
(",".join(sorted(r.methods - {"HEAD"})), r.path, r.kind, r.name)
|
|
116
124
|
for r in app.router.routes
|
|
@@ -175,9 +183,56 @@ def cmd_build(args):
|
|
|
175
183
|
print(_c("✓", "32;1"), f"compiled {len(COMPONENTS)} components → .jongo/build/app.js ({len(js) / 1024:.1f} KB, build {build_hash})")
|
|
176
184
|
|
|
177
185
|
|
|
186
|
+
def cmd_check(args):
|
|
187
|
+
"""Compile, resolve, plan; report problems as data. The command an agent runs after every change."""
|
|
188
|
+
import json
|
|
189
|
+
|
|
190
|
+
from .introspect import check
|
|
191
|
+
|
|
192
|
+
app = load_app(args.app)
|
|
193
|
+
report = check(app)
|
|
194
|
+
if args.json:
|
|
195
|
+
print(json.dumps(report, indent=2))
|
|
196
|
+
else:
|
|
197
|
+
c = report["counts"]
|
|
198
|
+
print(f" {c['components']} components, {c['server_functions']} server functions, {c['pages']} pages, "
|
|
199
|
+
f"{c['routes']} routes, {c['models']} models, {c['channels']} channels")
|
|
200
|
+
for op in report["pending_migrations"]:
|
|
201
|
+
flag = _c(" (destructive)", "31") if op["destructive"] else ""
|
|
202
|
+
print(f" • pending migration: {op['describe']}{flag}")
|
|
203
|
+
for p in report["problems"]:
|
|
204
|
+
where = f" ({p['file']}:{p['line']})" if p.get("file") else ""
|
|
205
|
+
print(_c(f"✗ {p['kind']}", "31;1") + f"{where}: {p['message']}")
|
|
206
|
+
if p.get("source"):
|
|
207
|
+
print(_c(f" {p['source'].strip()}", "2"))
|
|
208
|
+
if p.get("hint"):
|
|
209
|
+
print(_c(f" hint: {p['hint']}", "2"))
|
|
210
|
+
if report["ok"]:
|
|
211
|
+
print(_c("✓", "32;1"), "Everything compiles, every server function resolves, "
|
|
212
|
+
+ ("the schema is up to date." if not report["pending_migrations"] else "migrations are pending."))
|
|
213
|
+
raise SystemExit(0 if report["ok"] else 1)
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def cmd_context(args):
|
|
217
|
+
"""The context pack: the framework's rules plus this app's map, generated from the running code."""
|
|
218
|
+
import json
|
|
219
|
+
|
|
220
|
+
from .introspect import context, describe
|
|
221
|
+
|
|
222
|
+
app = load_app(args.app)
|
|
223
|
+
text = json.dumps(describe(app), indent=2) if args.json else context(app)
|
|
224
|
+
if args.output:
|
|
225
|
+
Path(args.output).write_text(text.rstrip("\n") + "\n")
|
|
226
|
+
print(_c("✓", "32;1"), f"wrote {args.output}")
|
|
227
|
+
else:
|
|
228
|
+
print(text, end="" if text.endswith("\n") else "\n")
|
|
229
|
+
|
|
230
|
+
|
|
178
231
|
def main(argv=None):
|
|
179
232
|
parser = argparse.ArgumentParser(prog="jongo", description="Full-stack Python web framework")
|
|
180
|
-
|
|
233
|
+
from . import __version__
|
|
234
|
+
|
|
235
|
+
parser.add_argument("--version", action="version", version=f"jongo {__version__}")
|
|
181
236
|
sub = parser.add_subparsers(dest="command", metavar="command")
|
|
182
237
|
|
|
183
238
|
def add(name, fn, help_text, app_arg=True):
|
|
@@ -205,6 +260,7 @@ def main(argv=None):
|
|
|
205
260
|
p.add_argument("--allow-destructive", action="store_true", help="also drop columns")
|
|
206
261
|
|
|
207
262
|
p = add("routes", cmd_routes, "list routes")
|
|
263
|
+
p.add_argument("--json", action="store_true", help="pages and routes as JSON, with parameters and guards")
|
|
208
264
|
p.add_argument("--all", action="store_true", help="include Jongo's internal routes")
|
|
209
265
|
|
|
210
266
|
add("shell", cmd_shell, "interactive Python shell with your models loaded")
|
|
@@ -215,6 +271,11 @@ def main(argv=None):
|
|
|
215
271
|
p.add_argument("--password")
|
|
216
272
|
|
|
217
273
|
add("build", cmd_build, "compile components and report errors")
|
|
274
|
+
p = add("check", cmd_check, "compile, resolve type hints and plan migrations; report problems as data")
|
|
275
|
+
p.add_argument("--json", action="store_true", help="the report as JSON (for a coding agent or CI)")
|
|
276
|
+
p = add("context", cmd_context, "describe this app for an AI coding tool: the rules, then the app's map")
|
|
277
|
+
p.add_argument("--json", action="store_true", help="the map as JSON instead of Markdown")
|
|
278
|
+
p.add_argument("-o", "--output", metavar="FILE", help="write to FILE (e.g. AGENTS.md) instead of stdout")
|
|
218
279
|
|
|
219
280
|
args = parser.parse_args(argv)
|
|
220
281
|
if not getattr(args, "fn", None):
|
|
@@ -287,6 +287,106 @@ const $ref = $fn(function ref(initial = null) {
|
|
|
287
287
|
return inst.hooks[i];
|
|
288
288
|
}, ["initial"]);
|
|
289
289
|
|
|
290
|
+
// ---- live channels ----------------------------------------------------------------------------
|
|
291
|
+
// One EventSource per tab carries every channel the mounted components asked for. The set of
|
|
292
|
+
// channels changes as components mount and unmount, so the stream is reopened — batched across a
|
|
293
|
+
// render — whenever it changes, and reconnected with backoff when the connection drops.
|
|
294
|
+
|
|
295
|
+
const $LIVE = { source: null, handlers: new Map(), retry: 500, syncing: false };
|
|
296
|
+
|
|
297
|
+
function $liveNames() {
|
|
298
|
+
return [...$LIVE.handlers.keys()];
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
function $liveSync() {
|
|
302
|
+
if ($LIVE.syncing) return;
|
|
303
|
+
$LIVE.syncing = true;
|
|
304
|
+
queueMicrotask(() => {
|
|
305
|
+
$LIVE.syncing = false;
|
|
306
|
+
const want = $liveNames().join(",");
|
|
307
|
+
if ($LIVE.source && $LIVE.source.jchannels === want) return;
|
|
308
|
+
if ($LIVE.source) {
|
|
309
|
+
$LIVE.source.jclosed = true;
|
|
310
|
+
$LIVE.source.close();
|
|
311
|
+
$LIVE.source = null;
|
|
312
|
+
}
|
|
313
|
+
if (want) $liveOpen(want);
|
|
314
|
+
});
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
function $liveOpen(want) {
|
|
318
|
+
if (typeof window === "undefined" || !window.EventSource) return;
|
|
319
|
+
const source = new EventSource("/_jongo/live?channels=" + encodeURIComponent(want));
|
|
320
|
+
source.jchannels = want;
|
|
321
|
+
$LIVE.source = source;
|
|
322
|
+
source.onopen = () => {
|
|
323
|
+
$LIVE.retry = 500;
|
|
324
|
+
};
|
|
325
|
+
source.onmessage = (event) => {
|
|
326
|
+
let message;
|
|
327
|
+
try {
|
|
328
|
+
message = JSON.parse(event.data);
|
|
329
|
+
} catch (err) {
|
|
330
|
+
return;
|
|
331
|
+
}
|
|
332
|
+
const handlers = $LIVE.handlers.get(message.channel);
|
|
333
|
+
if (!handlers) return;
|
|
334
|
+
for (const handler of [...handlers]) {
|
|
335
|
+
try {
|
|
336
|
+
handler(message.data);
|
|
337
|
+
} catch (err) {
|
|
338
|
+
$report(err);
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
};
|
|
342
|
+
source.onerror = () => {
|
|
343
|
+
source.close();
|
|
344
|
+
if (source.jclosed || $LIVE.source !== source) return;
|
|
345
|
+
$LIVE.source = null;
|
|
346
|
+
const wait = $LIVE.retry;
|
|
347
|
+
$LIVE.retry = Math.min(wait * 2, 10000);
|
|
348
|
+
setTimeout(() => {
|
|
349
|
+
const names = $liveNames().join(",");
|
|
350
|
+
if (!$LIVE.source && names) $liveOpen(names);
|
|
351
|
+
}, wait);
|
|
352
|
+
};
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
function $liveAdd(channel, handler) {
|
|
356
|
+
let handlers = $LIVE.handlers.get(channel);
|
|
357
|
+
if (!handlers) {
|
|
358
|
+
handlers = new Set();
|
|
359
|
+
$LIVE.handlers.set(channel, handlers);
|
|
360
|
+
}
|
|
361
|
+
handlers.add(handler);
|
|
362
|
+
$liveSync();
|
|
363
|
+
return () => {
|
|
364
|
+
handlers.delete(handler);
|
|
365
|
+
if (!handlers.size) $LIVE.handlers.delete(channel);
|
|
366
|
+
$liveSync();
|
|
367
|
+
};
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
const $live = $fn(function live(channel, handler) {
|
|
371
|
+
const inst = $hookOwner("live");
|
|
372
|
+
const i = inst.hi++;
|
|
373
|
+
const hook = inst.hooks[i] || (inst.hooks[i] = { channel: null, joined: null, fn: null, cleanup: null });
|
|
374
|
+
hook.fn = handler; // the latest closure, so the handler always sees current props
|
|
375
|
+
if (hook.channel === channel) return null;
|
|
376
|
+
hook.channel = channel;
|
|
377
|
+
$pendingEffects.push(() => {
|
|
378
|
+
if (inst.dead || hook.joined === hook.channel) return;
|
|
379
|
+
if (typeof hook.cleanup === "function") hook.cleanup();
|
|
380
|
+
hook.cleanup = null;
|
|
381
|
+
hook.joined = hook.channel;
|
|
382
|
+
if (hook.channel === null || hook.channel === undefined) return;
|
|
383
|
+
hook.cleanup = $liveAdd($str(hook.channel), (data) => {
|
|
384
|
+
if (!inst.dead && hook.fn) hook.fn(data);
|
|
385
|
+
});
|
|
386
|
+
});
|
|
387
|
+
return null;
|
|
388
|
+
}, ["channel", "handler"]);
|
|
389
|
+
|
|
290
390
|
// ---- DOM reconciliation -----------------------------------------------------------------------
|
|
291
391
|
|
|
292
392
|
function $domOf(v) {
|