nowity 1.2.1 → 1.5.0

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 (57) hide show
  1. package/README.md +316 -3
  2. package/dist/client/connection.d.ts +2 -0
  3. package/dist/client/connection.d.ts.map +1 -1
  4. package/dist/client/connection.js +13 -0
  5. package/dist/client/nowity-client.d.ts +23 -0
  6. package/dist/client/nowity-client.d.ts.map +1 -1
  7. package/dist/client/nowity-client.js +29 -1
  8. package/dist/client/overlay.d.ts +52 -2
  9. package/dist/client/overlay.d.ts.map +1 -1
  10. package/dist/client/overlay.js +43 -0
  11. package/dist/client.d.ts +1 -1
  12. package/dist/client.d.ts.map +1 -1
  13. package/dist/core/protocol.d.ts +20 -1
  14. package/dist/core/protocol.d.ts.map +1 -1
  15. package/dist/index.d.ts +5 -0
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +12 -1
  18. package/dist/server/api/collector.d.ts.map +1 -1
  19. package/dist/server/api/collector.js +4 -1
  20. package/dist/server/api/configure.d.ts +24 -0
  21. package/dist/server/api/configure.d.ts.map +1 -1
  22. package/dist/server/api/configure.js +51 -1
  23. package/dist/server/api/execution.d.ts +9 -0
  24. package/dist/server/api/execution.d.ts.map +1 -1
  25. package/dist/server/api/execution.js +19 -0
  26. package/dist/server/api/presence.d.ts +66 -0
  27. package/dist/server/api/presence.d.ts.map +1 -0
  28. package/dist/server/api/presence.js +181 -0
  29. package/dist/server/api/read-keys.d.ts +6 -0
  30. package/dist/server/api/read-keys.d.ts.map +1 -1
  31. package/dist/server/api/read-keys.js +12 -0
  32. package/dist/server/api/runtime.d.ts.map +1 -1
  33. package/dist/server/api/runtime.js +12 -0
  34. package/dist/server/api/scheduler.d.ts +122 -0
  35. package/dist/server/api/scheduler.d.ts.map +1 -0
  36. package/dist/server/api/scheduler.js +217 -0
  37. package/dist/server/change-source/wal-change-source.d.ts.map +1 -1
  38. package/dist/server/change-source/wal-change-source.js +10 -1
  39. package/dist/server/leader.d.ts +138 -0
  40. package/dist/server/leader.d.ts.map +1 -0
  41. package/dist/server/leader.js +342 -0
  42. package/dist/server/presence.d.ts +217 -0
  43. package/dist/server/presence.d.ts.map +1 -0
  44. package/dist/server/presence.js +428 -0
  45. package/dist/server/scheduler.d.ts +195 -0
  46. package/dist/server/scheduler.d.ts.map +1 -0
  47. package/dist/server/scheduler.js +432 -0
  48. package/dist/server/setup-sql.d.ts +1 -1
  49. package/dist/server/setup-sql.d.ts.map +1 -1
  50. package/dist/server/setup-sql.js +547 -0
  51. package/dist/server/sync-engine.d.ts +22 -1
  52. package/dist/server/sync-engine.d.ts.map +1 -1
  53. package/dist/server/sync-engine.js +30 -1
  54. package/dist/server/ws-server.d.ts +22 -0
  55. package/dist/server/ws-server.d.ts.map +1 -1
  56. package/dist/server/ws-server.js +81 -1
  57. package/package.json +1 -1
package/README.md CHANGED
@@ -411,11 +411,18 @@ it is the only part written twice:
411
411
 
412
412
  ```ts
413
413
  { name: "scores.add", local: ([id, delta], tx) => {
414
- const row = tx.get("Score", id);
415
- if (row) tx.update("Score", id, { points: row.points + delta });
414
+ const score = tx.of<{ points: number }>("Score").get(id);
415
+ if (score) score.points += delta;
416
416
  } }
417
417
  ```
418
418
 
419
+ `tx.of(entity)` gives `get(id)`, `all()`, `create(row)` and `remove(id)`. A row from `get` is a
420
+ draft: reading it gives the current value, assigning to a field stages the change in the
421
+ overlay (not in the live MobX object, which the next rebase rebuilds). A row that is not
422
+ loaded gives `undefined`. `tx.get/all/update/put/remove(entity, …)` still work and are
423
+ deprecated. Type the entities once with `declare module "nowity/client" { interface
424
+ LocalEntities { Score: { id: string; points: number } } }` and `tx.of("Score")` knows its fields.
425
+
419
426
  Rollback of a refused write and reconciliation with the confirmed one need no
420
427
  code at all — that is what the rebase is.
421
428
 
