jongo 0.2.3__tar.gz → 0.3.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.
Files changed (55) hide show
  1. {jongo-0.2.3 → jongo-0.3.0}/PKG-INFO +82 -3
  2. {jongo-0.2.3 → jongo-0.3.0}/README.md +78 -2
  3. {jongo-0.2.3 → jongo-0.3.0}/jongo/__init__.py +5 -2
  4. {jongo-0.2.3 → jongo-0.3.0}/jongo/app.py +50 -4
  5. {jongo-0.2.3 → jongo-0.3.0}/jongo/cli.py +3 -1
  6. {jongo-0.2.3 → jongo-0.3.0}/jongo/compiler/bundle.py +1 -0
  7. {jongo-0.2.3 → jongo-0.3.0}/jongo/compiler/dom.js +100 -0
  8. {jongo-0.2.3 → jongo-0.3.0}/jongo/compiler/pyrt.js +55 -17
  9. {jongo-0.2.3 → jongo-0.3.0}/jongo/compiler/transpile.py +2 -1
  10. {jongo-0.2.3 → jongo-0.3.0}/jongo/db/__init__.py +8 -3
  11. {jongo-0.2.3 → jongo-0.3.0}/jongo/db/connection.py +162 -31
  12. jongo-0.3.0/jongo/db/dialect.py +243 -0
  13. {jongo-0.2.3 → jongo-0.3.0}/jongo/db/migrate.py +197 -11
  14. {jongo-0.2.3 → jongo-0.3.0}/jongo/db/models.py +11 -5
  15. {jongo-0.2.3 → jongo-0.3.0}/jongo/db/query.py +76 -34
  16. jongo-0.3.0/jongo/live.py +234 -0
  17. {jongo-0.2.3 → jongo-0.3.0}/jongo/rpc.py +47 -1
  18. {jongo-0.2.3 → jongo-0.3.0}/jongo/testing.py +23 -1
  19. {jongo-0.2.3 → jongo-0.3.0}/jongo/vdom.py +183 -55
  20. {jongo-0.2.3 → jongo-0.3.0}/jongo.egg-info/PKG-INFO +82 -3
  21. {jongo-0.2.3 → jongo-0.3.0}/jongo.egg-info/SOURCES.txt +8 -0
  22. jongo-0.3.0/jongo.egg-info/requires.txt +3 -0
  23. {jongo-0.2.3 → jongo-0.3.0}/pyproject.toml +6 -1
  24. {jongo-0.2.3 → jongo-0.3.0}/tests/test_app.py +27 -0
  25. {jongo-0.2.3 → jongo-0.3.0}/tests/test_compiler.py +81 -0
  26. {jongo-0.2.3 → jongo-0.3.0}/tests/test_db.py +79 -29
  27. jongo-0.3.0/tests/test_docs_site.py +71 -0
  28. jongo-0.3.0/tests/test_guide_api.py +343 -0
  29. jongo-0.3.0/tests/test_live.py +287 -0
  30. jongo-0.3.0/tests/test_patterns.py +65 -0
  31. jongo-0.3.0/tests/test_postgres.py +220 -0
  32. {jongo-0.2.3 → jongo-0.3.0}/tests/test_stress_fixes.py +3 -1
  33. {jongo-0.2.3 → jongo-0.3.0}/tests/test_stress_fixes_022.py +3 -1
  34. {jongo-0.2.3 → jongo-0.3.0}/LICENSE +0 -0
  35. {jongo-0.2.3 → jongo-0.3.0}/jongo/__main__.py +0 -0
  36. {jongo-0.2.3 → jongo-0.3.0}/jongo/admin.py +0 -0
  37. {jongo-0.2.3 → jongo-0.3.0}/jongo/auth.py +0 -0
  38. {jongo-0.2.3 → jongo-0.3.0}/jongo/compiler/__init__.py +0 -0
  39. {jongo-0.2.3 → jongo-0.3.0}/jongo/compiler/scope.py +0 -0
  40. {jongo-0.2.3 → jongo-0.3.0}/jongo/db/fields.py +0 -0
  41. {jongo-0.2.3 → jongo-0.3.0}/jongo/errors.py +0 -0
  42. {jongo-0.2.3 → jongo-0.3.0}/jongo/errors_page.py +0 -0
  43. {jongo-0.2.3 → jongo-0.3.0}/jongo/html.py +0 -0
  44. {jongo-0.2.3 → jongo-0.3.0}/jongo/http.py +0 -0
  45. {jongo-0.2.3 → jongo-0.3.0}/jongo/log.py +0 -0
  46. {jongo-0.2.3 → jongo-0.3.0}/jongo/routing.py +0 -0
  47. {jongo-0.2.3 → jongo-0.3.0}/jongo/scaffold/app.py.tmpl +0 -0
  48. {jongo-0.2.3 → jongo-0.3.0}/jongo/scaffold/dot-gitignore.tmpl +0 -0
  49. {jongo-0.2.3 → jongo-0.3.0}/jongo/server.py +0 -0
  50. {jongo-0.2.3 → jongo-0.3.0}/jongo/styles.py +0 -0
  51. {jongo-0.2.3 → jongo-0.3.0}/jongo.egg-info/dependency_links.txt +0 -0
  52. {jongo-0.2.3 → jongo-0.3.0}/jongo.egg-info/entry_points.txt +0 -0
  53. {jongo-0.2.3 → jongo-0.3.0}/jongo.egg-info/top_level.txt +0 -0
  54. {jongo-0.2.3 → jongo-0.3.0}/setup.cfg +0 -0
  55. {jongo-0.2.3 → jongo-0.3.0}/tests/test_admin.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: jongo
