nowity 1.0.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 (192) hide show
  1. package/README.md +751 -0
  2. package/dist/api/contract.d.ts +186 -0
  3. package/dist/api/contract.d.ts.map +1 -0
  4. package/dist/api/contract.js +251 -0
  5. package/dist/api/errors.d.ts +50 -0
  6. package/dist/api/errors.d.ts.map +1 -0
  7. package/dist/api/errors.js +50 -0
  8. package/dist/api/index.d.ts +13 -0
  9. package/dist/api/index.d.ts.map +1 -0
  10. package/dist/api/index.js +32 -0
  11. package/dist/client/confirmed-store.d.ts +33 -0
  12. package/dist/client/confirmed-store.d.ts.map +1 -0
  13. package/dist/client/confirmed-store.js +123 -0
  14. package/dist/client/connection.d.ts +102 -0
  15. package/dist/client/connection.d.ts.map +1 -0
  16. package/dist/client/connection.js +285 -0
  17. package/dist/client/list.d.ts +102 -0
  18. package/dist/client/list.d.ts.map +1 -0
  19. package/dist/client/list.js +257 -0
  20. package/dist/client/live-query.d.ts +153 -0
  21. package/dist/client/live-query.d.ts.map +1 -0
  22. package/dist/client/live-query.js +244 -0
  23. package/dist/client/nowity-client.d.ts +188 -0
  24. package/dist/client/nowity-client.d.ts.map +1 -0
  25. package/dist/client/nowity-client.js +580 -0
  26. package/dist/client/null-transport.d.ts +16 -0
  27. package/dist/client/null-transport.d.ts.map +1 -0
  28. package/dist/client/null-transport.js +17 -0
  29. package/dist/client/overlay.d.ts +44 -0
  30. package/dist/client/overlay.d.ts.map +1 -0
  31. package/dist/client/overlay.js +90 -0
  32. package/dist/client/query-source.d.ts +78 -0
  33. package/dist/client/query-source.d.ts.map +1 -0
  34. package/dist/client/query-source.js +57 -0
  35. package/dist/client/ssr-source.d.ts +70 -0
  36. package/dist/client/ssr-source.d.ts.map +1 -0
  37. package/dist/client/ssr-source.js +134 -0
  38. package/dist/client/transport.d.ts +19 -0
  39. package/dist/client/transport.d.ts.map +1 -0
  40. package/dist/client/transport.js +2 -0
  41. package/dist/client/ws-transport.d.ts +30 -0
  42. package/dist/client/ws-transport.d.ts.map +1 -0
  43. package/dist/client/ws-transport.js +89 -0
  44. package/dist/client.d.ts +47 -0
  45. package/dist/client.d.ts.map +1 -0
  46. package/dist/client.js +80 -0
  47. package/dist/core/diff.d.ts +14 -0
  48. package/dist/core/diff.d.ts.map +1 -0
  49. package/dist/core/diff.js +56 -0
  50. package/dist/core/normalize.d.ts +16 -0
  51. package/dist/core/normalize.d.ts.map +1 -0
  52. package/dist/core/normalize.js +67 -0
  53. package/dist/core/protocol.d.ts +215 -0
  54. package/dist/core/protocol.d.ts.map +1 -0
  55. package/dist/core/protocol.js +14 -0
  56. package/dist/core/ssr-bridge.d.ts +69 -0
  57. package/dist/core/ssr-bridge.d.ts.map +1 -0
  58. package/dist/core/ssr-bridge.js +40 -0
  59. package/dist/core/types.d.ts +96 -0
  60. package/dist/core/types.d.ts.map +1 -0
  61. package/dist/core/types.js +17 -0
  62. package/dist/index.d.ts +47 -0
  63. package/dist/index.d.ts.map +1 -0
  64. package/dist/index.js +98 -0
  65. package/dist/ironbean/client.d.ts +7 -0
  66. package/dist/ironbean/client.d.ts.map +1 -0
  67. package/dist/ironbean/client.js +38 -0
  68. package/dist/ironbean/server.d.ts +42 -0
  69. package/dist/ironbean/server.d.ts.map +1 -0
  70. package/dist/ironbean/server.js +62 -0
  71. package/dist/ironbean/tokens.d.ts +26 -0
  72. package/dist/ironbean/tokens.d.ts.map +1 -0
  73. package/dist/ironbean/tokens.js +23 -0
  74. package/dist/next/config.d.ts +7 -0
  75. package/dist/next/config.d.ts.map +1 -0
  76. package/dist/next/config.js +77 -0
  77. package/dist/next/live.d.ts +69 -0
  78. package/dist/next/live.d.ts.map +1 -0
  79. package/dist/next/live.js +70 -0
  80. package/dist/next/serve.d.ts +44 -0
  81. package/dist/next/serve.d.ts.map +1 -0
  82. package/dist/next/serve.js +107 -0
  83. package/dist/next/server.d.ts +62 -0
  84. package/dist/next/server.d.ts.map +1 -0
  85. package/dist/next/server.js +127 -0
  86. package/dist/react/connection-context.d.ts +4 -0
  87. package/dist/react/connection-context.d.ts.map +1 -0
  88. package/dist/react/connection-context.js +28 -0
  89. package/dist/react/grid-list.d.ts +34 -0
  90. package/dist/react/grid-list.d.ts.map +1 -0
  91. package/dist/react/grid-list.js +62 -0
  92. package/dist/react/hydrate.d.ts +22 -0
  93. package/dist/react/hydrate.d.ts.map +1 -0
  94. package/dist/react/hydrate.js +18 -0
  95. package/dist/react/index.d.ts +35 -0
  96. package/dist/react/index.d.ts.map +1 -0
  97. package/dist/react/index.js +51 -0
  98. package/dist/react/list.d.ts +31 -0
  99. package/dist/react/list.d.ts.map +1 -0
  100. package/dist/react/list.js +35 -0
  101. package/dist/react/prerendered.d.ts +33 -0
  102. package/dist/react/prerendered.d.ts.map +1 -0
  103. package/dist/react/prerendered.js +165 -0
  104. package/dist/react/provider.d.ts +64 -0
  105. package/dist/react/provider.d.ts.map +1 -0
  106. package/dist/react/provider.js +130 -0
  107. package/dist/react/refusals.d.ts +31 -0
  108. package/dist/react/refusals.d.ts.map +1 -0
  109. package/dist/react/refusals.js +51 -0
  110. package/dist/react/restricted.d.ts +76 -0
  111. package/dist/react/restricted.d.ts.map +1 -0
  112. package/dist/react/restricted.js +126 -0
  113. package/dist/react/use-list.d.ts +42 -0
  114. package/dist/react/use-list.d.ts.map +1 -0
  115. package/dist/react/use-list.js +56 -0
  116. package/dist/react/use-query.d.ts +66 -0
  117. package/dist/react/use-query.d.ts.map +1 -0
  118. package/dist/react/use-query.js +126 -0
  119. package/dist/react/virtual.d.ts +60 -0
  120. package/dist/react/virtual.d.ts.map +1 -0
  121. package/dist/react/virtual.js +131 -0
  122. package/dist/server/api/auth.d.ts +37 -0
  123. package/dist/server/api/auth.d.ts.map +1 -0
  124. package/dist/server/api/auth.js +54 -0
  125. package/dist/server/api/bridge.d.ts +28 -0
  126. package/dist/server/api/bridge.d.ts.map +1 -0
  127. package/dist/server/api/bridge.js +330 -0
  128. package/dist/server/api/collector.d.ts +25 -0
  129. package/dist/server/api/collector.d.ts.map +1 -0
  130. package/dist/server/api/collector.js +184 -0
  131. package/dist/server/api/configure.d.ts +31 -0
  132. package/dist/server/api/configure.d.ts.map +1 -0
  133. package/dist/server/api/configure.js +67 -0
  134. package/dist/server/api/execution.d.ts +77 -0
  135. package/dist/server/api/execution.d.ts.map +1 -0
  136. package/dist/server/api/execution.js +97 -0
  137. package/dist/server/api/list.d.ts +141 -0
  138. package/dist/server/api/list.d.ts.map +1 -0
  139. package/dist/server/api/list.js +281 -0
  140. package/dist/server/api/prerender.d.ts +32 -0
  141. package/dist/server/api/prerender.d.ts.map +1 -0
  142. package/dist/server/api/prerender.js +69 -0
  143. package/dist/server/api/read-keys.d.ts +128 -0
  144. package/dist/server/api/read-keys.d.ts.map +1 -0
  145. package/dist/server/api/read-keys.js +464 -0
  146. package/dist/server/api/read-set.d.ts +103 -0
  147. package/dist/server/api/read-set.d.ts.map +1 -0
  148. package/dist/server/api/read-set.js +210 -0
  149. package/dist/server/api/runtime.d.ts +36 -0
  150. package/dist/server/api/runtime.d.ts.map +1 -0
  151. package/dist/server/api/runtime.js +49 -0
  152. package/dist/server/api/tracked-client.d.ts +6 -0
  153. package/dist/server/api/tracked-client.d.ts.map +1 -0
  154. package/dist/server/api/tracked-client.js +56 -0
  155. package/dist/server/change-source/change-source.d.ts +41 -0
  156. package/dist/server/change-source/change-source.d.ts.map +1 -0
  157. package/dist/server/change-source/change-source.js +2 -0
  158. package/dist/server/change-source/outbox-change-source.d.ts +106 -0
  159. package/dist/server/change-source/outbox-change-source.d.ts.map +1 -0
  160. package/dist/server/change-source/outbox-change-source.js +237 -0
  161. package/dist/server/change-source/wal-change-source.d.ts +85 -0
  162. package/dist/server/change-source/wal-change-source.d.ts.map +1 -0
  163. package/dist/server/change-source/wal-change-source.js +193 -0
  164. package/dist/server/db.d.ts +51 -0
  165. package/dist/server/db.d.ts.map +1 -0
  166. package/dist/server/db.js +53 -0
  167. package/dist/server/evaluate.d.ts +39 -0
  168. package/dist/server/evaluate.d.ts.map +1 -0
  169. package/dist/server/evaluate.js +61 -0
  170. package/dist/server/invalidation-index.d.ts +64 -0
  171. package/dist/server/invalidation-index.d.ts.map +1 -0
  172. package/dist/server/invalidation-index.js +0 -0
  173. package/dist/server/mutator.d.ts +59 -0
  174. package/dist/server/mutator.d.ts.map +1 -0
  175. package/dist/server/mutator.js +77 -0
  176. package/dist/server/query.d.ts +113 -0
  177. package/dist/server/query.d.ts.map +1 -0
  178. package/dist/server/query.js +35 -0
  179. package/dist/server/setup.d.ts +30 -0
  180. package/dist/server/setup.d.ts.map +1 -0
  181. package/dist/server/setup.js +107 -0
  182. package/dist/server/sql/setup.sql +215 -0
  183. package/dist/server/ssr.d.ts +29 -0
  184. package/dist/server/ssr.d.ts.map +1 -0
  185. package/dist/server/ssr.js +43 -0
  186. package/dist/server/sync-engine.d.ts +256 -0
  187. package/dist/server/sync-engine.d.ts.map +1 -0
  188. package/dist/server/sync-engine.js +805 -0
  189. package/dist/server/ws-server.d.ts +56 -0
  190. package/dist/server/ws-server.d.ts.map +1 -0
  191. package/dist/server/ws-server.js +241 -0
  192. package/package.json +81 -0