@@ -562,6 +569,300 @@ Three things follow from it being the database that coordinates:
562
569
 
563
570
  Scenario 22 runs two instances against one database and checks each of these.
564
571
 
572
+ ### Presence
573
+
574
+ Who is connected is something the sync server already knows — sockets open and
575
+ close on it — so it can record it once, in the database, instead of every page
576
+ writing a heartbeat. Off unless configured:
577
+
578
+ ```ts
579
+ export const nowity = createNowityServer({
580
+ prisma,
581
+ db: Db,
582
+ auth: CookieAuth,
583
+ services: [LobbyApiImpl],
584
+ presence: {
585
+ graceMs: 8_000, // a reload is not a transition
586
+ nodeLeaseMs: 30_000, // how long a killed process's sockets outlive it
587
+ reaperIntervalMs: 1_000, // how often the leader reaps and delivers
588
+ meta: (session) => ({ device: session.meta.device }), // stored per connection
589
+ },
590
+ syncServer: {
591
+ heartbeat: { intervalMs: 15_000, maxMissed: 2 }, // on by default with presence; `false` turns it off
592
+ },
593
+ });
594
+ ```
595
+
596
+ An endpoint reads it through the injectable `Presence`, beside `Session` and
597
+ `Db`:
598
+
599
+ ```ts
600
+ @api(LobbyApi)
601
+ @component
602
+ export class LobbyApiImpl {
603
+ constructor(private readonly db: Db, private readonly presence: Presence) {}
604
+
605
+ @query()
606
+ async members(lobbyId: string) {
607
+ const members = await this.db.lobbyMember.findMany({ where: { lobbyId } });
608
+ const online = await this.presence.online(members.map((m) => m.userId));
609
+ return members.map((m) => ({ ...m, online: online.has(m.userId) }));
610
+ }
611
+ }
612
+ ```
613
+
614
+ | | |
615
+ | --- | --- |
616
+ | `isOnline(userId)` | `Promise<boolean>` |
617
+ | `online(userIds)` | `Promise<Set<string>>` — which of them are online |
618
+ | `onlineAll()` | `Promise<string[]>` — watches the whole table; for admin pages |
619
+ | `contexts(userIds)` | `Promise<Map<string, object[]>>` — what their tabs said they look at |
620
+ | `details(userIds?, {limit})` | `Promise<PresenceDetail[]>` — online users with `since`, `contexts` and their newest connection's `meta`, longest online first; for operator pages |
621
+ | `onOffline(handler)` | called after a user goes offline, at least once; returns the unsubscribe |
622
+
623
+ Inside a `@query` a read goes through the query's own snapshot and is recorded
624
+ in its read set **by user**: `members` above is recomputed when one of those
625
+ members comes or goes, and not when anyone else does. Outside a query — a script,
626
+ a server component — it reads the database directly. It works the same in the
627
+ Next process (`createNextNowity`), which has no socket and no presence of its
628
+ own: the sync processes keep the table current, everyone can read it.
629
+
630
+ **What counts as a change.** A user is online from their first authenticated
631
+ connection until a grace period after their last one closed. A second tab, a
632
+ reload within the grace period, a reconnect to another node — none of them is a
633
+ change, writes nothing to the outbox, and recomputes nothing. Only the
634
+ online ↔ offline transition, and a change in the set of contexts, are seen by
635
+ readers. Anonymous connections are not recorded.
636
+
637
+ **Contexts.** `connection.setContext({ path })` (or `NowityClient.setContext`)
638
+ tells the server what this socket is looking at — per socket, a small plain
639
+ object (4 KB at most), `null` clears it. It is sent only when it changed, and a
640
+ client that reconnects carries it in its hello. A *page reload* is a new client,
641
+ though, and gets the same treatment only if the context is known before it
642
+ connects: pass it as the `context` option of the connection (or call
643
+ `setContext` before `connect()`), and the new socket is recorded with it, so the
644
+ reload is no change. Set after the socket opened, a reload shows up to readers as
645
+ the context going and coming back. Closing one of several tabs changes the set,
646
+ and is a change. `Presence.contexts` returns each user's distinct contexts.
647
+
648
+ **Several processes.** Each process records its sockets in
649
+ `nowity.nowity_connection` and renews a lease on itself in `nowity.nowity_node`.
650
+ One process — elected with a PostgreSQL advisory lock on a dedicated connection
651
+ with server-side keepalives and a heartbeat, see `LeaderElection` — runs the
652
+ reaper: connections of processes whose lease ran out are dropped, and users with
653
+ nothing open for the grace period become offline. The transition is a
654
+ conditional update of the user's `nowity.nowity_presence` row, so it happens
655
+ once even if two processes briefly both believe they lead; leadership only
656
+ saves the work. A process that stops cleanly drops its connections at once, and
657
+ its users get the grace period to land on another one — a rolling deploy is not
658
+ a transition.
659
+
660
+ **Zombie sockets.** With presence on, the server pings every socket and
661
+ terminates one that missed two pongs, so a peer that vanished without closing — a
662
+ laptop lid, a mobile network — goes offline within the interval rather than
663
+ whenever the kernel gives up. Browsers answer pings by themselves. Without
664
+ presence the heartbeat stays off unless `syncServer.heartbeat` asks for it.
665
+
666
+ **Self-repair.** Every lease renewal compares the process's sockets with its
667
+ rows in `nowity_connection`: a socket without a row is recorded again (a lease
668
+ that looked expired, a failed write), a row without a socket is disconnected (a
669
+ failed disconnect). The reaper deletes a dead node's lease *before* its
670
+ connections, so a node that renews in that moment learns it lost them. A
671
+ process's row in `nowity_node` always carries a per-boot suffix (`nodeId` is
672
+ only its prefix), so a restarted process never inherits what its previous life
673
+ left behind.
674
+
675
+ **Offline handlers: at least once, and idempotent.**
676
+
677
+ ```ts
678
+ // On every sync process, before nowity.start().
679
+ getBaseApplicationContext().getBean(Presence).onOffline(async ({ userId, offlineAt }) => {
680
+ // Remove them from the matchmaking queue — unless they rejoined after offlineAt.
681
+ await prisma.queueEntry.deleteMany({ where: { userId, joinedAt: { lt: offlineAt } } });
682
+ });
683
+ ```
684
+
685
+ - The transition and the debt to the handlers are written in one statement; the
686
+ debt is paid (`handled_at = offline_at`) only after every handler returned.
687
+ - A handler that throws, or runs past `handlerTimeoutMs` (a minute), is called
688
+ again with backoff (`retry: { minDelayMs: 1000, maxDelayMs: 60000 }`). One that
689
+ dies with its process is picked up by the next leader once the claim expires.
690
+ So a handler **must be idempotent**, and gets `attempt` to tell a retry.
691
+ - Deliveries run on their own clock beside the reaper, at most `batchSize` (100)
692
+ at once, so a slow handler holds its own slot and never anyone else's
693
+ transition. A retry is not started while the previous attempt's handler is
694
+ still running in the process.
695
+ - `stop()` waits up to `stopTimeoutMs` (5 s) for running handlers; one that has
696
+ not finished by then is left running with its outcome unrecorded, so the next
697
+ leader delivers it again.
698
+ - Handlers run on the leader only; register them on every sync process, before
699
+ `start()`. While none is registered nothing is claimed, and a handler
700
+ registered later receives what was owed.
701
+ - A delivery still owed when the user comes back online is **dropped** — the
702
+ handler would act on someone who is, by then, there. One already running when
703
+ they come back is not stopped, which is why the event carries `offlineAt`
704
+ (and `onlineSince`): guard what the handler undoes with it.
705
+
706
+ **Tables.** `nowity_presence` (one row per user: `online`, `online_since`,
707
+ `offline_at`, `contexts`, and the bookkeeping `last_disconnect_at`, `handled_at`,
708
+ `attempts`, `next_attempt_at`, `last_error`), `nowity_connection`
709
+ (`connection_id`, `user_id`, `node_id`, `connected_at`, `meta`, `context`) and
710
+ `nowity_node` (`node_id`, `lease_until`). All three are created by
711
+ `setupNowity` whether presence is on or not, and stay empty while it is off.
712
+ Only `nowity_presence` reaches the outbox, and only when `online` or `contexts`
713
+ moved. With the WAL change source, which cannot filter by column, the bookkeeping
714
+ updates of that row wake its readers too — an empty recomputation, never a
715
+ wrong one.
716
+
717
+ `LeaderElection` and `PeriodicTask` are exported on their own, for jobs of the
718
+ application that have to run on one process at a time.
719
+
720
+ Scenarios 24 and 25 cover each of these: reloads, tabs on two nodes, a node
721
+ killed without cleanup, a failing handler, a restart of every node, three nodes
722
+ racing, a socket that stops answering pings, contexts, and queries that read
723
+ presence — including which of them a transition must *not* wake.
724
+
725
+ ### Scheduler
726
+
727
+ Jobs to run at a given time — a turn deadline, a reminder, a sweep every
728
+ minute — kept in the database and run once, by whichever sync process leads.
729
+ Off unless configured:
730
+
731
+ ```ts
732
+ export const nowity = createNowityServer({
733
+ prisma,
734
+ db: Db,
735
+ auth: CookieAuth,
736
+ services: [GameApiImpl],
737
+ scheduler: {
738
+ pollIntervalMs: 5_000, // the net under the timer and the notification
739
+ concurrency: 10, // jobs running at once on the leader
740
+ maxAttempts: 5, // before a job is `failed`
741
+ retry: { minDelayMs: 1_000, maxDelayMs: 60_000 },
742
+ handlerTimeoutMs: 60_000, // one attempt; the claim is leased a little longer
743
+ },
744
+ });
745
+ ```
746
+
747
+ Handlers are registered by name on the injectable `Scheduler`, on every sync
748
+ process (only the leader runs them, and any process may become it), before
749
+ `start()`:
750
+
751
+ ```ts
752
+ const scheduler = getBaseApplicationContext().getBean(Scheduler);
753
+
754
+ scheduler.handle<{ gameId: string }>("turn-deadline", async ({ payload, runAt }) => {
755
+ // Idempotent, and checking the job still means something: a move may have
756
+ // landed while this was on its way.
757
+ await markTimedOut(payload.gameId, runAt);
758
+ }, { maxAttempts: 3, onFailed: (job, err) => log.error("deadline gave up", { key: job.key, err }) });
759
+
760
+ scheduler.every("sweep", 60_000, async () => {
761
+ await sweepAbandonedLobbies();
762
+ });
763
+ ```
764
+
765
+ Scheduling works from any process — the Next half included — and needs no
766
+ scheduler of its own there:
767
+
768
+ ```ts
769
+ @api(GameApi)
770
+ @component
771
+ export class GameApiImpl {
772
+ constructor(private readonly db: Db, private readonly scheduler: Scheduler) {}
773
+
774
+ @mutation()
775
+ async move(gameId: string, move: Move) {
776
+ const game = await this.db.game.update({ where: { id: gameId }, data: { ... } });
777
+ // In the mutation's own transaction: the deadline moves with the move,
778
+ // or not at all.
779
+ await this.scheduler.schedule({
780
+ key: `deadline:${gameId}`,
781
+ handler: "turn-deadline",
782
+ runAt: game.turnDeadline,
783
+ payload: { gameId },
784
+ });
785
+ }
786
+ }
787
+ ```
788
+
789
+ | | |
790
+ | --- | --- |
791
+ | `schedule({ key, handler, runAt, payload?, maxAttempts? }, { tx? })` | upsert by key: scheduling a key again replaces the job and starts its attempts over |
792
+ | `reschedule(key, runAt, { tx? })` | `Promise<boolean>`; brings a `failed` job back |
793
+ | `cancel(key, { tx? })` | `Promise<boolean>`; an attempt already running is not stopped |
794
+ | `handle(name, handler, { maxAttempts?, timeoutMs?, retry?, onFailed? })` | register a handler; returns the unregister |
795
+ | `every(name, intervalMs, handler, options?)` | a periodic job, stored as `every:<name>` |
796
+ | `list({ handler?, state?, limit? })` | `Promise<JobInfo[]>`, soonest first |
797
+ | `metrics()` | counts across every process (`pending`, `due`, `running`, `failed`, `lagMs` of the most overdue) and this process's counters (`claimed`, `delivered`, `retried`, `failed`, `lastLagMs`, `maxLagMs`) |
798
+
799
+ **Where a write goes.** Through `{ tx }` when given — a Prisma interactive
800
+ transaction client (`prisma.$transaction(async (tx) => ...)`), or anything with
801
+ a `pg`-style `query(text, values)`; otherwise through the write transaction of
802
+ the `@mutation` it is called from; otherwise on its own. Either of the first two
803
+ commits or rolls back with the caller's change. A `@query` cannot schedule — it
804
+ is re-run whenever what it read changes. A schedule is one statement,
805
+ `SELECT nowity.nowity_job_schedule(...)`, an `INSERT … ON CONFLICT (key) DO
806
+ UPDATE`; `nowity_job` is not tracked, so it writes no outbox row and wakes no
807
+ live query, and is cheap enough for a write after every move.
808
+
809
+ **When it runs.** Never before `runAt`, by the database clock. The leader sleeps
810
+ until the earliest job is due; a schedule that comes before every job still to
811
+ come notifies it (`NOTIFY nowity_scheduler`, at commit — a later one does not, a
812
+ notification costs a lock at commit). The poll is the net under both, for a
813
+ notification lost with a connection.
814
+
815
+ **At least once, and idempotent.** The leader claims due jobs with
816
+ `FOR UPDATE SKIP LOCKED` and leases each claim for the handler's timeout and a
817
+ margin. A handler that throws or runs past its timeout is retried with backoff
818
+ (doubling from `minDelayMs` to `maxDelayMs`); when its attempts are used up a
819
+ one-off job is `failed` — it stays, with `last_error`, until someone
820
+ reschedules or cancels it — and `onFailed` is called. Every failed attempt goes
821
+ to the server's `onError`. A job whose process died mid-attempt is claimed again
822
+ when its lease runs out, by whichever process leads by then. So a handler
823
+ **must be idempotent**, and gets `attempt` to tell a retry.
824
+
825
+ - The outcome of an attempt is recorded under its claim. A job scheduled again
826
+ under the same key while an attempt runs is a new job: the old attempt's
827
+ success does not delete it, its failure does not fail it. The leader does not
828
+ start a key again while its previous handler still runs there (timed out or
829
+ not — such a handler also keeps its `concurrency` slot), but after a change of
830
+ leader the new one may. Guard on what the job was for (`runAt`, the payload)
831
+ rather than on the key.
832
+ - A periodic job moves on by its interval from when it was due, never into the
833
+ past, so a late run is not followed by a burst of the ones it missed. A run
834
+ that uses up its attempts gives up that run, not the job. It keeps its clock
835
+ across restarts; a new interval takes effect from its next run. Its row stays
836
+ when no process registers it any more, until `cancel("every:<name>")`;
837
+ cancelled while still registered, it is written again — at once by the
838
+ process that cancelled it, by the others when they restart. `schedule`
839
+ refuses keys starting with `every:`.
840
+ - Jobs of a handler the leader does not know are not claimed: they wait for a
841
+ leader that does. During a rolling deploy that adds a handler, its jobs may
842
+ wait until a new process leads.
843
+ - A job that is due but cannot be claimed — locked by a transaction that is
844
+ rescheduling it, or its previous handler still running — is looked at again
845
+ after a short backoff (100 ms), not in a loop. With every slot taken the
846
+ leader does not look at all until one frees.
847
+ - `stop()` waits up to `stopTimeoutMs` (5 s) for running jobs; one that has not
848
+ finished by then is left running with its outcome unrecorded, and is claimed
849
+ again when its lease runs out.
850
+
851
+ **Election.** Its own `LeaderElection` (lock `nowity:scheduler`), not the
852
+ presence reaper's: the two then tend to lead on different processes, and
853
+ neither depends on the other being configured.
854
+
855
+ **Table.** `nowity.nowity_job`: `key`, `handler`, `payload`, `run_at`, `next_at`
856
+ (when it may next be attempted), `state` (`pending`, `running`, `failed`),
857
+ `attempts`, `max_attempts`, `interval_ms`, `claim_id`, `locked_until`,
858
+ `last_error`, `created_at`. Created by `setupNowity` whether the scheduler is on
859
+ or not.
860
+
861
+ Scenario 26 covers each of these: time accuracy and the wakeup, reschedule and
862
+ cancel, an attempt racing a new schedule of its key, retries and `failed`, three
863
+ processes and racing claims, a leader killed mid-job, a restart of every
864
+ process, periodic jobs, and scheduling in a Prisma transaction and in a mutation.
865
+
565
866
  ### Escape hatches