3
- Version: 0.2.3
3
+ Version: 0.3.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 SQLite schema.
254
- - It creates tables, adds columns and indexes, and rebuilds a table when a column's type changes.
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
@@ -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 SQLite schema.
224
- - It creates tables, adds columns and indexes, and rebuilds a table when a column's type changes.
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
@@ -18,6 +18,7 @@ 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 .live import broadcast
21
22
  from .rpc import server
22
23
  from .styles import css, global_css
23
24
  from .vdom import (
@@ -28,6 +29,7 @@ from .vdom import (
28
29
  fragment,
29
30
  h,
30
31
  js,
32
+ live,
31
33
  navigate,
32
34
  raw,
33
35
  ref,
@@ -35,11 +37,12 @@ from .vdom import (
35
37
  state,
36
38
  )
37
39
 
38
- __version__ = "0.2.3"
40
+ __version__ = "0.3.0"
39
41
 
40
42
  __all__ = [
41
43
  "Jongo", "Page", "Request", "Response", "redirect", "json_response",
42
- "component", "state", "effect", "ref", "navigate", "refresh", "form_values", "js",
44
+ "component", "state", "effect", "live", "ref", "navigate", "refresh", "form_values", "js",
45
+ "broadcast",
43
46
  "server", "css", "global_css", "h", "raw", "fragment", "VNode",
44
47
  "HTTPError", "NotFound", "Forbidden", "ServerError", "CompileError", "JongoError",
45
48
  ]
@@ -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, build, render_to_string, serialize
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(build(json.loads(encoded)))
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 stream():
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(stream(), headers={"Cache-Control": "no-cache"}, content_type="text/event-stream")
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()
@@ -177,7 +177,9 @@ def cmd_build(args):
177
177
 
178
178
  def main(argv=None):
179
179
  parser = argparse.ArgumentParser(prog="jongo", description="Full-stack Python web framework")
180
- parser.add_argument("--version", action="version", version="jongo 0.2.3")
180
+ from . import __version__
181
+
182
+ parser.add_argument("--version", action="version", version=f"jongo {__version__}")
181
183
  sub = parser.add_subparsers(dest="command", metavar="command")
182
184
 
183
185
  def add(name, fn, help_text, app_arg=True):
@@ -45,6 +45,7 @@ def _special_objects() -> dict[int, str]:
45
45
  special = {
46
46
  vdom.state: "$state",
47
47
  vdom.effect: "$effect",
48
+ vdom.live: "$live",
48
49
  vdom.ref: "$ref",
49
50
  vdom.navigate: "$navigate",
50
51
  vdom.refresh: "$refresh",
@@ -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) {