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,257 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.LiveList = exports.DEFAULT_PAGE_SIZE = void 0;
4
+ exports.listFor = listFor;
5
+ /**
6
+ * A collection, as much of it as anyone is looking at.
7
+ *
8
+ * The server answers a `@list` endpoint in windows, and this is what asks for
9
+ * them. It looks like an array with holes: `at(index)` gives the row if it is
10
+ * loaded and `undefined` if it is not, and asking is what makes it load — the
11
+ * same shape as reading a sparse array, which is the only shape a virtualised
12
+ * list can use, because it decides what to render before it knows what exists.
13
+ *
14
+ * Two things make that cheap. Windows are quantised to a page size, so scrolling
15
+ * asks for the same three subscriptions over and over instead of a new one per
16
+ * pixel; and a page nobody is looking at is *released*, so a hundred thousand
17
+ * rows cost three live queries rather than a hundred thousand. What is on screen
18
+ * is live in the full sense — a row edited by someone else updates in place,
19
+ * without the list reloading — and what is off screen is not watched at all.
20
+ *
21
+ * Nothing here is specific to a browser: it reads through the same
22
+ * {@link QuerySource} a hook reads through, so a server render pages the same
23
+ * way and the first screen arrives in the HTML.
24
+ */
25
+ const contract_1 = require("../api/contract");
26
+ const nowity_client_1 = require("./nowity-client");
27
+ /** How many rows one window holds. */
28
+ exports.DEFAULT_PAGE_SIZE = 50;
29
+ /** "Nothing local is in play here" — read the index from the server's windows. */
30
+ const SERVER_ORDER = Symbol("nowity.serverOrder");
31
+ class LiveList {
32
+ constructor(source, endpoint, args, pageSize) {
33
+ this.source = source;
34
+ this.endpoint = endpoint;
35
+ this.args = args;
36
+ this.pageSize = pageSize;
37
+ /** Pages currently held open, by page number. */
38
+ this.held = new Map();
39
+ this.holders = 0;
40
+ this.pageName = (0, contract_1.pageQuery)(endpoint);
41
+ this.countName = (0, contract_1.countQuery)(endpoint);
42
+ this.key = `${(0, nowity_client_1.subscriptionKey)(endpoint, args)}|${pageSize}`;
43
+ }
44
+ /**
45
+ * How many rows the collection has. Observable, and it moves as rows are added.
46
+ *
47
+ * A row created here and not yet confirmed counts: the server's total cannot
48
+ * know about it, and without it the row would have nowhere to be — the last
49
+ * index of the collection would still be the last one.
50
+ */
51
+ get total() {
52
+ return this.serverTotal + this.localDrift();
53
+ }
54
+ /** How many rows the server says there are, before anything local. */
55
+ get serverTotal() {
56
+ const value = this.count.value;
57
+ const row = (Array.isArray(value) ? value[0] : value);
58
+ return row?.total ?? 0;
59
+ }
60
+ /**
61
+ * How many rows the held windows differ from their own size by.
62
+ *
63
+ * Positive for a row created here, negative for one deleted here — the count
64
+ * came from the server and cannot know about either. Without it the
65
+ * collection would be the wrong length for as long as the write is in flight,
66
+ * and its last row would be unreachable or a blank.
67
+ */
68
+ localDrift() {
69
+ let drift = 0;
70
+ for (const page of this.held.keys()) {
71
+ const length = this.lengthOf(page);
72
+ if (length !== null)
73
+ drift += length - this.expected(page);
74
+ }
75
+ return drift;
76
+ }
77
+ /** How long a window is right now, or null while it cannot be read. */
78
+ lengthOf(page) {
79
+ const entry = this.page(page);
80
+ if (entry.loading || entry.problem)
81
+ return null;
82
+ return entry.value.length;
83
+ }
84
+ /**
85
+ * How long a window would be with nothing local in it.
86
+ *
87
+ * Every window is full except the collection's last, which holds whatever is
88
+ * left — so a short window is only news when it is not that one.
89
+ */
90
+ expected(page) {
91
+ const total = this.serverTotal;
92
+ const start = page * this.pageSize;
93
+ return Math.max(0, Math.min(this.pageSize, total - start));
94
+ }
95
+ /**
96
+ * The index, walked across the windows this list is holding.
97
+ *
98
+ * Needed when a window holds a different number of rows than its size —
99
+ * one more for a row created here, one fewer for one deleted here. Every
100
+ * index after it is then somewhere else than the arithmetic says, and
101
+ * walking the windows' *actual* lengths is what moves the rows instead of
102
+ * skipping one or leaving a blank where the deleted one was.
103
+ *
104
+ * Returns {@link SERVER_ORDER} when there is nothing local in play, which is
105
+ * every render but the few dozen milliseconds after a click.
106
+ */
107
+ local(index) {
108
+ if (!this.held.size || this.localDrift() === 0)
109
+ return SERVER_ORDER;
110
+ const first = Math.min(...this.held.keys());
111
+ const last = Math.max(...this.held.keys());
112
+ if (index < first * this.pageSize)
113
+ return SERVER_ORDER;
114
+ let cursor = first * this.pageSize;
115
+ for (let page = first; page <= last; page += 1) {
116
+ const entry = this.page(page);
117
+ if (entry.loading || entry.problem)
118
+ return SERVER_ORDER;
119
+ const rows = entry.value;
120
+ if (index < cursor + rows.length)
121
+ return rows[index - cursor];
122
+ cursor += rows.length;
123
+ }
124
+ // Past everything held; the window it falls in is not one of ours.
125
+ return SERVER_ORDER;
126
+ }
127
+ /** No answer yet about how big the collection is — what a list suspends on. */
128
+ get loading() {
129
+ return this.count.loading;
130
+ }
131
+ /** Why the collection cannot be read: refused, or broken. */
132
+ get problem() {
133
+ return this.count.problem;
134
+ }
135
+ get settled() {
136
+ return this.count.settled;
137
+ }
138
+ /**
139
+ * The row at an index, or `undefined` while its window is still loading.
140
+ *
141
+ * Asking is subscribing: the window covering the index is opened on the
142
+ * first ask, and every ask after that is a lookup. `undefined` is therefore
143
+ * an ordinary state and not an error — it is the cell a list renders as a
144
+ * skeleton, a moment before the row lands in it.
145
+ *
146
+ * Except while a page renders on a server, where a skeleton is not a moment
147
+ * before anything: that render is the HTML, so the window is waited for. It
148
+ * is also what the browser is about to hydrate against — a placeholder in the
149
+ * markup and a row in the store is a mismatch, and the row is the one both
150
+ * of them should have had.
151
+ */
152
+ at(index) {
153
+ if (index < 0 || index >= this.total)
154
+ return undefined;
155
+ const local = this.local(index);
156
+ if (local !== SERVER_ORDER)
157
+ return local;
158
+ const entry = this.page(Math.floor(index / this.pageSize));
159
+ // Read the status first: while a window is loading its rows are empty,
160
+ // and reading them anyway would make the cell depend on an array that is
161
+ // about to be replaced rather than on the thing it is waiting for.
162
+ if (entry.loading) {
163
+ if (this.source.rendersOnce)
164
+ throw entry.settled;
165
+ return undefined;
166
+ }
167
+ if (entry.problem)
168
+ return undefined;
169
+ return entry.value[index % this.pageSize];
170
+ }
171
+ /**
172
+ * Hold open exactly the windows covering `[from, to)`, and let the rest go.
173
+ *
174
+ * Called from an effect with what is on screen. Everything outside it is
175
+ * released — not dropped: the connection keeps a released subscription for a
176
+ * moment, which is what makes scrolling back up free.
177
+ */
178
+ view(from, to) {
179
+ const wanted = new Set();
180
+ if (to > from) {
181
+ const first = Math.floor(Math.max(0, from) / this.pageSize);
182
+ const last = Math.floor(Math.max(0, to - 1) / this.pageSize);
183
+ for (let page = first; page <= last; page += 1)
184
+ wanted.add(page);
185
+ }
186
+ for (const [page, entry] of [...this.held]) {
187
+ if (wanted.has(page))
188
+ continue;
189
+ this.held.delete(page);
190
+ this.source.release(entry);
191
+ }
192
+ for (const page of wanted) {
193
+ if (this.held.has(page))
194
+ continue;
195
+ const entry = this.page(page);
196
+ this.held.set(page, entry);
197
+ this.source.retain(entry);
198
+ }
199
+ }
200
+ /** Held for as long as a mounted component reads the collection. */
201
+ retain() {
202
+ this.holders += 1;
203
+ if (this.holders === 1)
204
+ this.source.retain(this.count);
205
+ }
206
+ release() {
207
+ this.holders = Math.max(0, this.holders - 1);
208
+ if (this.holders > 0)
209
+ return;
210
+ this.view(0, 0);
211
+ this.source.release(this.count);
212
+ forget(this.source, this.key);
213
+ }
214
+ get count() {
215
+ return this.source.ensure(this.countName, [this.args]);
216
+ }
217
+ /**
218
+ * One window's subscription, asked of the source every time rather than
219
+ * remembered.
220
+ *
221
+ * The source is where a subscription's lifetime is decided — a window
222
+ * released a moment ago may already have been collected — so holding a
223
+ * reference here would mean reading rows from a subscription that no longer
224
+ * exists. Asking again is a lookup in a map, and it is always the live one.
225
+ */
226
+ page(page) {
227
+ return this.source.ensure(this.pageName, [
228
+ this.args,
229
+ page * this.pageSize,
230
+ this.pageSize,
231
+ ]);
232
+ }
233
+ }
234
+ exports.LiveList = LiveList;
235
+ /**
236
+ * The collection for one endpoint and arguments, shared by everyone reading it.
237
+ *
238
+ * Shared because it is what holds the windows: two components showing the same
239
+ * collection must agree about which of them are open, or one would release what
240
+ * the other is reading.
241
+ */
242
+ const REGISTRIES = new WeakMap();
243
+ function listFor(source, endpoint, args, pageSize = exports.DEFAULT_PAGE_SIZE) {
244
+ let lists = REGISTRIES.get(source);
245
+ if (!lists)
246
+ REGISTRIES.set(source, (lists = new Map()));
247
+ const key = `${(0, nowity_client_1.subscriptionKey)(endpoint, args)}|${pageSize}`;
248
+ const existing = lists.get(key);
249
+ if (existing)
250
+ return existing;
251
+ const list = new LiveList(source, endpoint, args, pageSize);
252
+ lists.set(key, list);
253
+ return list;
254
+ }
255
+ function forget(source, key) {
256
+ REGISTRIES.get(source)?.delete(key);
257
+ }
@@ -0,0 +1,153 @@
1
+ import { type IObservableArray, type IObservableValue } from "mobx";
2
+ import type { OrderKey, RowFilter } from "../core/protocol";
3
+ import type { EntityId } from "../core/types";
4
+ export type LiveQueryStatus = "loading" | "ready" | "stale" | "revoked" | "error";
5
+ export interface QueryDescriptor<A = any, T = any> {
6
+ /**
7
+ * Entity name of the rows this query returns.
8
+ *
9
+ * Optional: every snapshot and patch states the entity, and that is what the
10
+ * subscription uses. Set it only to have the name available before the first
11
+ * snapshot arrives.
12
+ */
13
+ entity?: string;
14
+ /**
15
+ * Client-side predicate deciding whether a locally created row belongs in
16
+ * this result before the server has confirmed it.
17
+ *
18
+ * Without it, optimistic inserts stay invisible until the server answers —
19
+ * correct, but not what anyone wants from a create button. With it, the
20
+ * client evaluates just enough of the query to place the new row. This is the
21
+ * one place where the client duplicates query semantics; keep it in sync with
22
+ * the server query or leave it out.
23
+ */
24
+ matches?(row: T, args: A): boolean;
25
+ /** Ordering for optimistic rows. Server order is used when absent. */
26
+ compare?(a: T, b: T): number;
27
+ }
28
+ export interface SubscriptionState {
29
+ subId: string;
30
+ query: string;
31
+ args: unknown;
32
+ /**
33
+ * Set from the server's snapshot/patch; empty until the first one arrives.
34
+ *
35
+ * Observable, and it has to be: a `rows` computation that bailed out on an
36
+ * unknown entity would otherwise read no observable at all, and a computed
37
+ * with no dependencies is constant forever.
38
+ */
39
+ entity: IObservableValue<string>;
40
+ descriptor: QueryDescriptor;
41
+ ids: IObservableArray<EntityId>;
42
+ epoch: number;
43
+ scope: string | null;
44
+ status: IObservableValue<LiveQueryStatus>;
45
+ error: IObservableValue<string | null>;
46
+ /**
47
+ * The server said this query returns one row rather than a list.
48
+ * `undefined` until the first snapshot arrives.
49
+ */
50
+ single: IObservableValue<boolean | undefined>;
51
+ /**
52
+ * How the server ordered this result, when it could say.
53
+ *
54
+ * Used for exactly one thing: placing a row this browser has changed and the
55
+ * server has not confirmed yet. Observable because it arrives with the first
56
+ * snapshot, after the subscription already exists.
57
+ */
58
+ order: IObservableValue<OrderKey[] | null>;
59
+ /**
60
+ * Which rows belong to this result, when the server could say it as data.
61
+ *
62
+ * What it is for is a row created in this browser: it exists in the identity
63
+ * map and in no result's id list, because the only thing that puts an id in
64
+ * one is the server. This is what lets a window claim it in the meantime.
65
+ */
66
+ filter: IObservableValue<RowFilter | null>;
67
+ }
68
+ export interface LiveQueryDeps {
69
+ mapFor(entity: string): Map<EntityId, any>;
70
+ /** Rows this browser created that the server has not confirmed yet. */
71
+ pendingInserts(entity: string): EntityId[];
72
+ /**
73
+ * Whether anything this browser wrote is still unconfirmed.
74
+ *
75
+ * The server's order is authoritative and is used verbatim — except while a
76
+ * local write is in flight, when the row it changed may belong somewhere
77
+ * else and only this browser knows it yet.
78
+ */
79
+ hasPending(): boolean;
80
+ dispose(): void;
81
+ }
82
+ /**
83
+ * A live query result: an observable array of live entity objects.
84
+ *
85
+ * `rows` holds the same object instances as the identity map, so two queries
86
+ * returning the same row hand out the same object and a change to it re-renders
87
+ * both.
88
+ */
89
+ export declare class LiveQuery<T = any> {
90
+ private readonly state;
91
+ private readonly deps;
92
+ private readonly rowsComputed;
93
+ private disposed;
94
+ constructor(state: SubscriptionState, deps: LiveQueryDeps);
95
+ get rows(): T[];
96
+ get status(): LiveQueryStatus;
97
+ get error(): string | null;
98
+ get isReady(): boolean;
99
+ /** First row, for `findUnique`-shaped queries. */
100
+ get one(): T | undefined;
101
+ get subId(): string;
102
+ /** True once `dispose` ran; a React effect uses it to re-subscribe. */
103
+ get isDisposed(): boolean;
104
+ /** Idempotent: React may unmount and remount the same handle. */
105
+ dispose(): void;
106
+ /**
107
+ * Put a locally changed row where the query's own ordering says it goes.
108
+ *
109
+ * Only while a write of this browser's is unconfirmed, and only by the keys
110
+ * the server sent. In the settled state the server's order is used exactly
111
+ * as it arrived — which matters, because a comparison in JavaScript is not
112
+ * the comparison PostgreSQL made: text collation is a database's own, so a
113
+ * key whose values are not numbers or dates contributes nothing here and the
114
+ * rows keep the order they came in. A sort is stable, so that is a no-op
115
+ * rather than a guess.
116
+ *
117
+ * It reaches as far as this window and no further. A row whose new place is
118
+ * outside the window ends up at its edge, which is as far as a subscription
119
+ * that holds fifty of five thousand rows can honestly take it; the server's
120
+ * answer, a moment later, moves it the rest of the way.
121
+ */
122
+ private placeLocalWrites;
123
+ /**
124
+ * Take in a row this browser created, if it belongs to this window.
125
+ *
126
+ * Belonging is two questions and the server answered both as data: the
127
+ * `filter` says whether the row is in the collection at all, and the window's
128
+ * own first and last rows say whether it falls in *this* slice of it. A row
129
+ * that sorts before the first window's first row belongs to that window; one
130
+ * that sorts past the last loaded row belongs to a window nobody is holding,
131
+ * and is left where it is — invisible, which is where it would be on screen.
132
+ *
133
+ * The row is claimed by exactly one window, so the collection gains one row
134
+ * rather than one per window that happens to be open.
135
+ */
136
+ private claimLocalInserts;
137
+ /**
138
+ * Whether a row would fall inside this window rather than a neighbouring one.
139
+ *
140
+ * A row between the window's first and last row is unambiguously here. One
141
+ * beyond either end belongs here only if there is nothing beyond that end:
142
+ * the collection's first window owns everything above its first row, and its
143
+ * last window everything below its last. A window in the middle claiming
144
+ * either would be claiming its neighbour's row — and the neighbour would
145
+ * claim it too, so the row would appear twice.
146
+ *
147
+ * Which window this is comes from its own arguments: an offset of zero is
148
+ * the first, and a window the server did not fill is the last.
149
+ */
150
+ private covers;
151
+ private computeRows;
152
+ }
153
+ //# sourceMappingURL=live-query.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"live-query.d.ts","sourceRoot":"","sources":["../../src/client/live-query.ts"],"names":[],"mappings":"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"}
@@ -0,0 +1,244 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.LiveQuery = void 0;
4
+ const mobx_1 = require("mobx");
5
+ /**
6
+ * A live query result: an observable array of live entity objects.
7
+ *
8
+ * `rows` holds the same object instances as the identity map, so two queries
9
+ * returning the same row hand out the same object and a change to it re-renders
10
+ * both.
11
+ */
12
+ class LiveQuery {
13
+ constructor(state, deps) {
14
+ this.state = state;
15
+ this.deps = deps;
16
+ this.disposed = false;
17
+ this.rowsComputed = (0, mobx_1.computed)(() => this.computeRows(), { keepAlive: false });
18
+ }
19
+ get rows() {
20
+ return this.rowsComputed.get();
21
+ }
22
+ get status() {
23
+ return this.state.status.get();
24
+ }
25
+ get error() {
26
+ return this.state.error.get();
27
+ }
28
+ get isReady() {
29
+ return this.state.status.get() === "ready";
30
+ }
31
+ /** First row, for `findUnique`-shaped queries. */
32
+ get one() {
33
+ return this.rows[0];
34
+ }
35
+ get subId() {
36
+ return this.state.subId;
37
+ }
38
+ /** True once `dispose` ran; a React effect uses it to re-subscribe. */
39
+ get isDisposed() {
40
+ return this.disposed;
41
+ }
42
+ /** Idempotent: React may unmount and remount the same handle. */
43
+ dispose() {
44
+ if (this.disposed)
45
+ return;
46
+ this.disposed = true;
47
+ this.deps.dispose();
48
+ }
49
+ /**
50
+ * Put a locally changed row where the query's own ordering says it goes.
51
+ *
52
+ * Only while a write of this browser's is unconfirmed, and only by the keys
53
+ * the server sent. In the settled state the server's order is used exactly
54
+ * as it arrived — which matters, because a comparison in JavaScript is not
55
+ * the comparison PostgreSQL made: text collation is a database's own, so a
56
+ * key whose values are not numbers or dates contributes nothing here and the
57
+ * rows keep the order they came in. A sort is stable, so that is a no-op
58
+ * rather than a guess.
59
+ *
60
+ * It reaches as far as this window and no further. A row whose new place is
61
+ * outside the window ends up at its edge, which is as far as a subscription
62
+ * that holds fifty of five thousand rows can honestly take it; the server's
63
+ * answer, a moment later, moves it the rest of the way.
64
+ */
65
+ placeLocalWrites(rows) {
66
+ if (!this.deps.hasPending())
67
+ return;
68
+ const keys = this.state.order.get();
69
+ if (!keys?.length)
70
+ return;
71
+ rows.sort((a, b) => {
72
+ return compareByKeys(a, b, keys);
73
+ });
74
+ }
75
+ /**
76
+ * Take in a row this browser created, if it belongs to this window.
77
+ *
78
+ * Belonging is two questions and the server answered both as data: the
79
+ * `filter` says whether the row is in the collection at all, and the window's
80
+ * own first and last rows say whether it falls in *this* slice of it. A row
81
+ * that sorts before the first window's first row belongs to that window; one
82
+ * that sorts past the last loaded row belongs to a window nobody is holding,
83
+ * and is left where it is — invisible, which is where it would be on screen.
84
+ *
85
+ * The row is claimed by exactly one window, so the collection gains one row
86
+ * rather than one per window that happens to be open.
87
+ */
88
+ claimLocalInserts(out, map, seen) {
89
+ if (!this.deps.hasPending())
90
+ return;
91
+ const keys = this.state.order.get();
92
+ const filter = this.state.filter.get();
93
+ if (!keys?.length || !filter)
94
+ return;
95
+ for (const id of this.deps.pendingInserts(this.state.entity.get())) {
96
+ if (seen.has(id))
97
+ continue;
98
+ const row = map.get(id);
99
+ if (!row || !matchesFilter(row, filter))
100
+ continue;
101
+ if (!this.covers(row, out, keys))
102
+ continue;
103
+ out.push(row);
104
+ seen.add(id);
105
+ }
106
+ }
107
+ /**
108
+ * Whether a row would fall inside this window rather than a neighbouring one.
109
+ *
110
+ * A row between the window's first and last row is unambiguously here. One
111
+ * beyond either end belongs here only if there is nothing beyond that end:
112
+ * the collection's first window owns everything above its first row, and its
113
+ * last window everything below its last. A window in the middle claiming
114
+ * either would be claiming its neighbour's row — and the neighbour would
115
+ * claim it too, so the row would appear twice.
116
+ *
117
+ * Which window this is comes from its own arguments: an offset of zero is
118
+ * the first, and a window the server did not fill is the last.
119
+ */
120
+ covers(row, out, keys) {
121
+ if (out.length === 0)
122
+ return true;
123
+ const bounds = windowOf(this.state.args);
124
+ if (compareByKeys(row, out[0], keys) < 0)
125
+ return bounds ? bounds.offset === 0 : false;
126
+ if (compareByKeys(row, out[out.length - 1], keys) > 0) {
127
+ return bounds ? out.length < bounds.limit : false;
128
+ }
129
+ return true;
130
+ }
131
+ computeRows() {
132
+ // Before the first snapshot the entity is not known yet — and there is
133
+ // nothing to show anyway.
134
+ const entity = this.state.entity.get();
135
+ if (!entity)
136
+ return [];
137
+ const map = this.deps.mapFor(entity);
138
+ const out = [];
139
+ const seen = new Set();
140
+ for (const id of this.state.ids) {
141
+ const instance = map.get(id);
142
+ // A missing instance means a pending mutation deleted the row
143
+ // optimistically; it reappears if the server rejects the deletion.
144
+ if (instance !== undefined) {
145
+ out.push(instance);
146
+ seen.add(id);
147
+ }
148
+ }
149
+ const { matches, compare } = this.state.descriptor;
150
+ if (matches) {
151
+ for (const [id, instance] of map) {
152
+ if (seen.has(id))
153
+ continue;
154
+ if (matches(instance, this.state.args))
155
+ out.push(instance);
156
+ }
157
+ }
158
+ if (compare)
159
+ out.sort(compare);
160
+ else {
161
+ this.claimLocalInserts(out, map, seen);
162
+ this.placeLocalWrites(out);
163
+ }
164
+ return out;
165
+ }
166
+ }
167
+ exports.LiveQuery = LiveQuery;
168
+ /**
169
+ * Compare two values the way a database would, or refuse to.
170
+ *
171
+ * Numbers and dates are ordered the same everywhere. Text is not — collation is
172
+ * the database's, and a browser guessing at it would put a row in a place the
173
+ * server is about to disagree with. Refusing is `0`: the rows stay in the order
174
+ * the server sent, which is the right answer for everything except the one row
175
+ * that just moved.
176
+ */
177
+ /**
178
+ * A window's place in its collection, read off the arguments it subscribed with.
179
+ *
180
+ * `[args, offset, limit]` is the shape a paged collection asks for, and the two
181
+ * numbers are the only thing that says whether this window is at an end of the
182
+ * collection. A subscription with any other shape is not a window and gets
183
+ * nothing here — it simply never claims a row beyond its own rows.
184
+ */
185
+ function windowOf(args) {
186
+ if (!Array.isArray(args) || args.length !== 3)
187
+ return null;
188
+ const [, offset, limit] = args;
189
+ if (typeof offset !== "number" || typeof limit !== "number")
190
+ return null;
191
+ return { offset, limit };
192
+ }
193
+ /** One row against another, by the keys the server sent. */
194
+ function compareByKeys(a, b, keys) {
195
+ for (const { field, dir, type } of keys) {
196
+ const compared = compareValues(a?.[field], b?.[field], type);
197
+ if (compared !== 0)
198
+ return dir === "desc" ? -compared : compared;
199
+ }
200
+ return 0;
201
+ }
202
+ /** Whether a row satisfies a flat equality filter. */
203
+ function matchesFilter(row, filter) {
204
+ for (const [field, value] of Object.entries(filter)) {
205
+ const actual = row?.[field];
206
+ if (actual instanceof Date ? actual.getTime() !== new Date(value).getTime() : actual !== value) {
207
+ return false;
208
+ }
209
+ }
210
+ return true;
211
+ }
212
+ function compareValues(a, b, type) {
213
+ if (a === b)
214
+ return 0;
215
+ // Nulls last, which is PostgreSQL's default for ascending order.
216
+ if (a === null || a === undefined)
217
+ return b === null || b === undefined ? 0 : 1;
218
+ if (b === null || b === undefined)
219
+ return -1;
220
+ if (type === "text")
221
+ return 0;
222
+ const left = scalar(a, type);
223
+ const right = scalar(b, type);
224
+ if (left === null || right === null || left === right)
225
+ return 0;
226
+ return left < right ? -1 : 1;
227
+ }
228
+ /**
229
+ * A value as a number, whatever it arrived as.
230
+ *
231
+ * A timestamp comes over the wire as a string and out of a local mutator as a
232
+ * `Date`, and both have to compare the same way — the browser's own write must
233
+ * not sort differently from the server's copy of it.
234
+ */
235
+ function scalar(value, type) {
236
+ if (type === "date") {
237
+ const at = value instanceof Date ? value.getTime() : Date.parse(String(value));
238
+ return Number.isNaN(at) ? null : at;
239
+ }
240
+ if (type === "boolean")
241
+ return value ? 1 : 0;
242
+ const asNumber = typeof value === "number" ? value : Number(value);
243
+ return Number.isFinite(asNumber) ? asNumber : null;
244
+ }