566
867
 
567
868
  `@query({ tables: [...] })` for a query that reads through something the tracker
@@ -731,6 +1032,11 @@ produces an empty diff, so the client observes exactly once.
731
1032
  that needs a router that knows each node's read keys and sends it only what it
732
1033
  could care about; the data structure for it is `InvalidationIndex`, filed by
733
1034
  node instead of by subscription, and it is not written.
1035
+ - **A scheduled job is once in the normal run, not once always.** A leader that
1036
+ dies mid-job, a handler past its timeout, and two processes that both believe
1037
+ they lead for a heartbeat all end in a second attempt; the claim and the lease
1038
+ only make that rare. And `runAt` is compared with the database's clock, so an
1039
+ application server whose clock is off moves its jobs by as much.
734
1040
  - **The WAL source does not scale out.** One replication slot feeds one
735
1041
  consumer, so N processes means N slots and N times the retained WAL. Running
736
1042
  several instances is an outbox arrangement.
@@ -752,6 +1058,11 @@ src/server/api/ read-set tracker, contract→engine bridge, prerender, auth
752
1058
  src/server/api/list.ts paging an endpoint that has no paging
753
1059
  src/client/list.ts the windows a collection is actually showing
754
1060
  src/server/ engine: change sources, sync engine, mutators, WebSocket server