@@ -0,0 +1,580 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.NowityClient = void 0;
4
+ exports.subscriptionKey = subscriptionKey;
5
+ const mobx_1 = require("mobx");
6
+ const protocol_1 = require("../core/protocol");
7
+ const confirmed_store_1 = require("./confirmed-store");
8
+ const live_query_1 = require("./live-query");
9
+ const overlay_1 = require("./overlay");
10
+ /** Shared empty result, so a query with no local inserts allocates nothing. */
11
+ const EMPTY_IDS = [];
12
+ /**
13
+ * The client half of Nowity: a MobX object graph kept in sync with Postgres.
14
+ *
15
+ * State is layered, and the layering is the whole design:
16
+ *
17
+ * confirmed (plain data from the server)
18
+ * + pending mutations replayed on top → overlay
19
+ * → reconciled into the MobX identity map that the UI observes
20
+ *
21
+ * Every server message rebuilds the overlay from scratch and replays whatever is
22
+ * still unconfirmed. That single mechanism gives optimistic writes, rollback of
23
+ * rejected writes, and immunity to the echo of your own write — an incoming patch
24
+ * can never clobber a local change that has not been confirmed yet, because local
25
+ * changes are always re-applied last.
26
+ */
27
+ class NowityClient {
28
+ constructor(opts) {
29
+ this.status = mobx_1.observable.box("idle");
30
+ this.confirmed = new confirmed_store_1.ConfirmedStore();
31
+ this.entityMaps = new Map();
32
+ this.fieldsOf = new WeakMap();
33
+ this.subs = new Map();
34
+ this.mutators = new Map();
35
+ /** Server-rendered results waiting to be claimed by a matching subscribe. */
36
+ this.hydrationByKey = new Map();
37
+ /**
38
+ * Entity shapes announced by the server, derived there from the database
39
+ * schema. Explicit `entities` in the options still win — the server's version
40
+ * is a default, not an override.
41
+ */
42
+ this.serverEntities = {};
43
+ this.pending = [];
44
+ /**
45
+ * Whether anything written here is still unconfirmed, as an observable.
46
+ *
47
+ * Read by every live query that knows its ordering: while it is true, a row
48
+ * this browser changed is placed by that ordering rather than by the
49
+ * server's list, which is a moment out of date by definition.
50
+ */
51
+ this.pendingBox = mobx_1.observable.box(false);
52
+ /** Rows created here and not yet confirmed, per entity. Rebuilt on every rebase. */
53
+ this.localInserts = new Map();
54
+ this.lastMutationId = 0;
55
+ /**
56
+ * Subscriptions re-requested after a reconnect that have not been answered
57
+ * yet. While this is non-empty the client's confirmed data is older than the
58
+ * server's mutation watermark, so acks are held back (see {@link ackThrough}).
59
+ */
60
+ this.resyncPending = new Set();
61
+ this.deferredAck = -1;
62
+ this.subCounter = 0;
63
+ this.reconnectAttempt = 0;
64
+ this.reconnectTimer = null;
65
+ this.intentionalClose = false;
66
+ this.connected = false;
67
+ this.everWelcomed = false;
68
+ /** Rebuild the overlay from confirmed state plus pending mutations. */
69
+ this.rebase = (0, mobx_1.action)(() => {
70
+ this.pendingBox.set(this.pending.length > 0);
71
+ const overlay = new overlay_1.Overlay(this.confirmed, (entity) => this.idFieldOf(entity));
72
+ for (const mutation of this.pending) {
73
+ const def = this.mutators.get(mutation.name);
74
+ if (!def)
75
+ continue;
76
+ try {
77
+ def.local(mutation.args, overlay.tx());
78
+ }
79
+ catch (err) {
80
+ this.onError(err);
81
+ }
82
+ }
83
+ // Recorded before reconciling, so a window recomputing off the identity
84
+ // map below already sees which of its rows are local.
85
+ this.localInserts = overlay.inserted();
86
+ this.reconcile(overlay);
87
+ });
88
+ this.opts = opts;
89
+ this.onError = opts.onError ?? ((err) => console.error("[nowity/client]", err));
90
+ for (const mutator of opts.mutators ?? []) {
91
+ this.mutators.set(mutator.name, mutator);
92
+ }
93
+ }
94
+ // ------------------------------------------------------------------ connection
95
+ connect() {
96
+ // Idempotent. A second call would build a second socket and orphan the
97
+ // first, which stays open on the server — two connections where the
98
+ // client believes it has one.
99
+ const status = this.status.get();
100
+ if (status === "connecting" || status === "connected")
101
+ return;
102
+ this.intentionalClose = false;
103
+ (0, mobx_1.runInAction)(() => this.status.set("connecting"));
104
+ this.opts.transport.connect({
105
+ onOpen: () => this.handleOpen(),
106
+ onMessage: (message) => this.handleMessage(message),
107
+ onClose: () => this.handleClose(),
108
+ onError: (err) => this.onError(err),
109
+ });
110
+ }
111
+ close() {
112
+ this.intentionalClose = true;
113
+ if (this.reconnectTimer)
114
+ clearTimeout(this.reconnectTimer);
115
+ this.reconnectTimer = null;
116
+ this.opts.transport.close();
117
+ (0, mobx_1.runInAction)(() => this.status.set("idle"));
118
+ }
119
+ /** Drop the connection as if the network died. For tests and for retry UX. */
120
+ dropConnection() {
121
+ this.intentionalClose = false;
122
+ this.opts.transport.close();
123
+ }
124
+ handleOpen() {
125
+ this.connected = true;
126
+ this.reconnectAttempt = 0;
127
+ (0, mobx_1.runInAction)(() => this.status.set("connected"));
128
+ this.send({ t: "hello", v: protocol_1.PROTOCOL_VERSION, clientId: this.opts.clientId });
129
+ }
130
+ handleClose() {
131
+ this.connected = false;
132
+ (0, mobx_1.runInAction)(() => this.status.set(this.intentionalClose ? "idle" : "disconnected"));
133
+ if (this.intentionalClose)
134
+ return;
135
+ // Not "wrong", but possibly no longer current — the UI can dim it.
136
+ (0, mobx_1.runInAction)(() => {
137
+ for (const sub of this.subs.values()) {
138
+ if (sub.status.get() === "ready")
139
+ sub.status.set("stale");
140
+ }
141
+ });
142
+ if (this.opts.reconnect === false)
143
+ return;
144
+ const min = this.opts.reconnect?.minDelayMs ?? 50;
145
+ const max = this.opts.reconnect?.maxDelayMs ?? 5000;
146
+ const delay = Math.min(max, min * 2 ** this.reconnectAttempt);
147
+ this.reconnectAttempt += 1;
148
+ this.reconnectTimer = setTimeout(() => {
149
+ this.reconnectTimer = null;
150
+ this.connect();
151
+ }, delay);
152
+ }
153
+ send(message) {
154
+ this.opts.transport.send(message);
155
+ }
156
+ // --------------------------------------------------------------- subscriptions
157
+ /**
158
+ * Seed the store with data rendered on the server (`readInitialData`).
159
+ *
160
+ * A payload is consumed by the first `subscribe()` for the same query and
161
+ * arguments, so the first render already has rows — before the socket is even
162
+ * open. It is then replaced by the server's authoritative snapshot.
163
+ */
164
+ hydrate(payloads) {
165
+ for (const payload of payloads) {
166
+ this.hydrationByKey.set(subscriptionKey(payload.query, payload.args), payload);
167
+ }
168
+ }
169
+ subscribe(query, args = {}) {
170
+ const subId = `s${++this.subCounter}`;
171
+ const descriptor = this.opts.queries?.[query] ?? {};
172
+ const state = {
173
+ subId,
174
+ query,
175
+ args,
176
+ // Authoritative value arrives with the snapshot; never guessed from the
177
+ // query name, which would silently read an entity map that stays empty.
178
+ entity: mobx_1.observable.box(descriptor.entity ?? ""),
179
+ order: mobx_1.observable.box(null),
180
+ filter: mobx_1.observable.box(null),
181
+ descriptor,
182
+ ids: mobx_1.observable.array([], { deep: false }),
183
+ epoch: 0,
184
+ scope: null,
185
+ status: mobx_1.observable.box("loading"),
186
+ error: mobx_1.observable.box(null),
187
+ single: mobx_1.observable.box(undefined),
188
+ };
189
+ this.subs.set(subId, state);
190
+ const live = new live_query_1.LiveQuery(state, {
191
+ mapFor: (entity) => this.mapFor(entity),
192
+ hasPending: () => this.pendingBox.get(),
193
+ pendingInserts: (entity) => this.localInserts.get(entity) ?? EMPTY_IDS,
194
+ dispose: () => this.unsubscribe(subId),
195
+ });
196
+ const hydrationKey = subscriptionKey(query, args);
197
+ const payload = this.hydrationByKey.get(hydrationKey);
198
+ if (payload) {
199
+ // Server-rendered data is used once. Keeping it would resurrect stale
200
+ // rows on a later subscription to the same query.
201
+ this.hydrationByKey.delete(hydrationKey);
202
+ (0, mobx_1.runInAction)(() => {
203
+ if (payload.denied) {
204
+ this.applyRevoked(subId, "not-authorized");
205
+ }
206
+ else {
207
+ this.applySnapshot({ ...payload, subId, reason: "initial" });
208
+ }
209
+ this.rebase();
210
+ });
211
+ }
212
+ this.send({ t: "subscribe", subId, query, args });
213
+ return live;
214
+ }
215
+ unsubscribe(subId) {
216
+ const sub = this.subs.get(subId);
217
+ if (!sub)
218
+ return;
219
+ this.subs.delete(subId);
220
+ this.send({ t: "unsubscribe", subId });
221
+ this.resolveResync(subId);
222
+ (0, mobx_1.runInAction)(() => {
223
+ this.confirmed.releaseSub(subId);
224
+ this.rebase();
225
+ });
226
+ }
227
+ // ------------------------------------------------------------------- mutations
228
+ /**
229
+ * Run a named mutator: optimistically now, authoritatively on the server.
230
+ *
231
+ * The returned promise settles when the server has decided. It rejects if the
232
+ * mutation was refused — by then the optimistic effect is already undone.
233
+ */
234
+ mutate(name, args) {
235
+ // A mutation with no local counterpart is legal: it simply has no
236
+ // optimistic effect and lands when the server confirms it. Refusing it
237
+ // here would make every write opt into optimism, which is backwards.
238
+ const mutationId = ++this.lastMutationId;
239
+ return new Promise((resolve, reject) => {
240
+ this.pending.push({ mutationId, name, args, resolve, reject });
241
+ (0, mobx_1.runInAction)(() => this.rebase());
242
+ this.send({ t: "mutate", mutationId, name, args });
243
+ });
244
+ }
245
+ // -------------------------------------------------------------------- messages
246
+ handleMessage(message) {
247
+ try {
248
+ this.opts.onServerMessage?.(message);
249
+ switch (message.t) {
250
+ case "welcome":
251
+ this.handleWelcome(message);
252
+ break;
253
+ case "snapshot":
254
+ this.handleSnapshotMessage(message);
255
+ break;
256
+ case "tx":
257
+ (0, mobx_1.runInAction)(() => {
258
+ for (const revoked of message.revoked ?? []) {
259
+ this.applyRevoked(revoked.subId, revoked.reason);
260
+ }
261
+ for (const snapshot of message.snapshots ?? []) {
262
+ this.applySnapshot(snapshot);
263
+ }
264
+ for (const patch of message.patches) {
265
+ this.applyPatch(patch);
266
+ }
267
+ this.ackThrough(message.lastMutationId);
268
+ this.rebase();
269
+ });
270
+ break;
271
+ case "mutation-result":
272
+ this.handleMutationResult(message.mutationId, message.ok, message.error);
273
+ break;
274
+ case "error":
275
+ this.handleServerError(message.subId, message.message);
276
+ break;
277
+ }
278
+ }
279
+ catch (err) {
280
+ this.onError(err);
281
+ }
282
+ }
283
+ handleWelcome(message) {
284
+ const serverLastMutationId = message.lastMutationId;
285
+ if (message.api?.entities) {
286
+ this.serverEntities = message.api.entities;
287
+ }
288
+ this.opts.onWelcome?.(message.api);
289
+ // Every subscription is about to be re-requested. Until its fresh snapshot
290
+ // lands, the store still holds pre-outage data, so the server's mutation
291
+ // watermark says nothing about what this client can see yet.
292
+ this.resyncPending = new Set(this.subs.keys());
293
+ (0, mobx_1.runInAction)(() => {
294
+ // Mutation ids must keep climbing across reconnects, otherwise the
295
+ // server sees a gap (or a replay) and rejects the numbering.
296
+ this.lastMutationId = Math.max(this.lastMutationId, serverLastMutationId);
297
+ this.ackThrough(serverLastMutationId);
298
+ this.rebase();
299
+ });
300
+ // Re-send everything the server has not seen, then re-establish the
301
+ // subscriptions. Snapshots recomputed afterwards may or may not already
302
+ // contain these mutations; whichever way, the reported lastMutationId says
303
+ // which of them may leave the pending queue.
304
+ for (const mutation of this.pending) {
305
+ this.send({
306
+ t: "mutate",
307
+ mutationId: mutation.mutationId,
308
+ name: mutation.name,
309
+ args: mutation.args,
310
+ });
311
+ }
312
+ if (this.everWelcomed) {
313
+ // Only after a reconnect. On the first welcome the subscriptions were
314
+ // already sent (queued by the transport if the socket was not open yet),
315
+ // and re-sending them would cost a second snapshot of everything.
316
+ for (const sub of this.subs.values()) {
317
+ this.send({ t: "subscribe", subId: sub.subId, query: sub.query, args: sub.args });
318
+ }
319
+ }
320
+ this.everWelcomed = true;
321
+ }
322
+ handleSnapshotMessage(message) {
323
+ (0, mobx_1.runInAction)(() => {
324
+ this.applySnapshot(message);
325
+ this.ackThrough(message.lastMutationId);
326
+ this.rebase();
327
+ });
328
+ }
329
+ applySnapshot(snapshot) {
330
+ const sub = this.subs.get(snapshot.subId);
331
+ if (!sub)
332
+ return;
333
+ sub.entity.set(snapshot.entity);
334
+ sub.epoch = snapshot.epoch;
335
+ sub.scope = snapshot.scope;
336
+ this.confirmed.setSnapshot(snapshot.subId, snapshot.entity, snapshot.rows, this.idFieldOf(snapshot.entity));
337
+ for (const [entity, rows] of Object.entries(snapshot.extra ?? {})) {
338
+ this.confirmed.setSnapshot(snapshot.subId, entity, rows, this.idFieldOf(entity));
339
+ }
340
+ sub.ids.replace(snapshot.ids);
341
+ sub.single.set(snapshot.single === true);
342
+ if (snapshot.order)
343
+ sub.order.set(snapshot.order);
344
+ if (snapshot.filter)
345
+ sub.filter.set(snapshot.filter);
346
+ sub.status.set("ready");
347
+ sub.error.set(null);
348
+ this.resolveResync(snapshot.subId);
349
+ }
350
+ applyPatch(patch) {
351
+ const sub = this.subs.get(patch.subId);
352
+ if (!sub)
353
+ return;
354
+ // Guard against a patch computed before a permission change this client
355
+ // has already been told about (test 4). Without it, a patch that was in
356
+ // flight during an invalidation would resurrect data the client just lost.
357
+ if (patch.epoch < sub.epoch)
358
+ return;
359
+ sub.epoch = patch.epoch;
360
+ sub.entity.set(patch.entity);
361
+ this.confirmed.applyUpsert(patch.subId, patch.entity, patch.upsert);
362
+ this.confirmed.applyRemove(patch.subId, patch.entity, patch.remove);
363
+ for (const [entity, upserts] of Object.entries(patch.extraUpsert ?? {})) {
364
+ this.confirmed.applyUpsert(patch.subId, entity, upserts);
365
+ }
366
+ for (const [entity, ids] of Object.entries(patch.extraRemove ?? {})) {
367
+ this.confirmed.applyRemove(patch.subId, entity, ids);
368
+ }
369
+ // `ids` is sent only when the ordered result actually changed; absent means
370
+ // "same rows in the same order, just different field values".
371
+ if (patch.ids)
372
+ sub.ids.replace(patch.ids);
373
+ }
374
+ applyRevoked(subId, reason) {
375
+ const sub = this.subs.get(subId);
376
+ if (!sub)
377
+ return;
378
+ // Never wait for the server to say which rows to delete — drop the whole
379
+ // slice of the store the subscription was responsible for.
380
+ this.confirmed.releaseSub(subId);
381
+ sub.ids.clear();
382
+ sub.status.set("revoked");
383
+ sub.error.set(reason);
384
+ this.resolveResync(subId);
385
+ }
386
+ handleMutationResult(mutationId, ok, error) {
387
+ const index = this.pending.findIndex((m) => m.mutationId === mutationId);
388
+ if (index === -1)
389
+ return;
390
+ const mutation = this.pending[index];
391
+ if (ok) {
392
+ // Do not drop it yet: the data carrying its effect may still be in
393
+ // flight, and dropping now would make the UI flicker back to the old
394
+ // value. The pending queue is emptied by `ackThrough` when data
395
+ // arrives that already includes this mutation.
396
+ mutation.resolve();
397
+ return;
398
+ }
399
+ (0, mobx_1.runInAction)(() => {
400
+ this.pending.splice(index, 1);
401
+ this.rebase();
402
+ });
403
+ mutation.reject(new Error(error ?? "Mutation rejected"));
404
+ }
405
+ handleServerError(subId, messageText) {
406
+ if (subId) {
407
+ const sub = this.subs.get(subId);
408
+ if (sub) {
409
+ (0, mobx_1.runInAction)(() => {
410
+ sub.status.set("error");
411
+ sub.error.set(messageText);
412
+ });
413
+ }
414
+ }
415
+ this.onError(new Error(messageText));
416
+ }
417
+ /** A re-requested subscription answered; release the ack once all have. */
418
+ resolveResync(subId) {
419
+ if (this.resyncPending.size === 0)
420
+ return;
421
+ this.resyncPending.delete(subId);
422
+ if (this.resyncPending.size > 0)
423
+ return;
424
+ const deferred = this.deferredAck;
425
+ this.deferredAck = -1;
426
+ if (deferred >= 0)
427
+ this.ackThrough(deferred);
428
+ }
429
+ /**
430
+ * Forget mutations whose effect is already contained in confirmed data.
431
+ *
432
+ * Held back while a resync is outstanding: dropping a pending mutation on the
433
+ * strength of a watermark that describes data the client has not received
434
+ * would make the UI fall back to the pre-mutation value until the snapshot
435
+ * arrives — the same flicker the whole rebase mechanism exists to prevent.
436
+ */
437
+ ackThrough(lastMutationId) {
438
+ if (this.resyncPending.size > 0) {
439
+ this.deferredAck = Math.max(this.deferredAck, lastMutationId);
440
+ return;
441
+ }
442
+ if (this.pending.length === 0)
443
+ return;
444
+ const kept = [];
445
+ for (const mutation of this.pending) {
446
+ if (mutation.mutationId <= lastMutationId)
447
+ mutation.resolve();
448
+ else
449
+ kept.push(mutation);
450
+ }
451
+ this.pending = kept;
452
+ }
453
+ // --------------------------------------------------------------- MobX identity
454
+ /** Observable identity map of an entity: id → live object. */
455
+ mapFor(entity) {
456
+ let map = this.entityMaps.get(entity);
457
+ if (!map) {
458
+ map = mobx_1.observable.map(undefined, { deep: false });
459
+ this.entityMaps.set(entity, map);
460
+ }
461
+ return map;
462
+ }
463
+ /** A single live entity instance, or undefined if it is not loaded. */
464
+ entity(entityName, id) {
465
+ return this.mapFor(entityName).get(String(id));
466
+ }
467
+ /** Bring the observable graph in line with the overlay, keeping identities. */
468
+ reconcile(overlay) {
469
+ const entities = new Set([...overlay.entities(), ...this.entityMaps.keys()]);
470
+ for (const entity of entities) {
471
+ const target = overlay.merged(entity);
472
+ const map = this.mapFor(entity);
473
+ for (const [id, row] of target) {
474
+ const existing = map.get(id);
475
+ if (existing)
476
+ this.updateInstance(existing, row);
477
+ else
478
+ map.set(id, this.materialize(entity, row));
479
+ }
480
+ for (const id of [...map.keys()]) {
481
+ if (!target.has(id))
482
+ map.delete(id);
483
+ }
484
+ }
485
+ }
486
+ materialize(entity, row) {
487
+ const instance = mobx_1.observable.object({ ...row }, {}, { deep: false });
488
+ this.fieldsOf.set(instance, new Set(Object.keys(row)));
489
+ const relations = this.descriptorOf(entity).relations;
490
+ for (const [name, relation] of Object.entries(relations ?? {})) {
491
+ // Relations are non-enumerable getters so they never look like data
492
+ // fields to the reconciler; they read the identity map, which is
493
+ // observable, so they stay reactive.
494
+ Object.defineProperty(instance, name, {
495
+ enumerable: false,
496
+ configurable: true,
497
+ get: () => this.resolveRelation(entity, relation, instance),
498
+ });
499
+ }
500
+ return instance;
501
+ }
502
+ updateInstance(instance, row) {
503
+ const known = this.fieldsOf.get(instance) ?? new Set();
504
+ for (const [key, value] of Object.entries(row)) {
505
+ if (!known.has(key)) {
506
+ (0, mobx_1.set)(instance, key, value);
507
+ known.add(key);
508
+ }
509
+ else if (instance[key] !== value) {
510
+ instance[key] = value;
511
+ }
512
+ }
513
+ for (const key of [...known]) {
514
+ if (!(key in row)) {
515
+ (0, mobx_1.remove)(instance, key);
516
+ known.delete(key);
517
+ }
518
+ }
519
+ this.fieldsOf.set(instance, known);
520
+ }
521
+ resolveRelation(entity, relation, instance) {
522
+ const targetMap = this.mapFor(relation.entity);
523
+ if (relation.localKey) {
524
+ const key = instance[relation.localKey];
525
+ return key === null || key === undefined ? undefined : targetMap.get(String(key));
526
+ }
527
+ if (relation.foreignKey) {
528
+ const ownId = String(instance[this.idFieldOf(entity)]);
529
+ const out = [];
530
+ for (const candidate of targetMap.values()) {
531
+ if (String(candidate[relation.foreignKey]) === ownId)
532
+ out.push(candidate);
533
+ }
534
+ return out;
535
+ }
536
+ return undefined;
537
+ }
538
+ /** Whether a subscription's endpoint returns one row; undefined before the snapshot. */
539
+ isSingle(subId) {
540
+ return this.subs.get(subId)?.single.get();
541
+ }
542
+ idFieldOf(entity) {
543
+ return this.descriptorOf(entity).idField ?? "id";
544
+ }
545
+ descriptorOf(entity) {
546
+ return this.opts.entities?.[entity] ?? this.serverEntities[entity] ?? {};
547
+ }
548
+ // ------------------------------------------------------------------ diagnostics
549
+ /** Mutations issued locally that the server's data has not caught up with. */
550
+ get pendingMutationCount() {
551
+ return this.pending.length;
552
+ }
553
+ get isConnected() {
554
+ return this.connected;
555
+ }
556
+ /** Test seam: feed a server message in as if it arrived over the wire. */
557
+ injectMessage(message) {
558
+ this.handleMessage(message);
559
+ }
560
+ }
561
+ exports.NowityClient = NowityClient;
562
+ /**
563
+ * Identity of a subscription for hydration lookup.
564
+ *
565
+ * Argument keys are sorted so that `{a, b}` and `{b, a}` — which any two call
566
+ * sites may produce for the same query — resolve to the same payload.
567
+ */
568
+ function subscriptionKey(query, args) {
569
+ return `${query}|${stableStringify(args)}`;
570
+ }
571
+ function stableStringify(value) {
572
+ if (value === null || typeof value !== "object")
573
+ return JSON.stringify(value) ?? "null";
574
+ if (Array.isArray(value))
575
+ return `[${value.map(stableStringify).join(",")}]`;
576
+ const entries = Object.keys(value)
577
+ .sort()
578
+ .map((key) => `${JSON.stringify(key)}:${stableStringify(value[key])}`);
579
+ return `{${entries.join(",")}}`;
580
+ }
@@ -0,0 +1,16 @@
1
+ import type { ClientMessage } from "../core/protocol";
2
+ import type { Transport, TransportHandlers } from "./transport";
3
+ /**
4
+ * A transport that goes nowhere.
5
+ *
6
+ * Server-side rendering needs a connection object — the components ask it for
7
+ * their queries — but there is no socket to open and nothing to send. Everything
8
+ * those components can see arrives as hydration instead, applied directly to the
9
+ * store, so the messages this swallows would have had no answer anyway.
10
+ */
11
+ export declare class NullTransport implements Transport {
12
+ connect(_handlers: TransportHandlers): void;
13
+ send(_message: ClientMessage): void;
14
+ close(): void;
15
+ }
16
+ //# sourceMappingURL=null-transport.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"null-transport.d.ts","sourceRoot":"","sources":["../../src/client/null-transport.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AACtD,OAAO,KAAK,EAAE,SAAS,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAEhE;;;;;;;GAOG;AACH,qBAAa,aAAc,YAAW,SAAS;IAC3C,OAAO,CAAC,SAAS,EAAE,iBAAiB,GAAG,IAAI;IAC3C,IAAI,CAAC,QAAQ,EAAE,aAAa,GAAG,IAAI;IACnC,KAAK,IAAI,IAAI;CAChB"}
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.NullTransport = void 0;
4
+ /**
5
+ * A transport that goes nowhere.
6
+ *
7
+ * Server-side rendering needs a connection object — the components ask it for
8
+ * their queries — but there is no socket to open and nothing to send. Everything
9
+ * those components can see arrives as hydration instead, applied directly to the
10
+ * store, so the messages this swallows would have had no answer anyway.
11
+ */
12
+ class NullTransport {
13
+ connect(_handlers) { }
14
+ send(_message) { }
15
+ close() { }
16
+ }
17
+ exports.NullTransport = NullTransport;
@@ -0,0 +1,44 @@
1
+ import type { EntityId, Row } from "../core/types";
2
+ import type { ConfirmedStore } from "./confirmed-store";
3
+ /** Write surface a client-side mutator gets. */
4
+ export interface LocalTx {
5
+ get(entity: string, id: EntityId): Row | undefined;
6
+ all(entity: string): Row[];
7
+ /** Merge fields into an existing row. No-op if the row is not loaded. */
8
+ update(entity: string, id: EntityId, fields: Row): void;
9
+ /** Insert or replace a whole row. */
10
+ put(entity: string, row: Row): void;
11
+ remove(entity: string, id: EntityId): void;
12
+ }
13
+ /**
14
+ * Copy-on-write layer over {@link ConfirmedStore} holding the effect of pending
15
+ * mutations.
16
+ *
17
+ * A rebase is: throw the overlay away, make a new one, replay every pending
18
+ * mutator into it. That is why mutators are named domain operations rather than
19
+ * precomputed patches — a patch cannot be meaningfully re-applied to state that
20
+ * has moved underneath it, an operation can.
21
+ */
22
+ export declare class Overlay {
23
+ private readonly confirmed;
24
+ private readonly idFieldOf;
25
+ private readonly changes;
26
+ constructor(confirmed: ConfirmedStore, idFieldOf: (entity: string) => string);
27
+ tx(): LocalTx;
28
+ get(entity: string, id: EntityId): Row | undefined;
29
+ /**
30
+ * Rows a pending mutation created, per entity.
31
+ *
32
+ * Staged and not in the confirmed store: nothing on the server knows about
33
+ * them yet, which is exactly why no query result lists their ids. A window
34
+ * that knows its collection's ordering and membership can take them in
35
+ * meanwhile.
36
+ */
37
+ inserted(): Map<string, EntityId[]>;
38
+ /** Entities that either the server or a pending mutation knows about. */
39
+ entities(): string[];
40
+ /** Confirmed rows with pending changes applied. */
41
+ merged(entity: string): Map<EntityId, Row>;
42
+ private stage;
43
+ }
44
+ //# sourceMappingURL=overlay.d.ts.map
@@ -0,0 +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,MAAM,EAAE,MAAM,GAAG,GAAG,EAAE,CAAC;IAC3B,yEAAyE;IACzE,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,EAAE,EAAE,QAAQ,EAAE,MAAM,EAAE,GAAG,GAAG,IAAI,CAAC;IACxD,qCAAqC;IACrC,GAAG,CAAC,MAAM,EAAE,MAAM,EAAE,GAAG,EAAE,GAAG,GAAG,IAAI,CAAC;IACpC,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,EAAE,EAAE,QAAQ,GAAG,IAAI,CAAC;CAC9C;AAED;;;;;;;;GAQG;AACH,qBAAa,OAAO;IAIZ,OAAO,CAAC,QAAQ,CAAC,SAAS;IAC1B,OAAO,CAAC,QAAQ,CAAC,SAAS;IAJ9B,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAgD;gBAGnD,SAAS,EAAE,cAAc,EACzB,SAAS,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,MAAM;IAG1D,EAAE,IAAI,OAAO;IAiBb,GAAG,CAAC,MAAM,EAAE,MAAM,EAAE,EAAE,EAAE,QAAQ,GAAG,GAAG,GAAG,SAAS;IAMlD;;;;;;;OAOG;IACH,QAAQ,IAAI,GAAG,CAAC,MAAM,EAAE,QAAQ,EAAE,CAAC;IAYnC,yEAAyE;IACzE,QAAQ,IAAI,MAAM,EAAE;IAIpB,mDAAmD;IACnD,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,GAAG,CAAC,QAAQ,EAAE,GAAG,CAAC;IAY1C,OAAO,CAAC,KAAK;CAQhB"}