1061
+ src/server/presence.ts connections, node leases, the reaper, offline delivery
1062
+ src/server/leader.ts one process out of many: advisory-lock election, periodic tasks
1063
+ src/server/scheduler.ts jobs at a time: claims, leases, retries, the leader's loop
1064
+ src/server/api/scheduler.ts `Scheduler`, as application code uses it
1065
+ src/server/api/presence.ts `Presence`, as an endpoint reads it
755
1066
  src/client/ engine: confirmed store, overlay/rebase, identity map, live queries
756
1067
  src/client/connection.ts contract proxies, async acquisition, subscription lifetime
757
1068
  src/client/query-source.ts what a component reads through — the socket's, or a
@@ -762,7 +1073,9 @@ test/app/ demo app: shared.ts (client half) vs server.ts (server half),
762
1073
  test/scenarios/ 00 milestones, 01–11 acceptance scenarios, 12 Prisma, 13 WAL,
763
1074
  14 React, 15 SSR hydration, 16 DI containers, 17 SSR collection,
764
1075
  18 live collections, the grid and list over them, and hydration,
765
- 19 two tabs of one browser
1076
+ 19 two tabs of one browser, 20–21 read keys, 22 several nodes,
1077
+ 23 wire fidelity, 24 presence, 25 queries reading presence,
1078
+ 26 scheduler
766
1079
  example/demo.ts runnable walkthrough of the engine under the framework
767
1080
  example/contract-demo.ts the same story through contracts, with nothing declared
768
1081
  example-next/ a Next.js application: SSR, optimistic edits, access revoked live,
@@ -70,6 +70,8 @@ export declare class NowityConnection implements QuerySource {
70
70
  connect(): void;
71
71
  /** {@link QuerySource.hydrate} — the store's own, so both sources seed alike. */
72
72
  hydrate(payloads: HydrationPayload[]): void;
73
+ /** See {@link NowityClient.setContext}. */
74
+ setContext(context: Record<string, unknown> | null): void;
73
75
  close(): void;
74
76
  private adoptManifest;
75
77
  /** The proxy for a service, by its token. */
@@ -1 +1 @@
1
- {"version":3,"file":"connection.d.ts","sourceRoot":"","sources":["../../src/client/connection.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,OAAO,EAA0C,KAAK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AiF;IACjF,OAAO,CAAC,QAAQ,EAAE,gBAAgB,EAAE,GAAG,IAAI;IAI3C,2CAA2C;IAC3C,UAAU,CAAC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,GAAG,IAAI;IAIzD,KAAK,IAAI,IAAI;IAMb,OAAO,CAAC,aAAa;IAWrB,6CAA6C;IAC7C,OAAO,CAAC,CAAC,SAAS,MAAM,EAAE,KAAK,EAAE,QAAQ,MAAM,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,CAAC,GAAG,CAAC;IAIvE;;;;;;;OAOG;IACH,QAAQ,CAAC,CAAC,SAAS,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,CAAC;IAuB3C,OAAO,CAAC,IAAI;IAON,IAAI,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC,OAAO,CAAC;YA0B7C,MAAM;IAepB;;;;;;OAMG;IACH,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,GAAG,SAAS;IAehD,MAAM,CAAC,KAAK,EAAE,SAAS,GAAG,IAAI;IAK9B,OAAO,CAAC,KAAK,EAAE,SAAS,GAAG,IAAI;IAK/B,OAAO,CAAC,eAAe;IAsBvB,OAAO,CAAC,UAAU;CAMrB"}
@@ -75,6 +75,15 @@ class LiveEntry {
75
75
  }
76
76
  /** Called once the server has said whether this endpoint returns one row. */
77
77
  watchCardinality(isSingle) {
78
+ // Known already (hydrated from the SSR snapshot): set it now. A `when`
79
+ // created during an observer render runs only after the surrounding batch,
80
+ // so that render would hand out the row list instead of the single row —
81
+ // a hydration mismatch against the server render.
82
+ const known = isSingle();
83
+ if (known !== undefined) {
84
+ this.single = known === true;
85
+ return;
86
+ }
78
87
  this.stopCardinality = (0, mobx_1.when)(() => isSingle() !== undefined, () => {
79
88
  this.single = isSingle() === true;
80
89
  });
@@ -141,6 +150,10 @@ class NowityConnection {
141
150
  hydrate(payloads) {
142
151
  this.client.hydrate(payloads);
143
152
  }
153
+ /** See {@link NowityClient.setContext}. */
154
+ setContext(context) {
155
+ this.client.setContext(context);
156
+ }
144
157
  close() {
145
158
  for (const entry of this.entries.values())
146
159
  entry.dispose();
@@ -51,6 +51,15 @@ export interface NowityClientOptions {
51
51
  minDelayMs?: number;
52
52
  maxDelayMs?: number;
53
53
  } | false;
54
+ /**
55
+ * The context the first hello already carries (see {@link NowityClient.setContext}).
56
+ *
57
+ * What a page knows before it connects — its own path — belongs here: the
58
+ * new connection is then recorded with it, and a reload is no change for
59
+ * anyone reading presence. Set after the socket opened, it is one write
60
+ * later, and a reload shows up as the context going and coming back.
61
+ */
62
+ context?: Record<string, unknown> | null;
54
63
  onError?: (error: Error) => void;
55
64
  /** Observability hook: every message received, before it is applied. */
56
65
  onServerMessage?: (message: ServerMessage) => void;
@@ -125,12 +134,26 @@ export declare class NowityClient {
125
134
  private intentionalClose;
126
135
  private connected;
127
136
  private everWelcomed;
137
+ /** What this connection says it is looking at; resent after every reconnect. */
138
+ private context;
128
139
  constructor(opts: NowityClientOptions);
129
140
  connect(): void;
130
141
  close(): void;
131
142
  /** Drop the connection as if the network died. For tests and for retry UX. */
132
143
  dropConnection(): void;
133
144
  private handleOpen;
145
+ /**
146
+ * Tell the server what this connection is looking at — `{ path }`, a game
147
+ * id — so that a server reading presence can show it (`Presence.contexts`).
148
+ *
149
+ * Sent only when it changed, kept across reconnects of this client (it
150
+ * rides on the hello), and cleared with `null`. It describes this socket,
151
+ * not the user: two tabs have two contexts. A server without presence
152
+ * ignores it. Called before `connect()` it goes out with the first hello —
153
+ * as does the `context` option — which is what keeps a page reload from
154
+ * being a change of context; called later, it is a separate message.
155
+ */
156
+ setContext(context: Record<string, unknown> | null): void;
134
157
  private handleClose;
135
158
  private send;
136
159
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"nowity-client.d.ts","sourceRoot":"","sources":["../../src/client/nowity-client.ts"],"names":[],"mappings":"AA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CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,GAAG,SAAS;IAI5C,OAAO,CAAC,SAAS;IASjB,OAAO,CAAC,YAAY;IAMpB,8EAA8E;IAC9E,IAAI,oBAAoB,IAAI,MAAM,CAEjC;IAED,IAAI,WAAW,IAAI,OAAO,CAEzB;IAED,0EAA0E;IAC1E,aAAa,CAAC,OAAO,EAAE,aAAa,GAAG,IAAI;CAG9C;AAED;;;;;GAKG;AACH,wBAAgB,eAAe,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,GAAG,MAAM,CAEpE"}
@@ -77,6 +77,8 @@ class NowityClient {
77
77
  this.intentionalClose = false;
78
78
  this.connected = false;
79
79
  this.everWelcomed = false;
80
+ /** What this connection says it is looking at; resent after every reconnect. */
81
+ this.context = null;
80
82
  /** Rebuild the overlay from confirmed state plus pending mutations. */
81
83
  this.rebase = (0, mobx_1.action)(() => {
82
84
  this.pendingBox.set(this.pending.length > 0);
@@ -99,6 +101,7 @@ class NowityClient {
99
101
  });
100
102
  this.opts = opts;
101
103
  this.onError = opts.onError ?? ((err) => console.error("[nowity/client]", err));
104
+ this.context = opts.context ?? null;
102
105
  for (const mutator of opts.mutators ?? []) {
103
106
  this.mutators.set(mutator.name, mutator);
104
107
  }
@@ -137,7 +140,32 @@ class NowityClient {
137
140
  this.connected = true;
138
141
  this.reconnectAttempt = 0;
139
142
  (0, mobx_1.runInAction)(() => this.status.set("connected"));
140
- this.send({ t: "hello", v: protocol_1.PROTOCOL_VERSION, clientId: this.opts.clientId });
143
+ // The context rides on the hello: the server forgets it with the old
144
+ // socket, and a new socket has to be told before it is recorded.
145
+ this.send({
146
+ t: "hello",
147
+ v: protocol_1.PROTOCOL_VERSION,
148
+ clientId: this.opts.clientId,
149
+ ...(this.context !== null ? { context: this.context } : {}),
150
+ });
151
+ }
152
+ /**
153
+ * Tell the server what this connection is looking at — `{ path }`, a game
154
+ * id — so that a server reading presence can show it (`Presence.contexts`).
155
+ *
156
+ * Sent only when it changed, kept across reconnects of this client (it
157
+ * rides on the hello), and cleared with `null`. It describes this socket,
158
+ * not the user: two tabs have two contexts. A server without presence
159
+ * ignores it. Called before `connect()` it goes out with the first hello —
160
+ * as does the `context` option — which is what keeps a page reload from
161
+ * being a change of context; called later, it is a separate message.
162
+ */
163
+ setContext(context) {
164
+ if (JSON.stringify(context) === JSON.stringify(this.context))
165
+ return;
166
+ this.context = context;
167
+ if (this.connected)
168
+ this.send({ t: "context", context });
141
169
  }
142
170
  handleClose() {
143
171
  this.connected = false;
@@ -1,13 +1,55 @@
1
1
  import type { EntityId, Row } from "../core/types";
2
2
  import type { ConfirmedStore } from "./confirmed-store";
3
+ /**
4
+ * Optionally maps entity names to their row types, so `tx.of("Score")` knows
5
+ * its fields. Augment it from application code:
6
+ *
7
+ * declare module "nowity/client" {
8
+ * interface LocalEntities { Score: { id: string; points: number } }
9
+ * }
10
+ *
11
+ * Left empty, `of` takes a row type as a type argument instead.
12
+ */
13
+ export interface LocalEntities {
14
+ }
15
+ /**
16
+ * A row as a mutator sees it: reads give the row's current value (confirmed data
17
+ * plus whatever earlier mutators staged), assignments stage a change.
18
+ *
19
+ * It is not the live MobX object the UI holds. Those are the *output* of a
20
+ * rebase and are rebuilt from it, so a write there would be gone on the next
21
+ * message; a draft writes into the overlay, which is what the rebase replays.
22
+ */
23
+ export type Draft<T extends Row = Row> = T;
24
+ /** The rows of one entity, as a mutator sees them. */
25
+ export interface EntityTx<T extends Row = Row> {
26
+ /** The row, or undefined if it is not loaded. Assign to its fields to change it. */
27
+ get(id: EntityId): Draft<T> | undefined;
28
+ all(): Draft<T>[];
29
+ /** Insert a row that does not exist yet. An existing id is replaced whole. */
30
+ create(row: T): void;
31
+ remove(id: EntityId): void;
32
+ }
3
33
  /** Write surface a client-side mutator gets. */
4
34
  export interface LocalTx {
35
+ /** The rows of one entity: `tx.of("Score").get(id).points += delta`. */
36
+ of<K extends keyof LocalEntities>(entity: K): EntityTx<LocalEntities[K] & Row>;
37
+ of<T extends Row = Row>(entity: string): EntityTx<T>;
38
+ /** @deprecated Use `tx.of(entity).get(id)`. */
5
39
  get(entity: string, id: EntityId): Row | undefined;
40
+ /** @deprecated Use `tx.of(entity).all()`. */
6
41
  all(entity: string): Row[];
7
- /** Merge fields into an existing row. No-op if the row is not loaded. */
42
+ /**
43
+ * Merge fields into an existing row. No-op if the row is not loaded.
44
+ * @deprecated Assign to the fields of `tx.of(entity).get(id)`.
45
+ */
8
46
  update(entity: string, id: EntityId, fields: Row): void;
9
- /** Insert or replace a whole row. */
47
+ /**
48
+ * Insert or replace a whole row.
49
+ * @deprecated Use `tx.of(entity).create(row)`, or assign to the fields of the row.
50
+ */
10
51
  put(entity: string, row: Row): void;
52
+ /** @deprecated Use `tx.of(entity).remove(id)`. */
11
53
  remove(entity: string, id: EntityId): void;
12
54
  }
13
55
  /**
@@ -25,6 +67,14 @@ export declare class Overlay {
25
67
  private readonly changes;
26
68
  constructor(confirmed: ConfirmedStore, idFieldOf: (entity: string) => string);
27
69
  tx(): LocalTx;
70
+ private entityTx;
71
+ /**
72
+ * A view of one row that reads through to the overlay on every access, so
73
+ * it stays right as later writes land and a row removed meanwhile reads as
74
+ * empty. Writes to a row that is gone are dropped, like `update` on one that
75
+ * is not loaded.
76
+ */
77
+ private draft;
28
78
  get(entity: string, id: EntityId): Row | undefined;
29
79
  /**
30
80
  * Rows a pending mutation created, per entity.
@@ -1 +1 @@
1
- {"version":3,"file":"overlay.d.ts","sourceRoot":"","sources":["../../src/client/overlay.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,GAAG,EAAE,MAAM,eAAe,CAAC;AACnD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAExD,gDAAgD;AAChD,MAAM,WAAW,OAAO;IACpB,GAAG,CAAC,MAAM,EAAE,MAAM,EAAE,EAAE,EAAE,QAAQ,GAAG,GAAG,GAAG,SAAS,CAAC;IACnD,GAAG,CAAC,MAA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