@hyper-fetch/db 0.0.0-stage → 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 (141) hide show
  1. package/README.md +180 -2
  2. package/__tests__/e2e/db.e2e.spec.ts +269 -0
  3. package/__tests__/features/connection/connection.spec.ts +23 -0
  4. package/__tests__/features/model/live-query.model.spec.ts +320 -0
  5. package/__tests__/features/operators/operators.spec.ts +113 -0
  6. package/__tests__/features/runtime/runtime.spec.ts +185 -0
  7. package/__tests__/features/serializer/serializer.spec.ts +73 -0
  8. package/__tests__/features/store/store.spec.ts +147 -0
  9. package/__tests__/features/types/db.types.spec.ts +337 -0
  10. package/__tests__/integration/audit.spec.ts +639 -0
  11. package/__tests__/integration/competitors.spec.ts +393 -0
  12. package/__tests__/integration/convergence.model.spec.ts +162 -0
  13. package/__tests__/integration/edge-cases.spec.ts +465 -0
  14. package/__tests__/integration/errors.spec.ts +178 -0
  15. package/__tests__/integration/infinite.model.spec.ts +142 -0
  16. package/__tests__/integration/infinite.spec.ts +290 -0
  17. package/__tests__/integration/inspect.spec.ts +103 -0
  18. package/__tests__/integration/joins-many.spec.ts +177 -0
  19. package/__tests__/integration/joins.spec.ts +179 -0
  20. package/__tests__/integration/key-loaders.spec.ts +196 -0
  21. package/__tests__/integration/links.spec.ts +105 -0
  22. package/__tests__/integration/mutations.spec.ts +337 -0
  23. package/__tests__/integration/normalize.spec.ts +80 -0
  24. package/__tests__/integration/offline.spec.ts +479 -0
  25. package/__tests__/integration/queries.spec.ts +513 -0
  26. package/__tests__/integration/races.spec.ts +127 -0
  27. package/__tests__/integration/server-operators.spec.ts +123 -0
  28. package/__tests__/integration/ssr.spec.ts +111 -0
  29. package/__tests__/integration/syncs.spec.ts +564 -0
  30. package/__tests__/integration/transactions.spec.ts +344 -0
  31. package/__tests__/integration/windows.spec.ts +192 -0
  32. package/__tests__/tsconfig.json +11 -0
  33. package/__tests__/type-budget/budget.fixture.ts +2476 -0
  34. package/__tests__/type-budget/tsconfig.json +4 -0
  35. package/__tests__/utils/fixtures.ts +225 -0
  36. package/__tests__/utils/random.ts +19 -0
  37. package/__tests__/vitest.setup.ts +11 -0
  38. package/dist/collection/collection.d.ts +111 -0
  39. package/dist/collection/collection.d.ts.map +1 -0
  40. package/dist/collection/collection.types.d.ts +316 -0
  41. package/dist/collection/collection.types.d.ts.map +1 -0
  42. package/dist/collection/resource.types.d.ts +77 -0
  43. package/dist/collection/resource.types.d.ts.map +1 -0
  44. package/dist/db/collection.runtime.d.ts +98 -0
  45. package/dist/db/collection.runtime.d.ts.map +1 -0
  46. package/dist/db/db.d.ts +154 -0
  47. package/dist/db/db.d.ts.map +1 -0
  48. package/dist/db/db.runtime.d.ts +114 -0
  49. package/dist/db/db.runtime.d.ts.map +1 -0
  50. package/dist/db/db.types.d.ts +162 -0
  51. package/dist/db/db.types.d.ts.map +1 -0
  52. package/dist/graphql/connection.d.ts +25 -0
  53. package/dist/graphql/connection.d.ts.map +1 -0
  54. package/dist/index.d.ts +17 -0
  55. package/dist/index.d.ts.map +1 -0
  56. package/dist/index.mjs +4220 -0
  57. package/dist/index.mjs.map +1 -0
  58. package/dist/mutation/mutation.d.ts +136 -0
  59. package/dist/mutation/mutation.d.ts.map +1 -0
  60. package/dist/mutation/mutation.errors.d.ts +6 -0
  61. package/dist/mutation/mutation.errors.d.ts.map +1 -0
  62. package/dist/mutation/mutation.utils.d.ts +35 -0
  63. package/dist/mutation/mutation.utils.d.ts.map +1 -0
  64. package/dist/operators/operators.d.ts +33 -0
  65. package/dist/operators/operators.d.ts.map +1 -0
  66. package/dist/operators/operators.types.d.ts +68 -0
  67. package/dist/operators/operators.types.d.ts.map +1 -0
  68. package/dist/operators/operators.utils.d.ts +19 -0
  69. package/dist/operators/operators.utils.d.ts.map +1 -0
  70. package/dist/persistence/persistence.d.ts +42 -0
  71. package/dist/persistence/persistence.d.ts.map +1 -0
  72. package/dist/persistence/serializer.d.ts +23 -0
  73. package/dist/persistence/serializer.d.ts.map +1 -0
  74. package/dist/persistence/snapshot.d.ts +29 -0
  75. package/dist/persistence/snapshot.d.ts.map +1 -0
  76. package/dist/persistence/tabs.d.ts +53 -0
  77. package/dist/persistence/tabs.d.ts.map +1 -0
  78. package/dist/query/infinite-query.d.ts +59 -0
  79. package/dist/query/infinite-query.d.ts.map +1 -0
  80. package/dist/query/live-query.d.ts +85 -0
  81. package/dist/query/live-query.d.ts.map +1 -0
  82. package/dist/query/planner.d.ts +57 -0
  83. package/dist/query/planner.d.ts.map +1 -0
  84. package/dist/query/query.d.ts +155 -0
  85. package/dist/query/query.d.ts.map +1 -0
  86. package/dist/query/query.types.d.ts +71 -0
  87. package/dist/query/query.types.d.ts.map +1 -0
  88. package/dist/schema/schema.types.d.ts +33 -0
  89. package/dist/schema/schema.types.d.ts.map +1 -0
  90. package/dist/store/store.d.ts +76 -0
  91. package/dist/store/store.d.ts.map +1 -0
  92. package/dist/store/store.types.d.ts +27 -0
  93. package/dist/store/store.types.d.ts.map +1 -0
  94. package/dist/subset/base-subset.d.ts +66 -0
  95. package/dist/subset/base-subset.d.ts.map +1 -0
  96. package/dist/subset/key-subset.d.ts +23 -0
  97. package/dist/subset/key-subset.d.ts.map +1 -0
  98. package/dist/subset/list-subset.d.ts +63 -0
  99. package/dist/subset/list-subset.d.ts.map +1 -0
  100. package/dist/sync/sync.d.ts +42 -0
  101. package/dist/sync/sync.d.ts.map +1 -0
  102. package/dist/utils/request.utils.d.ts +11 -0
  103. package/dist/utils/request.utils.d.ts.map +1 -0
  104. package/package.json +71 -4
  105. package/project.json +4 -0
  106. package/scripts/docs-typescript.mjs +24 -0
  107. package/scripts/type-budget.mjs +37 -0
  108. package/src/collection/collection.ts +330 -0
  109. package/src/collection/collection.types.ts +383 -0
  110. package/src/collection/resource.types.ts +114 -0
  111. package/src/db/collection.runtime.ts +572 -0
  112. package/src/db/db.runtime.ts +537 -0
  113. package/src/db/db.ts +451 -0
  114. package/src/db/db.types.ts +157 -0
  115. package/src/graphql/connection.ts +23 -0
  116. package/src/index.ts +16 -0
  117. package/src/mutation/mutation.errors.ts +7 -0
  118. package/src/mutation/mutation.ts +776 -0
  119. package/src/mutation/mutation.utils.ts +58 -0
  120. package/src/operators/operators.ts +90 -0
  121. package/src/operators/operators.types.ts +67 -0
  122. package/src/operators/operators.utils.ts +169 -0
  123. package/src/persistence/persistence.ts +168 -0
  124. package/src/persistence/serializer.ts +123 -0
  125. package/src/persistence/snapshot.ts +76 -0
  126. package/src/persistence/tabs.ts +86 -0
  127. package/src/query/infinite-query.ts +206 -0
  128. package/src/query/live-query.ts +552 -0
  129. package/src/query/planner.ts +199 -0
  130. package/src/query/query.ts +319 -0
  131. package/src/query/query.types.ts +90 -0
  132. package/src/schema/schema.types.ts +29 -0
  133. package/src/store/store.ts +300 -0
  134. package/src/store/store.types.ts +17 -0
  135. package/src/subset/base-subset.ts +169 -0
  136. package/src/subset/key-subset.ts +44 -0
  137. package/src/subset/list-subset.ts +328 -0
  138. package/src/sync/sync.ts +99 -0
  139. package/src/utils/request.utils.ts +67 -0
  140. package/tsconfig.json +12 -0
  141. package/vite.config.ts +71 -0
package/dist/index.mjs ADDED
@@ -0,0 +1,4220 @@
1
+ //#region src/collection/collection.ts
2
+ /**
3
+ * A typed set of complete rows, defined by a schema and a key. It declares how its backend loads rows (`load`), keeps
4
+ * them live (`sync`), feeds them from other responses (`ingest`) and changes them (`mutate`). A collection is
5
+ * immutable: every method returns a new collection, so it is defined in one chain and passed to `createDb`.
6
+ *
7
+ * When rows a method reads do not match the row type, it returns a `RowMismatch` instead of a collection, so the chain
8
+ * and `createDb` do not compile.
9
+ */
10
+ var Collection = class Collection {
11
+ constructor(config) {
12
+ this.config = config;
13
+ }
14
+ /**
15
+ * Adds a loader: a request plus the way to read complete rows from its response. A list loader declares the filters
16
+ * and orders it can send and whether it is paginated. A loader with `byKey` or `byKeys` reads rows by key.
17
+ */
18
+ load(request, options) {
19
+ const loaderOptions = options ?? {};
20
+ let kind = "list";
21
+ if (loaderOptions.byKey) kind = "byKey";
22
+ else if (loaderOptions.byKeys) kind = "byKeys";
23
+ const loader = {
24
+ ...loaderOptions,
25
+ kind,
26
+ request
27
+ };
28
+ return new Collection({
29
+ ...this.config,
30
+ loaders: [...this.config.loaders, loader]
31
+ });
32
+ }
33
+ /**
34
+ * Derives loaders and mutations from an SDK resource that follows REST conventions: `$get` lists, `item.$get` reads
35
+ * by key, `$post` inserts, `item.$patch` or `item.$put` updates and `item.$delete` deletes. Path params of the list
36
+ * endpoint become required `eq` filters, and the query params listed in `list.where` become `eq` filters.
37
+ *
38
+ * @example
39
+ * collection(PostSchema, { key: "id" }).resource(sdk.posts, { item: "$postId" });
40
+ */
41
+ resource(node, options) {
42
+ const resourceNode = node;
43
+ const itemKey = options.item;
44
+ const itemParam = itemKey.slice(1);
45
+ const itemNode = resourceNode[itemKey];
46
+ const toKeyPatch = (key) => ({ params: { [itemParam]: key } });
47
+ const loaders = [];
48
+ const list = options.list === false ? void 0 : options.list ?? {};
49
+ if (list) {
50
+ const listRequest = resourceNode.$get;
51
+ const pathParams = [...String(listRequest.requestOptions.endpoint).matchAll(/:([A-Za-z0-9_]+)/g)].map((match) => match[1]);
52
+ const where = {};
53
+ pathParams.forEach((param) => {
54
+ where[param] = {
55
+ eq: (value) => ({ params: { [param]: value } }),
56
+ required: true
57
+ };
58
+ });
59
+ (list.where ?? []).forEach((field) => {
60
+ where[field] = { eq: (value) => ({ queryParams: { [field]: value } }) };
61
+ });
62
+ loaders.push({
63
+ kind: "list",
64
+ request: listRequest,
65
+ rows: list.rows,
66
+ where,
67
+ cursor: list.cursor,
68
+ page: list.page
69
+ });
70
+ }
71
+ loaders.push({
72
+ kind: "byKey",
73
+ request: itemNode.$get,
74
+ byKey: toKeyPatch
75
+ });
76
+ return new Collection({
77
+ ...this.config,
78
+ loaders: [...this.config.loaders, ...loaders],
79
+ mutations: {
80
+ ...this.config.mutations,
81
+ insert: {
82
+ request: resourceNode.$post,
83
+ map: (row) => ({ payload: row }),
84
+ onSuccess: options.insert?.onSuccess
85
+ },
86
+ update: {
87
+ request: itemNode[options.update?.method ?? "$patch"],
88
+ map: (key, changes) => ({
89
+ ...toKeyPatch(key),
90
+ payload: changes
91
+ }),
92
+ onSuccess: options.update?.onSuccess
93
+ },
94
+ delete: {
95
+ request: itemNode.$delete,
96
+ map: (key) => toKeyPatch(key),
97
+ onSuccess: "keep"
98
+ }
99
+ }
100
+ });
101
+ }
102
+ /**
103
+ * Keeps rows current from a listener. `insert` messages carry complete rows, `update` messages the key and some
104
+ * fields, and `delete` messages the key. One listener can sync several collections.
105
+ */
106
+ sync(listener, options) {
107
+ const sync = {
108
+ ...options,
109
+ listener
110
+ };
111
+ return new Collection({
112
+ ...this.config,
113
+ syncs: [...this.config.syncs, sync]
114
+ });
115
+ }
116
+ /**
117
+ * Writes the rows nested in this collection's rows into another collection, for example the author of a post into
118
+ * the `user` collection. It runs on every complete write from the server: loads, inserts, ingested responses and
119
+ * mutation responses. The target is the collection itself, so renaming or removing it breaks the build.
120
+ *
121
+ * @example
122
+ * collection(PostSchema, { key: "id" }).normalize(User, (post) => (post.author ? [post.author] : []));
123
+ */
124
+ normalize(target, extract) {
125
+ const normalize = [...this.config.normalize ?? [], {
126
+ target: target.config,
127
+ extract
128
+ }];
129
+ return new Collection({
130
+ ...this.config,
131
+ normalize
132
+ });
133
+ }
134
+ /**
135
+ * Keeps rows current from a listener whose events carry several changes at once, such as a Firestore snapshot.
136
+ * `changes` reads the complete rows to write and the keys to delete. With `notation`, the sync covers every subset
137
+ * by sending its conditions to the listener. Adapter presets such as `firestoreCollection` use it.
138
+ */
139
+ syncChanges(listener, options) {
140
+ const sync = {
141
+ ...options,
142
+ type: "changes",
143
+ listener
144
+ };
145
+ return new Collection({
146
+ ...this.config,
147
+ syncs: [...this.config.syncs, sync]
148
+ });
149
+ }
150
+ /**
151
+ * Writes the rows of another request's responses into the collection, for example a search endpoint or a
152
+ * `useSubmit` whose response is the changed row. The request does not become a loader.
153
+ */
154
+ ingest(request, options) {
155
+ const ingestOptions = options ?? {};
156
+ const ingest = {
157
+ ...ingestOptions,
158
+ request,
159
+ type: ingestOptions.type ?? "insert"
160
+ };
161
+ return new Collection({
162
+ ...this.config,
163
+ ingests: [...this.config.ingests, ingest]
164
+ });
165
+ }
166
+ /**
167
+ * Declares how inserts, updates and deletes reach the backend. Each `map` turns the write into the request's params,
168
+ * query params and payload. A response that is not the row needs `onSuccess`.
169
+ */
170
+ mutate(mutations) {
171
+ const config = mutations;
172
+ return new Collection({
173
+ ...this.config,
174
+ mutations: {
175
+ ...this.config.mutations,
176
+ ...config.insert ? { insert: config.insert } : {},
177
+ ...config.update ? { update: config.update } : {},
178
+ ...config.delete ? { delete: config.delete } : {}
179
+ }
180
+ });
181
+ }
182
+ };
183
+ var emptyConfig = (options, schema) => ({
184
+ schema,
185
+ key: options.key,
186
+ version: options.version,
187
+ validate: options.validate ?? "client",
188
+ loaders: [],
189
+ syncs: [],
190
+ ingests: [],
191
+ mutations: {}
192
+ });
193
+ /** Declares a collection's row type without a schema, so writes are not validated */
194
+ var rowType = () => ({ kind: "row-type" });
195
+ function collection(schemaOrType, options) {
196
+ return new Collection(emptyConfig(options, "~standard" in schemaOrType ? schemaOrType : void 0));
197
+ }
198
+ //#endregion
199
+ //#region src/utils/request.utils.ts
200
+ var isPlainObject$1 = (value) => {
201
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value) && !(value instanceof Date);
202
+ };
203
+ /** Objects merge and arrays, such as Firestore constraints, add up. Anything else replaces the current value. */
204
+ var mergeValue = (current, next) => {
205
+ if (isPlainObject$1(current) && isPlainObject$1(next)) return {
206
+ ...current,
207
+ ...next
208
+ };
209
+ if (Array.isArray(current) && Array.isArray(next)) return [...current, ...next];
210
+ return next;
211
+ };
212
+ /** Applies patches to a request, merging params, query params and object payloads into what it already has */
213
+ var applyRequestPatches = (request, patches) => {
214
+ let next = request;
215
+ patches.forEach((patch) => {
216
+ if (patch.params) next = next.setParams({
217
+ ...next.params,
218
+ ...patch.params
219
+ });
220
+ if (patch.queryParams !== void 0) next = next.setQueryParams(mergeValue(next.queryParams, patch.queryParams));
221
+ if ("payload" in patch) next = next.setPayload(mergeValue(next.payload, patch.payload));
222
+ });
223
+ return next;
224
+ };
225
+ /** Applies patches to a listener, merging topic params, payloads and query params into what it already has */
226
+ var applyListenerPatches = (listener, patches) => {
227
+ let next = listener;
228
+ patches.forEach((patch) => {
229
+ if (patch.params) next = next.setParams({
230
+ ...next.params,
231
+ ...patch.params
232
+ });
233
+ if ("payload" in patch) next = next.setPayload(mergeValue(next.payload, patch.payload));
234
+ if (patch.queryParams !== void 0) next = next.setQueryParams(mergeValue(next.queryParams, patch.queryParams));
235
+ });
236
+ return next;
237
+ };
238
+ var idCounter = 0;
239
+ /** A unique id for transactions and temporary keys */
240
+ var createId = () => {
241
+ if (typeof globalThis.crypto?.randomUUID === "function") return globalThis.crypto.randomUUID();
242
+ idCounter += 1;
243
+ return `${Date.now().toString(36)}-${idCounter.toString(36)}-${Math.random().toString(36).slice(2)}`;
244
+ };
245
+ //#endregion
246
+ //#region src/mutation/mutation.errors.ts
247
+ /** Why a write was dropped: an earlier write it was built on failed */
248
+ var DependencyError = class extends Error {
249
+ constructor(transactionId) {
250
+ super(`An earlier write this one depends on (${transactionId}) failed`);
251
+ this.transactionId = transactionId;
252
+ this.name = "DependencyError";
253
+ }
254
+ };
255
+ //#endregion
256
+ //#region src/mutation/mutation.utils.ts
257
+ var createTransaction = (id, result) => {
258
+ return Object.assign(result, { id });
259
+ };
260
+ /** By default a 4xx response other than 408 and 429 is permanent, and everything else is retried */
261
+ var isTemporaryFailure = (response) => {
262
+ const status = Number(response.status);
263
+ if (!status) return true;
264
+ return status >= 500 || status === 408 || status === 429;
265
+ };
266
+ /** The rows a record writes, as `collection:key` */
267
+ var rowsOf = (record) => {
268
+ return (record.transaction?.writes ?? [record]).map((write) => `${write.collection}:${String(write.key)}`);
269
+ };
270
+ /** One result for several writes: the first failure, or every write's data */
271
+ var combineResults = (results) => {
272
+ return results.find((result) => !result.success) ?? {
273
+ success: true,
274
+ data: results.map((result) => result.data),
275
+ error: null
276
+ };
277
+ };
278
+ var defaultRetryDelay = (attempt) => Math.min(1e3 * 2 ** (attempt - 1), 3e4);
279
+ /** Resolves once the client is online again. `cancel` stops listening, for `destroy`. */
280
+ var waitForOnline = (client) => {
281
+ let resolve;
282
+ const promise = new Promise((done) => {
283
+ resolve = done;
284
+ });
285
+ const cancel = client.appManager.events.onOnline(() => {
286
+ cancel();
287
+ resolve();
288
+ });
289
+ return {
290
+ promise,
291
+ cancel
292
+ };
293
+ };
294
+ //#endregion
295
+ //#region src/mutation/mutation.ts
296
+ /**
297
+ * Sends writes. Each write shows at once as an optimistic layer. Writes to one row go out one at a time, and a failure
298
+ * drops the writes queued after it on that row. With `offline`, every write goes through a persisted outbox that is
299
+ * replayed in order across the whole db by one tab.
300
+ */
301
+ var MutationEngine = class {
302
+ /** The outbox, in replay order */
303
+ outbox = [];
304
+ /** The last write of each row, which the next write to the row waits for while it is pending */
305
+ chains = /* @__PURE__ */ new Map();
306
+ inFlight = /* @__PURE__ */ new Map();
307
+ settleWaiters = /* @__PURE__ */ new Map();
308
+ resolvers = /* @__PURE__ */ new Map();
309
+ /** Writes counted as in flight, so a write is counted once however its sending ends */
310
+ begun = /* @__PURE__ */ new Set();
311
+ /** Whether each settled write succeeded, so `dependsOn` can name a write that already settled */
312
+ outcomes = /* @__PURE__ */ new Map();
313
+ outcomeWaiters = /* @__PURE__ */ new Map();
314
+ /** When each write's request was sent, so a sync event that arrived while it was in flight confirms it */
315
+ sentAt = /* @__PURE__ */ new Map();
316
+ pumping = false;
317
+ retryTimer;
318
+ cancelWait = () => {};
319
+ offline;
320
+ constructor(db, offline, transactions = {}) {
321
+ this.db = db;
322
+ this.transactions = transactions;
323
+ this.offline = offline === true ? {} : offline || void 0;
324
+ }
325
+ /**
326
+ * Applies several writes as one transaction. A named transaction sends them through its `mutationFn` as one request.
327
+ * Without a name, each write goes through its collection's `mutate`, in order, and a failure drops the writes after
328
+ * it and refetches the subsets holding the rows already written.
329
+ */
330
+ submitTransaction = ({ id, name, writes }) => {
331
+ if (writes.length === 0) return createTransaction(id, Promise.resolve({
332
+ success: true,
333
+ data: [],
334
+ error: null
335
+ }));
336
+ return name === void 0 ? this.submitSequence(id, writes) : this.submitNamed(id, name, writes);
337
+ };
338
+ createRecord = (write) => ({
339
+ id: write.id,
340
+ collection: write.collection.name,
341
+ op: write.op,
342
+ key: write.key,
343
+ values: write.values,
344
+ dependsOn: write.dependsOn,
345
+ sent: false,
346
+ createdAt: Date.now()
347
+ });
348
+ /** The result promise of a record, resolved once the record settles */
349
+ track = (record) => {
350
+ return new Promise((resolve) => {
351
+ this.resolvers.set(record.id, resolve);
352
+ this.generations.set(record.id, this.db.generation);
353
+ });
354
+ };
355
+ submitSequence = (id, writes) => {
356
+ const records = writes.map((write, index) => this.createRecord({
357
+ ...write,
358
+ id: `${id}:${index}`,
359
+ dependsOn: index > 0 ? [`${id}:${index - 1}`] : []
360
+ }));
361
+ const results = records.map(this.track);
362
+ this.db.batch(() => {
363
+ writes.forEach((write, index) => {
364
+ if (write.collection.config.mutations[write.op]?.optimistic !== false) write.collection.store.addLayer({
365
+ id: records[index].id,
366
+ key: write.key,
367
+ type: write.op,
368
+ values: write.values
369
+ });
370
+ });
371
+ });
372
+ if (this.offline) records.forEach((record) => this.enqueue(record));
373
+ else this.runSequence(records, results, 0);
374
+ return createTransaction(id, Promise.all(results).then(combineResults));
375
+ };
376
+ /** Sends the writes of an unnamed transaction one after another */
377
+ runSequence = async (records, results, index) => {
378
+ const record = records[index];
379
+ this.runDirect(record);
380
+ if (!(await results[index]).success) {
381
+ records.slice(index + 1).forEach((later) => this.fail(later, new DependencyError(record.id)));
382
+ records.slice(0, index).forEach((written) => {
383
+ const collection = this.db.collections.get(written.collection);
384
+ collection.getSubsetsHolding(collection.resolveKey(written.key)).forEach((subset) => subset.reload());
385
+ });
386
+ return;
387
+ }
388
+ if (index + 1 < records.length) await this.runSequence(records, results, index + 1);
389
+ };
390
+ submitNamed = (id, name, writes) => {
391
+ const transactionWrites = writes.map((write) => ({
392
+ collection: write.collection.name,
393
+ op: write.op,
394
+ key: write.key,
395
+ values: write.values
396
+ }));
397
+ const record = {
398
+ ...this.createRecord({
399
+ ...writes[0],
400
+ id,
401
+ dependsOn: []
402
+ }),
403
+ values: {},
404
+ transaction: {
405
+ name,
406
+ writes: transactionWrites
407
+ }
408
+ };
409
+ const result = this.track(record);
410
+ this.addTransactionLayers(record);
411
+ if (this.offline) this.enqueue(record);
412
+ else this.runDirect(record);
413
+ return createTransaction(id, result);
414
+ };
415
+ addTransactionLayers = (record) => {
416
+ this.db.batch(() => {
417
+ record.transaction.writes.forEach((write, index) => {
418
+ this.db.collections.get(write.collection).store.addLayer({
419
+ id: `${record.id}:${index}`,
420
+ key: write.key,
421
+ type: write.op,
422
+ values: write.values
423
+ });
424
+ });
425
+ });
426
+ };
427
+ /** Runs a callback for each write of a named transaction, as a plain record with its layer id */
428
+ eachWrite = (record, callback) => {
429
+ record.transaction.writes.forEach((write, index) => {
430
+ callback({
431
+ ...record,
432
+ ...write,
433
+ id: `${record.id}:${index}`,
434
+ transaction: void 0
435
+ });
436
+ });
437
+ };
438
+ /** Applies a write optimistically and sends it */
439
+ submit = ({ collection, op, key, values, dependsOn, id, temporaryKey }) => {
440
+ const record = {
441
+ id,
442
+ collection: collection.name,
443
+ op,
444
+ key,
445
+ values,
446
+ dependsOn,
447
+ sent: false,
448
+ createdAt: Date.now(),
449
+ ...temporaryKey ? { temporaryKey: true } : {}
450
+ };
451
+ const result = new Promise((resolve) => {
452
+ this.resolvers.set(id, resolve);
453
+ this.generations.set(id, this.db.generation);
454
+ });
455
+ const mutation = collection.config.mutations[op];
456
+ if (mutation?.optimistic !== false) this.db.batch(() => collection.store.addLayer({
457
+ id,
458
+ key,
459
+ type: op,
460
+ values
461
+ }));
462
+ if (this.offline && mutation?.outbox !== false) this.enqueue(record);
463
+ else this.runDirect(record);
464
+ return createTransaction(id, result);
465
+ };
466
+ /** A write rejected before it was sent, for example by validation */
467
+ reject = (error, id) => {
468
+ return createTransaction(id, Promise.resolve({
469
+ success: false,
470
+ data: null,
471
+ error
472
+ }));
473
+ };
474
+ /** Whether writes go through the outbox */
475
+ get usesOutbox() {
476
+ return Boolean(this.offline);
477
+ }
478
+ /** Resolves once no write of the collection is in flight */
479
+ settled = (collection) => {
480
+ if (!this.inFlight.get(collection)) return Promise.resolve();
481
+ return new Promise((resolve) => {
482
+ this.settleWaiters.set(collection, [...this.settleWaiters.get(collection) ?? [], resolve]);
483
+ });
484
+ };
485
+ /** Rebuilds the optimistic layers of a restored outbox and replays it */
486
+ restore = (records) => {
487
+ this.addRecords(records);
488
+ this.persistOutbox();
489
+ this.pump();
490
+ };
491
+ /**
492
+ * Writes another tab made: a follower sent them to this tab, the leader, or this tab became the leader and adopts the
493
+ * outbox the previous leader persisted. They are persisted together with this tab's own writes and replayed.
494
+ */
495
+ mergeOutbox = (records) => {
496
+ this.addRecords(records);
497
+ this.persistOutbox();
498
+ this.pump();
499
+ };
500
+ /** A new leader asks for the writes followers still wait for */
501
+ resendToLeader = () => {
502
+ if (this.outbox.length > 0) this.db.tabs?.post({
503
+ type: "enqueue",
504
+ records: [...this.outbox]
505
+ });
506
+ };
507
+ /** Adds records this tab does not hold yet, with their optimistic layers, in the order they were made */
508
+ addRecords = (records) => {
509
+ const fresh = this.replayable(records).filter((record) => !this.outbox.some((item) => item.id === record.id));
510
+ if (fresh.length === 0) return;
511
+ fresh.forEach((record) => this.generations.set(record.id, this.db.generation));
512
+ this.db.batch(() => {
513
+ fresh.forEach((record) => {
514
+ if (record.transaction) {
515
+ this.addTransactionLayers(record);
516
+ return;
517
+ }
518
+ this.db.collections.get(record.collection).store.addLayer({
519
+ id: record.id,
520
+ key: record.key,
521
+ type: record.op,
522
+ values: record.values
523
+ });
524
+ });
525
+ });
526
+ this.outbox = [...this.outbox, ...fresh].toSorted((left, right) => left.createdAt - right.createdAt);
527
+ };
528
+ /** The records this db can replay. The others are reported, never dropped silently. */
529
+ replayable = (records) => {
530
+ return records.filter((record) => {
531
+ const canReplay = record.transaction ? Boolean(this.transactions[record.transaction.name]) : Boolean(this.db.collections.get(record.collection)?.config.mutations[record.op]);
532
+ if (!canReplay) {
533
+ const target = record.transaction ? `the transaction "${record.transaction.name}"` : `a write to "${record.collection}"`;
534
+ this.db.emitError({
535
+ type: "outbox",
536
+ error: /* @__PURE__ */ new Error(`The outbox holds ${target} that the db cannot replay`),
537
+ transaction: record
538
+ });
539
+ }
540
+ return canReplay;
541
+ });
542
+ };
543
+ /** The replaying tab reports a write's outcome */
544
+ applyOutcome = (outcome) => {
545
+ const record = this.outbox.find((item) => item.id === outcome.id);
546
+ if (!record) return;
547
+ this.outbox = this.outbox.filter((item) => item.id !== outcome.id);
548
+ if (outcome.success) {
549
+ const collection = this.db.collections.get(record.collection);
550
+ if (record.temporaryKey && outcome.key !== void 0 && outcome.key !== record.key) {
551
+ collection.aliases.set(record.key, outcome.key);
552
+ collection.setRenderKey(outcome.key, collection.getRenderKey(record.key));
553
+ collection.store.rekeyLayers(record.key, outcome.key);
554
+ }
555
+ this.keep(record);
556
+ this.resolve(record, {
557
+ success: true,
558
+ data: null,
559
+ error: null
560
+ });
561
+ } else this.fail(record, outcome.error);
562
+ };
563
+ /** Replays the outbox when this tab is the one that replays it, one write at a time and in order */
564
+ pump = async () => {
565
+ if (!this.offline || this.pumping || !this.db.isLeader) return;
566
+ this.pumping = true;
567
+ await this.db.ready;
568
+ let attempt = 0;
569
+ while (this.outbox.length > 0 && !this.db.isDestroyed) {
570
+ const record = this.outbox[0];
571
+ const client = this.getClient(record);
572
+ if (client && !client.appManager.isOnline) {
573
+ const online = waitForOnline(client);
574
+ this.cancelWait = online.cancel;
575
+ await online.promise;
576
+ continue;
577
+ }
578
+ record.sent = true;
579
+ await this.persistOutbox();
580
+ try {
581
+ const response = await this.send(record, true);
582
+ if (!response) this.removeFromOutbox([record.id]);
583
+ else if (response.success) {
584
+ attempt = 0;
585
+ await this.succeed(record, response);
586
+ this.end(record);
587
+ this.removeFromOutbox([record.id]);
588
+ const serverKey = this.db.collections.get(record.collection)?.resolveKey(record.key);
589
+ this.db.tabs?.post({
590
+ type: "outcome",
591
+ id: record.id,
592
+ success: true,
593
+ ...record.temporaryKey ? { key: serverKey } : {}
594
+ });
595
+ } else if ((this.offline.retryable ?? isTemporaryFailure)(response)) {
596
+ attempt += 1;
597
+ this.end(record);
598
+ const delay = (this.offline.retryDelay ?? defaultRetryDelay)(attempt);
599
+ await new Promise((resolve) => {
600
+ this.retryTimer = setTimeout(resolve, delay);
601
+ });
602
+ } else {
603
+ attempt = 0;
604
+ this.drop(record, response.error ?? response);
605
+ }
606
+ } catch (error) {
607
+ attempt = 0;
608
+ this.drop(record, error);
609
+ }
610
+ }
611
+ this.pumping = false;
612
+ };
613
+ /**
614
+ * Drops every pending write, for example on sign-out. Writes in flight resolve as failed now, and their responses,
615
+ * which carry the previous user's data, are never written.
616
+ */
617
+ clear = () => {
618
+ this.outbox = [];
619
+ this.chains.clear();
620
+ const cleared = {
621
+ success: false,
622
+ data: null,
623
+ error: /* @__PURE__ */ new Error("Cleared")
624
+ };
625
+ [...this.resolvers.values()].forEach((resolve) => resolve(cleared));
626
+ this.resolvers.clear();
627
+ this.sentAt.clear();
628
+ this.persistOutbox();
629
+ };
630
+ /** Stops the retry timer, for `destroy` */
631
+ destroy = () => {
632
+ clearTimeout(this.retryTimer);
633
+ this.cancelWait();
634
+ };
635
+ /** The generation each write was made or restored in, so `clear` ends the writes of the previous user */
636
+ generations = /* @__PURE__ */ new Map();
637
+ /** Whether a write belongs to the current user, rather than to one `clear` ended */
638
+ isActive = (record) => this.generations.get(record.id) === this.db.generation;
639
+ /** Resolves with whether a write succeeded. A write this db never saw, such as one from another session, is done. */
640
+ waitForOutcome = (id) => {
641
+ if (this.outcomes.has(id)) return Promise.resolve(this.outcomes.get(id));
642
+ if (!this.resolvers.has(id)) return Promise.resolve(true);
643
+ return new Promise((resolve) => {
644
+ this.outcomeWaiters.set(id, [...this.outcomeWaiters.get(id) ?? [], resolve]);
645
+ });
646
+ };
647
+ enqueue = async (record) => {
648
+ const failed = record.dependsOn.find((id) => this.outcomes.get(id) === false);
649
+ if (failed) {
650
+ this.fail(record, new DependencyError(failed));
651
+ return;
652
+ }
653
+ this.outbox.push(record);
654
+ if (!this.db.isLeader) {
655
+ this.db.tabs?.post({
656
+ type: "enqueue",
657
+ records: [record]
658
+ });
659
+ this.db.notifyChange();
660
+ return;
661
+ }
662
+ await this.persistOutbox();
663
+ this.pump();
664
+ };
665
+ persistOutbox = () => {
666
+ this.db.notifyChange();
667
+ if (!this.db.isLeader) return Promise.resolve();
668
+ return this.db.persistence?.saveOutbox(this.outbox) ?? Promise.resolve();
669
+ };
670
+ removeFromOutbox = (ids) => {
671
+ this.outbox = this.outbox.filter((record) => !ids.includes(record.id));
672
+ this.persistOutbox();
673
+ };
674
+ runDirect = (record) => {
675
+ const chainKey = `${record.collection}:${String(record.key)}`;
676
+ const last = this.chains.get(chainKey);
677
+ const previous = last && !this.outcomes.has(last.id) ? last.run : Promise.resolve(true);
678
+ this.begin(record);
679
+ const run = previous.then(async (previousSucceeded) => {
680
+ const dependencies = await Promise.all(record.dependsOn.map(this.waitForOutcome));
681
+ const failedDependency = record.dependsOn.find((_id, index) => !dependencies[index]);
682
+ if (!previousSucceeded || failedDependency) {
683
+ this.fail(record, new DependencyError(failedDependency ?? chainKey));
684
+ return false;
685
+ }
686
+ if (!this.isActive(record)) return false;
687
+ try {
688
+ const response = await this.send(record, false);
689
+ if (!response) return false;
690
+ if (response.success) {
691
+ await this.succeed(record, response);
692
+ return true;
693
+ }
694
+ this.fail(record, response.error ?? response);
695
+ return false;
696
+ } catch (error) {
697
+ this.fail(record, error);
698
+ return false;
699
+ }
700
+ });
701
+ this.chains.set(chainKey, {
702
+ id: record.id,
703
+ run
704
+ });
705
+ run.then(() => {
706
+ this.end(record);
707
+ if (this.chains.get(chainKey)?.run === run) this.chains.delete(chainKey);
708
+ });
709
+ };
710
+ /** The client a record's request goes through, so replay waits while it is offline */
711
+ getClient = (record) => {
712
+ if (record.transaction) return this.transactions[record.transaction.name]?.mutationFn({
713
+ id: record.id,
714
+ mutations: record.transaction.writes
715
+ }).client;
716
+ return this.db.collections.get(record.collection)?.config.mutations[record.op]?.request.client;
717
+ };
718
+ send = async (record, fromOutbox) => {
719
+ if (record.transaction) return this.sendNamed(record, fromOutbox);
720
+ const collection = this.db.collections.get(record.collection);
721
+ const mutation = collection.config.mutations[record.op];
722
+ if (!mutation) {
723
+ this.fail(record, /* @__PURE__ */ new Error(`"${record.collection}" declares no ${record.op} mutation`));
724
+ return;
725
+ }
726
+ if (fromOutbox) this.begin(record);
727
+ const key = collection.resolveKey(record.key);
728
+ const context = { id: record.id };
729
+ let patch;
730
+ if (record.op === "insert") {
731
+ const keyField = collection.config.key;
732
+ const withoutKey = Object.fromEntries(Object.entries(record.values).filter(([field]) => field !== keyField));
733
+ patch = mutation.map(record.temporaryKey ? withoutKey : record.values, context);
734
+ } else if (record.op === "update") patch = mutation.map(key, record.values, context);
735
+ else patch = mutation.map(key, context);
736
+ let request = applyRequestPatches(mutation.request, [patch]);
737
+ if (fromOutbox) request = request.setOffline(false);
738
+ this.sentAt.set(record.id, this.db.tick());
739
+ return request.send();
740
+ };
741
+ sendNamed = (record, fromOutbox) => {
742
+ const { name, writes } = record.transaction;
743
+ if (fromOutbox) this.begin(record);
744
+ let request = this.transactions[name].mutationFn({
745
+ id: record.id,
746
+ mutations: writes
747
+ });
748
+ if (fromOutbox) request = request.setOffline(false);
749
+ this.sentAt.set(record.id, this.db.tick());
750
+ return request.send();
751
+ };
752
+ /** A named transaction succeeded: its changes become the server state, or the subsets holding them reload */
753
+ succeedNamed = async (record, response) => {
754
+ const { onSuccess = "keep" } = this.transactions[record.transaction.name];
755
+ if (onSuccess === "refetch") {
756
+ this.end(record);
757
+ const refetches = [];
758
+ this.eachWrite(record, (write) => {
759
+ refetches.push(this.refetch(this.db.collections.get(write.collection), write));
760
+ });
761
+ await Promise.all(refetches);
762
+ this.removeTransactionLayers(record);
763
+ } else this.keep(record);
764
+ this.resolve(record, {
765
+ success: true,
766
+ data: response.data,
767
+ error: null
768
+ });
769
+ };
770
+ removeTransactionLayers = (record) => {
771
+ this.db.batch(() => {
772
+ this.eachWrite(record, (write) => this.db.collections.get(write.collection).store.removeLayer(write.id));
773
+ });
774
+ };
775
+ succeed = async (record, response) => {
776
+ if (!this.isActive(record)) return;
777
+ if (record.transaction) {
778
+ await this.succeedNamed(record, response);
779
+ return;
780
+ }
781
+ const collection = this.db.collections.get(record.collection);
782
+ const mutation = collection.config.mutations[record.op];
783
+ const key = collection.resolveKey(record.key);
784
+ if (record.op === "insert" && record.temporaryKey && mutation.onSuccess) {
785
+ this.end(record);
786
+ const lists = [...collection.listSubsets.values()].filter((subset) => subset.hasLoaded && subset.matchesSent(record.values));
787
+ await Promise.all(lists.map((subset) => subset.reload({ waitForWrites: false })));
788
+ this.db.batch(() => collection.store.removeLayer(record.id));
789
+ this.resolve(record, {
790
+ success: true,
791
+ data: response.data,
792
+ error: null
793
+ });
794
+ return;
795
+ }
796
+ if (mutation.onSuccess === "refetch" || mutation.onSuccess === "sync") {
797
+ this.end(record);
798
+ let confirmed = false;
799
+ if (mutation.onSuccess === "sync") {
800
+ const since = this.sentAt.get(record.id);
801
+ confirmed = await this.db.waitForSync({
802
+ collection: record.collection,
803
+ key,
804
+ since,
805
+ timeout: this.db.syncTimeout
806
+ });
807
+ }
808
+ if (!confirmed) await this.refetch(collection, record);
809
+ this.db.batch(() => collection.store.removeLayer(record.id));
810
+ this.resolve(record, {
811
+ success: true,
812
+ data: response.data,
813
+ error: null
814
+ });
815
+ return;
816
+ }
817
+ this.db.batch(() => {
818
+ if (mutation.onSuccess === "keep") this.writeKept(collection, record);
819
+ else this.writeResponse(collection, record, mutation.row ? mutation.row(response.data) : response.data);
820
+ collection.store.removeLayer(record.id);
821
+ });
822
+ this.resolve(record, {
823
+ success: true,
824
+ data: response.data,
825
+ error: null
826
+ });
827
+ };
828
+ /** A write confirmed by another tab: its values become the server state */
829
+ keep = (record) => {
830
+ if (record.transaction) {
831
+ this.db.batch(() => this.eachWrite(record, this.keep));
832
+ return;
833
+ }
834
+ const collection = this.db.collections.get(record.collection);
835
+ this.db.batch(() => {
836
+ this.writeKept(collection, record);
837
+ collection.store.removeLayer(record.id);
838
+ });
839
+ };
840
+ writeKept = (collection, record) => {
841
+ const key = collection.resolveKey(record.key);
842
+ const stamp = {
843
+ kind: "now",
844
+ seq: this.db.tick(),
845
+ wall: Date.now()
846
+ };
847
+ if (record.op === "delete") {
848
+ collection.store.remove(key, stamp);
849
+ return;
850
+ }
851
+ collection.store.write(key, {
852
+ ...record.values,
853
+ [collection.config.key]: key
854
+ }, {
855
+ complete: record.op === "insert",
856
+ stamp
857
+ });
858
+ };
859
+ writeResponse = (collection, record, data) => {
860
+ const key = collection.resolveKey(record.key);
861
+ const stamp = {
862
+ kind: "now",
863
+ seq: this.db.tick(),
864
+ wall: Date.now()
865
+ };
866
+ if (record.op === "delete") {
867
+ collection.store.remove(key, stamp);
868
+ return;
869
+ }
870
+ if (!isPlainObject$1(data)) return;
871
+ const serverKey = data[collection.config.key] ?? key;
872
+ collection.writeServerRows([{
873
+ ...data,
874
+ [collection.config.key]: serverKey
875
+ }], record.op === "insert", stamp);
876
+ if (record.op !== "insert") return;
877
+ if (serverKey !== record.key) {
878
+ collection.aliases.set(record.key, serverKey);
879
+ collection.setRenderKey(serverKey, collection.getRenderKey(record.key));
880
+ collection.store.rekeyLayers(record.key, serverKey);
881
+ }
882
+ collection.noteInsert(serverKey);
883
+ };
884
+ /** Reloads the subsets that hold the row, after the loads already in flight */
885
+ refetch = async (collection, record) => {
886
+ const key = collection.resolveKey(record.key);
887
+ const subsets = collection.getSubsetsHolding(key);
888
+ if (subsets.length === 0) {
889
+ this.db.batch(() => this.writeKept(collection, record));
890
+ return;
891
+ }
892
+ await Promise.all(subsets.map((subset) => subset.reload({ waitForWrites: false })));
893
+ };
894
+ /** Drops a rejected outbox write and every later write that was built on it */
895
+ drop = (record, error) => {
896
+ const droppedIds = new Set([record.id]);
897
+ const droppedRows = new Set(rowsOf(record));
898
+ const dropped = [record];
899
+ this.outbox.slice(1).forEach((later) => {
900
+ const rows = rowsOf(later);
901
+ if (rows.some((row) => droppedRows.has(row)) || later.dependsOn.some((id) => droppedIds.has(id))) {
902
+ droppedIds.add(later.id);
903
+ rows.forEach((row) => droppedRows.add(row));
904
+ dropped.push(later);
905
+ }
906
+ });
907
+ this.end(record);
908
+ this.removeFromOutbox([...droppedIds]);
909
+ dropped.forEach((item) => {
910
+ const reason = item === record ? error : new DependencyError(record.id);
911
+ this.fail(item, reason);
912
+ this.db.tabs?.post({
913
+ type: "outcome",
914
+ id: item.id,
915
+ success: false,
916
+ error: String(reason)
917
+ });
918
+ });
919
+ };
920
+ fail = (record, error) => {
921
+ const active = this.isActive(record);
922
+ if (record.transaction) this.removeTransactionLayers(record);
923
+ else {
924
+ const collection = this.db.collections.get(record.collection);
925
+ this.db.batch(() => collection?.store.removeLayer(record.id));
926
+ }
927
+ this.resolve(record, {
928
+ success: false,
929
+ data: null,
930
+ error
931
+ });
932
+ if (active) this.db.emitError({
933
+ type: "mutation",
934
+ error,
935
+ collection: record.collection,
936
+ transaction: record
937
+ });
938
+ };
939
+ resolve = (record, result) => {
940
+ this.resolvers.get(record.id)?.(result);
941
+ this.resolvers.delete(record.id);
942
+ this.sentAt.delete(record.id);
943
+ this.outcomes.set(record.id, result.success);
944
+ this.outcomeWaiters.get(record.id)?.forEach((notify) => notify(result.success));
945
+ this.outcomeWaiters.delete(record.id);
946
+ };
947
+ /** The collections a write changes: one, or every collection a named transaction writes */
948
+ collectionsOf = (record) => [...new Set((record.transaction?.writes ?? [record]).map((write) => write.collection))];
949
+ /** Counts a sent write as in flight in every collection it changes, once per attempt */
950
+ begin = (record) => {
951
+ this.begun.add(record.id);
952
+ this.collectionsOf(record).forEach((collection) => {
953
+ this.inFlight.set(collection, (this.inFlight.get(collection) ?? 0) + 1);
954
+ });
955
+ };
956
+ /** Ends a write's in-flight state once, even when its success handling ended it early */
957
+ end = (record) => {
958
+ if (!this.begun.delete(record.id)) return;
959
+ this.collectionsOf(record).forEach((collection) => {
960
+ const count = this.inFlight.get(collection) - 1;
961
+ this.inFlight.set(collection, count);
962
+ if (count > 0) return;
963
+ const waiters = this.settleWaiters.get(collection) ?? [];
964
+ this.settleWaiters.delete(collection);
965
+ waiters.forEach((resolve) => resolve());
966
+ });
967
+ };
968
+ };
969
+ //#endregion
970
+ //#region src/operators/operators.utils.ts
971
+ /** Turns a value into the form the db compares: dates become their instant */
972
+ var normalize = (value) => value instanceof Date ? value.getTime() : value;
973
+ /** Compares two strings by Unicode code point, so the order does not depend on the runtime's locale */
974
+ var compareStrings = (left, right) => {
975
+ const leftPoints = [...left];
976
+ const rightPoints = [...right];
977
+ const length = Math.min(leftPoints.length, rightPoints.length);
978
+ for (let index = 0; index < length; index += 1) {
979
+ const difference = leftPoints[index].codePointAt(0) - rightPoints[index].codePointAt(0);
980
+ if (difference !== 0) return difference < 0 ? -1 : 1;
981
+ }
982
+ if (leftPoints.length === rightPoints.length) return 0;
983
+ return leftPoints.length < rightPoints.length ? -1 : 1;
984
+ };
985
+ /** Two values are equal when they are the same value, or dates of the same instant */
986
+ var isEqualValue = (left, right) => {
987
+ return Object.is(normalize(left), normalize(right));
988
+ };
989
+ /**
990
+ * Orders two values. `null` and `undefined` sort before every other value. Strings compare by code point, dates by
991
+ * instant, and values of different types by their type name, so the order is always total.
992
+ */
993
+ var compareValues = (left, right) => {
994
+ const a = normalize(left);
995
+ const b = normalize(right);
996
+ const aEmpty = a === null || a === void 0;
997
+ const bEmpty = b === null || b === void 0;
998
+ if (aEmpty || bEmpty) {
999
+ if (aEmpty && bEmpty) return 0;
1000
+ return aEmpty ? -1 : 1;
1001
+ }
1002
+ if (typeof a === "string" && typeof b === "string") return compareStrings(a, b);
1003
+ if (typeof a !== typeof b) return compareStrings(typeof a, typeof b);
1004
+ if (Object.is(a, b)) return 0;
1005
+ if (Number.isNaN(a) || Number.isNaN(b)) return Number.isNaN(a) ? 1 : -1;
1006
+ return a < b ? -1 : 1;
1007
+ };
1008
+ var isEmpty = (value) => value === null || value === void 0;
1009
+ var evaluateComparison = (node, row) => {
1010
+ const value = row[node.field];
1011
+ switch (node.op) {
1012
+ case "eq": return isEqualValue(value, node.value);
1013
+ case "inArray": return node.value.some((item) => isEqualValue(value, item));
1014
+ case "gt": return !isEmpty(value) && compareValues(value, node.value) > 0;
1015
+ case "gte": return !isEmpty(value) && compareValues(value, node.value) >= 0;
1016
+ case "lt": return !isEmpty(value) && compareValues(value, node.value) < 0;
1017
+ default: return !isEmpty(value) && compareValues(value, node.value) <= 0;
1018
+ }
1019
+ };
1020
+ /** Evaluates a filter expression on one row */
1021
+ var evaluate = (node, row) => {
1022
+ switch (node.op) {
1023
+ case "and": return node.items.every((item) => evaluate(item, row));
1024
+ case "or": return node.items.some((item) => evaluate(item, row));
1025
+ case "not": return !evaluate(node.item, row);
1026
+ case "server": return true;
1027
+ default: return evaluateComparison(node, row);
1028
+ }
1029
+ };
1030
+ /** Splits an expression at its top-level `and`, flattening nested `and` nodes */
1031
+ var splitAnd = (node) => {
1032
+ if (!node) return [];
1033
+ if (node.op === "and") return node.items.flatMap((item) => splitAnd(item));
1034
+ return [node];
1035
+ };
1036
+ /** The fields an expression reads */
1037
+ var getExpressionFields = (node) => {
1038
+ switch (node.op) {
1039
+ case "and":
1040
+ case "or": return node.items.flatMap((item) => getExpressionFields(item));
1041
+ case "not": return getExpressionFields(node.item);
1042
+ default: return [node.field];
1043
+ }
1044
+ };
1045
+ /** A JSON value that identifies a value structurally. Dates keep their instant. */
1046
+ var toStableValue = (value) => {
1047
+ if (value instanceof Date) return { $date: value.getTime() };
1048
+ if (typeof value === "bigint") return { $bigint: value.toString() };
1049
+ if (typeof value === "number" && !Number.isFinite(value)) return { $number: String(value) };
1050
+ if (value === void 0) return { $undefined: true };
1051
+ if (value instanceof Map) return { $map: [...value.entries()].map(([key, item]) => [toStableValue(key), toStableValue(item)]) };
1052
+ if (value instanceof Set) return { $set: [...value].map((item) => toStableValue(item)) };
1053
+ if (Array.isArray(value)) return value.map((item) => toStableValue(item));
1054
+ if (value && typeof value === "object") return Object.fromEntries(Object.keys(value).toSorted().map((key) => [key, toStableValue(value[key])]));
1055
+ return value;
1056
+ };
1057
+ /** A string that is equal for structurally equal values */
1058
+ var stableStringify = (value) => JSON.stringify(toStableValue(value));
1059
+ //#endregion
1060
+ //#region src/query/infinite-query.ts
1061
+ var toPages = (items, pageSize) => {
1062
+ return Array.from({ length: Math.ceil(items.length / pageSize) }, (_, index) => items.slice(index * pageSize, (index + 1) * pageSize));
1063
+ };
1064
+ /**
1065
+ * A window over an ordered live query: the first `pageSize` times the number of pages rows of its result. Widening it
1066
+ * shows rows the db holds at once and loads more from the query's loader only when the window runs past them.
1067
+ *
1068
+ * The window belongs to this instance, so two components showing the same query share its live query and its subset,
1069
+ * and each keeps its own number of pages.
1070
+ */
1071
+ var InfiniteQuery = class {
1072
+ /** Identifies the infinite query by its query's structure and page size */
1073
+ key;
1074
+ pageCount = 1;
1075
+ live;
1076
+ /** The live query of the previous window, shown while a wider `limit` loads */
1077
+ previous;
1078
+ unsubscribeLive;
1079
+ listeners = /* @__PURE__ */ new Set();
1080
+ filling;
1081
+ widening;
1082
+ paging;
1083
+ snapshot;
1084
+ constructor(runtime, definition, options) {
1085
+ this.runtime = runtime;
1086
+ this.definition = definition;
1087
+ this.options = options;
1088
+ if (!Number.isInteger(options.pageSize) || options.pageSize < 1) throw new Error(`An infinite query needs a whole pageSize of at least 1, received ${options.pageSize}`);
1089
+ this.key = stableStringify({
1090
+ definition,
1091
+ pageSize: options.pageSize
1092
+ });
1093
+ this.paging = runtime.getLiveQuery(definition).getPaging();
1094
+ this.live = runtime.getLiveQuery(this.getDefinition());
1095
+ }
1096
+ subscribe = (listener) => {
1097
+ this.listeners.add(listener);
1098
+ if (this.listeners.size === 1) {
1099
+ this.live = this.runtime.getLiveQuery(this.getDefinition());
1100
+ this.unsubscribeLive = this.live.subscribe(this.onLiveChange);
1101
+ this.fill();
1102
+ }
1103
+ return () => {
1104
+ this.listeners.delete(listener);
1105
+ if (this.listeners.size === 0) {
1106
+ this.unsubscribeLive();
1107
+ this.unsubscribeLive = void 0;
1108
+ this.dropPrevious();
1109
+ }
1110
+ };
1111
+ };
1112
+ getSnapshot = () => {
1113
+ const { source, pageCount } = this.getSource();
1114
+ const fetching = this.isFetchingNextPage();
1115
+ const cached = this.snapshot;
1116
+ if (cached && cached.source === source && cached.pageCount === pageCount && cached.fetching === fetching) return cached.value;
1117
+ const size = pageCount * this.options.pageSize;
1118
+ const rows = source.data;
1119
+ const data = rows?.slice(0, size);
1120
+ const value = {
1121
+ ...source,
1122
+ data,
1123
+ pages: data ? toPages(data, this.options.pageSize) : [],
1124
+ hasNextPage: (rows?.length ?? 0) > size || this.paging === "cursor" && source.hasNextPage,
1125
+ isFetchingNextPage: fetching
1126
+ };
1127
+ this.snapshot = {
1128
+ source,
1129
+ pageCount,
1130
+ fetching,
1131
+ value
1132
+ };
1133
+ return value;
1134
+ };
1135
+ /**
1136
+ * Widens the window by one page. Rows the db holds show at once, and the loader loads more when the window runs past
1137
+ * them. Resolves once the window is filled or the backend has no more rows.
1138
+ */
1139
+ fetchNextPage = () => {
1140
+ if (this.filling || this.previous) return this.filling ?? this.widening;
1141
+ if (!this.unsubscribeLive || !this.getSnapshot().hasNextPage) return Promise.resolve();
1142
+ this.pageCount += 1;
1143
+ if (this.paging === "limit") return this.widenLimit();
1144
+ this.notify();
1145
+ return this.fill();
1146
+ };
1147
+ /** Loads the query again from its first page */
1148
+ refetch = () => this.live.refetch();
1149
+ getDefinition = () => {
1150
+ if (this.paging !== "limit") return this.definition;
1151
+ return {
1152
+ ...this.definition,
1153
+ limit: this.pageCount * this.options.pageSize + 1
1154
+ };
1155
+ };
1156
+ /** The state and window the snapshot shows: the previous window while a wider one loads its first response */
1157
+ getSource = () => {
1158
+ const state = this.live.getState();
1159
+ if (this.previous && state.status === "loading") return {
1160
+ source: this.previous.live.getState(),
1161
+ pageCount: this.previous.pageCount
1162
+ };
1163
+ return {
1164
+ source: state,
1165
+ pageCount: this.pageCount
1166
+ };
1167
+ };
1168
+ isFetchingNextPage = () => Boolean(this.filling) || Boolean(this.previous);
1169
+ onLiveChange = () => {
1170
+ if (this.previous && this.live.getState().status !== "loading") this.dropPrevious();
1171
+ this.fill();
1172
+ this.notify();
1173
+ };
1174
+ /** Loads backend pages until the db holds one row past the window, or the backend has none */
1175
+ fill = () => {
1176
+ if (this.filling) return this.filling;
1177
+ const state = this.live.getState();
1178
+ const size = this.pageCount * this.options.pageSize;
1179
+ const held = state.data?.length ?? 0;
1180
+ if (!this.unsubscribeLive || this.paging !== "cursor" || state.status === "loading" || !state.hasNextPage || held > size) return Promise.resolve();
1181
+ this.filling = this.live.fetchNextPage().then(() => {
1182
+ this.filling = void 0;
1183
+ const next = this.live.getState();
1184
+ const failed = next.error !== null && next.error !== void 0;
1185
+ this.notify();
1186
+ return failed || next.data.length <= held ? void 0 : this.fill();
1187
+ });
1188
+ this.notify();
1189
+ return this.filling;
1190
+ };
1191
+ /** A loader with `limit` and no cursor is sent the window size plus one, as a new live query */
1192
+ widenLimit = () => {
1193
+ const next = this.runtime.getLiveQuery(this.getDefinition());
1194
+ this.previous = {
1195
+ live: this.live,
1196
+ unsubscribe: this.unsubscribeLive,
1197
+ pageCount: this.pageCount - 1
1198
+ };
1199
+ this.live = next;
1200
+ this.unsubscribeLive = next.subscribe(this.onLiveChange);
1201
+ this.notify();
1202
+ this.widening = new Promise((resolve) => {
1203
+ let settled = false;
1204
+ const check = () => {
1205
+ if (!settled && next.getState().status !== "loading") {
1206
+ settled = true;
1207
+ resolve();
1208
+ queueMicrotask(() => stop());
1209
+ }
1210
+ };
1211
+ const stop = next.subscribe(check);
1212
+ check();
1213
+ });
1214
+ return this.widening;
1215
+ };
1216
+ dropPrevious = () => {
1217
+ this.previous?.unsubscribe();
1218
+ this.previous = void 0;
1219
+ };
1220
+ notify = () => {
1221
+ this.listeners.forEach((listener) => listener());
1222
+ };
1223
+ };
1224
+ //#endregion
1225
+ //#region src/query/query.ts
1226
+ var createRefs = () => {
1227
+ return new Proxy({}, { get: (_target, field) => ({
1228
+ kind: "field",
1229
+ field
1230
+ }) });
1231
+ };
1232
+ /**
1233
+ * An immutable description of a query over one collection. Each method returns a new query, and two queries with the
1234
+ * same structure are the same query, so a component can rebuild its query on every render.
1235
+ *
1236
+ * The type parameters record what the query asks a backend for, so the types can check that a loader serves it.
1237
+ */
1238
+ var Query = class Query {
1239
+ /** Identifies the query by its structure */
1240
+ key;
1241
+ constructor(runtime, definition) {
1242
+ this.runtime = runtime;
1243
+ this.definition = definition;
1244
+ this.key = stableStringify(definition);
1245
+ }
1246
+ /**
1247
+ * Filters rows. The db splits the condition at its top-level `and`: conditions the loader declares are sent to the
1248
+ * backend, and the rest run on the rows the db holds. Calling it again adds conditions.
1249
+ */
1250
+ where(callback) {
1251
+ const { node } = callback(createRefs());
1252
+ const where = this.definition.where ? {
1253
+ op: "and",
1254
+ items: [this.definition.where, node]
1255
+ } : node;
1256
+ return new Query(this.runtime, {
1257
+ ...this.definition,
1258
+ where
1259
+ });
1260
+ }
1261
+ /** Sorts rows by a field. Calling it again adds a sort that breaks ties of the previous ones. */
1262
+ orderBy(callback, direction = "asc") {
1263
+ const { field } = callback(createRefs());
1264
+ return new Query(this.runtime, {
1265
+ ...this.definition,
1266
+ orderBy: [...this.definition.orderBy, {
1267
+ field,
1268
+ direction
1269
+ }]
1270
+ });
1271
+ }
1272
+ /** Picks and renames the fields each result holds */
1273
+ select(callback) {
1274
+ const selection = callback(createRefs());
1275
+ const select = Object.fromEntries(Object.entries(selection).map(([output, ref]) => [output, ref.field]));
1276
+ return new Query(this.runtime, {
1277
+ ...this.definition,
1278
+ select
1279
+ });
1280
+ }
1281
+ /**
1282
+ * Adds the row of another collection whose key is the given field, as a left join: each result holds it under `name`,
1283
+ * or `undefined` while it is not loaded or when there is none. With `{ type: "inner" }`, results without a joined row
1284
+ * are left out. With `{ on: "postId" }`, the join matches that field of the joined collection instead of its key and
1285
+ * holds an array of every matching row, loaded through a list loader that can send `inArray` on it. Options go in an
1286
+ * object with the field as `by`, as in `join("comments", db.comment, { by: (post) => post.id, on: "postId" })`. The db loads joined rows in batches through the joined
1287
+ * collection's key loader, and a result updates whenever its joined row changes. Joined rows are loaded by key, so
1288
+ * only syncs without `where` reach them.
1289
+ */
1290
+ join(name, collection, by) {
1291
+ const options = typeof by === "function" ? {} : by;
1292
+ const { field } = (typeof by === "function" ? by : by.by)(createRefs());
1293
+ const join = {
1294
+ name,
1295
+ collection: collection.collectionName,
1296
+ field,
1297
+ ...options.type === "inner" ? { type: "inner" } : {},
1298
+ ...options.on ? { on: options.on } : {}
1299
+ };
1300
+ return new Query(this.runtime, {
1301
+ ...this.definition,
1302
+ joins: [...this.definition.joins ?? [], join]
1303
+ });
1304
+ }
1305
+ /** Limits the number of results. A paginated loader that declares `limit` receives it as its page size. */
1306
+ limit(limit) {
1307
+ return new Query(this.runtime, {
1308
+ ...this.definition,
1309
+ limit
1310
+ });
1311
+ }
1312
+ /** Reads only the rows the db holds and never sends a request */
1313
+ local() {
1314
+ return new Query(this.runtime, {
1315
+ ...this.definition,
1316
+ local: true
1317
+ });
1318
+ }
1319
+ /**
1320
+ * Subscribes to the query's state. The first subscriber attaches the query to the subset that serves it, which loads
1321
+ * when it is stale. Returns a function that unsubscribes.
1322
+ */
1323
+ subscribe(listener) {
1324
+ return this.runtime.getLiveQuery(this.definition).subscribe(listener);
1325
+ }
1326
+ /** The current state. It keeps its identity until something changes, as `useSyncExternalStore` expects. */
1327
+ getSnapshot() {
1328
+ return this.runtime.getLiveQuery(this.definition).getState();
1329
+ }
1330
+ /** Reads the query once: resolves with the first state that is not loading */
1331
+ get() {
1332
+ const live = this.runtime.getLiveQuery(this.definition);
1333
+ return new Promise((resolve) => {
1334
+ let settled = false;
1335
+ const settle = () => {
1336
+ const state = live.getState();
1337
+ if (settled || state.status === "loading") return;
1338
+ settled = true;
1339
+ resolve(state);
1340
+ queueMicrotask(() => unsubscribe());
1341
+ };
1342
+ const unsubscribe = live.subscribe(settle);
1343
+ settle();
1344
+ });
1345
+ }
1346
+ /**
1347
+ * A window over the query's ordered result, widened one page at a time with `fetchNextPage`. Rows the db holds show
1348
+ * at once, and the loader loads more only when the window runs past them. The query must have `orderBy`, so a page
1349
+ * never shifts between renders.
1350
+ *
1351
+ * @example
1352
+ * const feed = db.post.orderBy((post) => post.createdAt, "desc").infinite({ pageSize: 20 });
1353
+ * feed.subscribe(() => render(feed.getSnapshot().pages));
1354
+ */
1355
+ infinite(options) {
1356
+ return new InfiniteQuery(this.runtime, this.definition, options);
1357
+ }
1358
+ /** Loads the query's subset again */
1359
+ refetch() {
1360
+ return this.runtime.getLiveQuery(this.definition).refetch();
1361
+ }
1362
+ /** Loads the next page of a paginated query */
1363
+ fetchNextPage() {
1364
+ return this.runtime.getLiveQuery(this.definition).fetchNextPage();
1365
+ }
1366
+ /** How the db serves the query: the loader, what is sent, what runs locally and which syncs keep it live */
1367
+ explain() {
1368
+ return this.runtime.getLiveQuery(this.definition).explain();
1369
+ }
1370
+ };
1371
+ //#endregion
1372
+ //#region src/persistence/snapshot.ts
1373
+ var snapshotCollection = (collection) => {
1374
+ const { store } = collection;
1375
+ return {
1376
+ rows: store.getServerKeys().map((key) => [key, store.getServerRow(key)]),
1377
+ subsets: [...collection.listSubsets.values()].filter((subset) => subset.hasLoaded).map((subset) => ({
1378
+ plan: subset.plan,
1379
+ definition: subset.definition,
1380
+ owned: [...subset.owned].toSorted((left, right) => subset.orderIndex.get(left) - subset.orderIndex.get(right)),
1381
+ cursor: subset.cursor,
1382
+ hasMore: subset.hasMore,
1383
+ pages: subset.pages,
1384
+ loadedAt: subset.loadedAt
1385
+ }))
1386
+ };
1387
+ };
1388
+ /**
1389
+ * Writes a snapshot's rows and subsets into a collection. The subsets answer queries at once but count as stale,
1390
+ * because events sent since the snapshot was taken were missed, so they refetch when a query mounts.
1391
+ */
1392
+ var restoreSnapshot = (collection, snapshot) => {
1393
+ collection.db.batch(() => {
1394
+ snapshot.rows.forEach(([rowKey, row]) => {
1395
+ collection.store.write(rowKey, row, {
1396
+ complete: true,
1397
+ stamp: {
1398
+ kind: "sent",
1399
+ seq: 0,
1400
+ wall: 0
1401
+ }
1402
+ });
1403
+ });
1404
+ snapshot.subsets.forEach((stored) => {
1405
+ const subset = collection.getListSubset(stored.plan, {
1406
+ collection: collection.name,
1407
+ orderBy: stored.definition.orderBy,
1408
+ limit: stored.definition.limit,
1409
+ local: false
1410
+ });
1411
+ stored.owned.forEach((ownedKey, index) => {
1412
+ subset.owned.add(ownedKey);
1413
+ subset.orderIndex.set(ownedKey, index);
1414
+ });
1415
+ subset.cursor = stored.cursor;
1416
+ subset.hasMore = stored.hasMore;
1417
+ subset.pages = stored.pages;
1418
+ subset.hasLoaded = true;
1419
+ subset.loadedAt = stored.loadedAt;
1420
+ subset.invalidated = true;
1421
+ subset.notify();
1422
+ });
1423
+ });
1424
+ };
1425
+ /**
1426
+ * Persists server rows, loaded subsets and the outbox under a scope, such as the user id. Rows of another db version
1427
+ * are cleared, because the server holds a copy. The outbox is never cleared with them.
1428
+ */
1429
+ var Persistence = class {
1430
+ networkTimeout;
1431
+ storage;
1432
+ prefix;
1433
+ version;
1434
+ serializer;
1435
+ /** Set when the stored outbox cannot be read, so it is never written over */
1436
+ outboxLocked = false;
1437
+ scheduled = /* @__PURE__ */ new Set();
1438
+ timer;
1439
+ constructor(db, options, serializer) {
1440
+ this.db = db;
1441
+ this.storage = options.storage;
1442
+ this.prefix = `hf-db:${options.scope ?? "default"}`;
1443
+ this.version = options.version ?? 1;
1444
+ this.networkTimeout = options.networkTimeout ?? 5e3;
1445
+ this.serializer = serializer;
1446
+ }
1447
+ /** Restores every collection and returns the persisted outbox */
1448
+ restore = async () => {
1449
+ await Promise.all([...this.db.collections.values()].map((collection) => this.restoreCollection(collection)));
1450
+ return this.loadOutbox();
1451
+ };
1452
+ /**
1453
+ * Reads the outbox. An outbox this version cannot read, corrupt or of another format, is reported and never written
1454
+ * over, because it may hold the only copy of writes another version of the app can replay.
1455
+ */
1456
+ loadOutbox = async () => {
1457
+ const key = `${this.prefix}:outbox`;
1458
+ let raw;
1459
+ try {
1460
+ raw = await this.storage.getItem(key);
1461
+ } catch (error) {
1462
+ this.db.emitError({
1463
+ type: "persistence",
1464
+ error
1465
+ });
1466
+ return [];
1467
+ }
1468
+ if (!raw) return [];
1469
+ let stored;
1470
+ try {
1471
+ stored = this.serializer.parse(raw);
1472
+ } catch (error) {
1473
+ this.outboxLocked = true;
1474
+ this.db.emitError({
1475
+ type: "persistence",
1476
+ error
1477
+ });
1478
+ return [];
1479
+ }
1480
+ if (stored.format !== 1) {
1481
+ this.outboxLocked = true;
1482
+ this.db.emitError({
1483
+ type: "outbox",
1484
+ error: /* @__PURE__ */ new Error(`The persisted outbox has format ${stored.format}, which this version cannot replay`)
1485
+ });
1486
+ return [];
1487
+ }
1488
+ return stored.entries;
1489
+ };
1490
+ saveOutbox = (entries) => {
1491
+ if (this.outboxLocked) return Promise.resolve();
1492
+ const value = {
1493
+ format: 1,
1494
+ entries
1495
+ };
1496
+ return this.write(`${this.prefix}:outbox`, value);
1497
+ };
1498
+ /** Saves the collections whose rows changed, once the current tick is over */
1499
+ scheduleSave = (collections) => {
1500
+ if (!this.db.isLeader || !this.db.isReady) return;
1501
+ [...collections].forEach((collection) => this.scheduled.add(collection));
1502
+ if (this.timer || this.scheduled.size === 0) return;
1503
+ this.timer = setTimeout(() => {
1504
+ this.timer = void 0;
1505
+ const due = [...this.scheduled];
1506
+ this.scheduled.clear();
1507
+ due.forEach((collection) => this.saveCollection(collection));
1508
+ }, 0);
1509
+ };
1510
+ saveCollection = (collection) => {
1511
+ const value = {
1512
+ version: this.version,
1513
+ ...snapshotCollection(collection)
1514
+ };
1515
+ return this.write(`${this.prefix}:rows:${collection.name}`, value);
1516
+ };
1517
+ /** Removes everything this scope persisted */
1518
+ clear = async () => {
1519
+ clearTimeout(this.timer);
1520
+ this.timer = void 0;
1521
+ this.scheduled.clear();
1522
+ await Promise.all([this.remove(`${this.prefix}:outbox`), ...[...this.db.collections.keys()].map((name) => this.remove(`${this.prefix}:rows:${name}`))]);
1523
+ };
1524
+ destroy = () => {
1525
+ clearTimeout(this.timer);
1526
+ this.timer = void 0;
1527
+ };
1528
+ restoreCollection = async (collection) => {
1529
+ const key = `${this.prefix}:rows:${collection.name}`;
1530
+ const stored = await this.read(key);
1531
+ if (!stored) return;
1532
+ if (stored.version !== this.version) {
1533
+ await this.remove(key);
1534
+ return;
1535
+ }
1536
+ restoreSnapshot(collection, {
1537
+ ...stored,
1538
+ subsets: stored.subsets.map((subset) => ({
1539
+ ...subset,
1540
+ loadedAt: 0
1541
+ }))
1542
+ });
1543
+ };
1544
+ read = async (key) => {
1545
+ try {
1546
+ const raw = await this.storage.getItem(key);
1547
+ return raw ? this.serializer.parse(raw) : void 0;
1548
+ } catch (error) {
1549
+ this.db.emitError({
1550
+ type: "persistence",
1551
+ error
1552
+ });
1553
+ return;
1554
+ }
1555
+ };
1556
+ write = async (key, value) => {
1557
+ try {
1558
+ await this.storage.setItem(key, this.serializer.stringify(value));
1559
+ } catch (error) {
1560
+ this.db.emitError({
1561
+ type: "persistence",
1562
+ error
1563
+ });
1564
+ }
1565
+ };
1566
+ remove = async (key) => {
1567
+ try {
1568
+ await this.storage.removeItem(key);
1569
+ } catch (error) {
1570
+ this.db.emitError({
1571
+ type: "persistence",
1572
+ error
1573
+ });
1574
+ }
1575
+ };
1576
+ };
1577
+ //#endregion
1578
+ //#region src/persistence/serializer.ts
1579
+ var TAG = "$hf";
1580
+ var isPlainObject = (value) => {
1581
+ if (typeof value !== "object" || value === null) return false;
1582
+ const prototype = Object.getPrototypeOf(value);
1583
+ return prototype === Object.prototype || prototype === null;
1584
+ };
1585
+ var isTagged = (value) => isPlainObject(value) && typeof value[TAG] === "string";
1586
+ /**
1587
+ * Stores values as type-tagged JSON, so `Date`, `bigint`, `Map`, `Set`, `undefined`, `NaN` and the infinities come back
1588
+ * as they were. Persistence, the outbox and server rendering use it.
1589
+ */
1590
+ var createSerializer = (codecs = []) => {
1591
+ const encode = (value) => {
1592
+ const codec = codecs.find((item) => item.test(value));
1593
+ if (codec) return {
1594
+ [TAG]: codec.name,
1595
+ v: encode(codec.encode(value))
1596
+ };
1597
+ if (value === void 0) return { [TAG]: "undefined" };
1598
+ if (typeof value === "number" && !Number.isFinite(value)) return {
1599
+ [TAG]: "number",
1600
+ v: String(value)
1601
+ };
1602
+ if (typeof value === "bigint") return {
1603
+ [TAG]: "bigint",
1604
+ v: value.toString()
1605
+ };
1606
+ if (value instanceof Date) return {
1607
+ [TAG]: "Date",
1608
+ v: encode(value.getTime())
1609
+ };
1610
+ if (value instanceof Map) return {
1611
+ [TAG]: "Map",
1612
+ v: [...value.entries()].map(([key, item]) => [encode(key), encode(item)])
1613
+ };
1614
+ if (value instanceof Set) return {
1615
+ [TAG]: "Set",
1616
+ v: [...value].map(encode)
1617
+ };
1618
+ if (Array.isArray(value)) return value.map(encode);
1619
+ if (isPlainObject(value)) {
1620
+ const encoded = Object.fromEntries(Object.entries(value).map(([key, item]) => [key, encode(item)]));
1621
+ return TAG in value ? {
1622
+ [TAG]: "object",
1623
+ v: encoded
1624
+ } : encoded;
1625
+ }
1626
+ return value;
1627
+ };
1628
+ const decodeEntries = (value) => Object.fromEntries(Object.entries(value).map(([key, item]) => [key, decode(item)]));
1629
+ const decodeTagged = ({ [TAG]: tag, v }) => {
1630
+ switch (tag) {
1631
+ case "undefined": return;
1632
+ case "number": return Number(v);
1633
+ case "bigint": return BigInt(v);
1634
+ case "Date": return new Date(decode(v));
1635
+ case "Map": return new Map(v.map(([key, item]) => [decode(key), decode(item)]));
1636
+ case "Set": return new Set(v.map(decode));
1637
+ case "object": return decodeEntries(v);
1638
+ default: {
1639
+ const codec = codecs.find((item) => item.name === tag);
1640
+ if (!codec) throw new Error(`No codec decodes stored values tagged "${tag}"`);
1641
+ return codec.decode(decode(v));
1642
+ }
1643
+ }
1644
+ };
1645
+ function decode(value) {
1646
+ if (Array.isArray(value)) return value.map(decode);
1647
+ if (isTagged(value)) return decodeTagged(value);
1648
+ if (isPlainObject(value)) return decodeEntries(value);
1649
+ return value;
1650
+ }
1651
+ return {
1652
+ encode,
1653
+ decode,
1654
+ stringify: (value) => JSON.stringify(encode(value)),
1655
+ parse: (raw) => decode(JSON.parse(raw))
1656
+ };
1657
+ };
1658
+ //#endregion
1659
+ //#region src/persistence/tabs.ts
1660
+ var getDefaultLocks = () => {
1661
+ return globalThis.navigator?.locks;
1662
+ };
1663
+ var getDefaultChannel = (name) => {
1664
+ if (typeof BroadcastChannel === "undefined") return;
1665
+ return new BroadcastChannel(name);
1666
+ };
1667
+ /**
1668
+ * Elects the one tab that replays the outbox and writes persisted rows, with Web Locks. Without Web Locks every tab
1669
+ * treats itself as the leader. Tabs exchange outbox changes, outcomes and rows over a `BroadcastChannel`.
1670
+ */
1671
+ var Tabs = class {
1672
+ isLeader = false;
1673
+ closed = false;
1674
+ locks;
1675
+ channel;
1676
+ releaseLock;
1677
+ listener = (event) => this.handlers.onMessage(event.data);
1678
+ constructor(name, options, handlers) {
1679
+ this.name = name;
1680
+ this.handlers = handlers;
1681
+ this.locks = options ? options.locks : getDefaultLocks();
1682
+ this.channel = options ? options.channel : getDefaultChannel(name);
1683
+ }
1684
+ start = () => {
1685
+ this.channel?.addEventListener("message", this.listener);
1686
+ if (!this.locks) {
1687
+ this.becomeLeader();
1688
+ return;
1689
+ }
1690
+ this.locks.request(`${this.name}:leader`, () => {
1691
+ if (this.closed) return Promise.resolve();
1692
+ this.becomeLeader();
1693
+ return new Promise((resolve) => {
1694
+ this.releaseLock = resolve;
1695
+ });
1696
+ });
1697
+ };
1698
+ post = (message) => {
1699
+ if (this.closed) return;
1700
+ this.channel?.postMessage(message);
1701
+ };
1702
+ close = () => {
1703
+ this.closed = true;
1704
+ this.releaseLock?.();
1705
+ this.releaseLock = void 0;
1706
+ this.isLeader = false;
1707
+ this.channel?.removeEventListener("message", this.listener);
1708
+ this.channel?.close();
1709
+ };
1710
+ becomeLeader = () => {
1711
+ this.isLeader = true;
1712
+ this.handlers.onLeader();
1713
+ };
1714
+ };
1715
+ //#endregion
1716
+ //#region src/query/planner.ts
1717
+ var isPaginatedLoader = (loader) => Boolean(loader.cursor || loader.limit);
1718
+ /**
1719
+ * How a loader sends a comparison: its own mapping, the db-wide notation for one declared with `true`, or the loader's
1720
+ * adapter notation for any field. `undefined` when it cannot send it.
1721
+ */
1722
+ var getWhereMapping = (loader, node, notation) => {
1723
+ if (node.op === "server") {
1724
+ const declaration = (loader.where?.[node.field])?.[node.name];
1725
+ return typeof declaration === "function" ? declaration : void 0;
1726
+ }
1727
+ const declaration = loader.where?.[node.field]?.[node.op];
1728
+ if (typeof declaration === "function") return declaration;
1729
+ const shared = declaration === true ? notation?.where?.[node.op] : loader.notation?.where?.[node.op];
1730
+ return shared && ((value) => shared(node.field, value));
1731
+ };
1732
+ /** How a loader sends an order, resolved like `getWhereMapping` */
1733
+ var getOrderMapping = (loader, field, notation) => {
1734
+ const declaration = loader.orderBy?.[field];
1735
+ if (typeof declaration === "function") return declaration;
1736
+ const shared = declaration === true ? notation?.orderBy : loader.notation?.orderBy;
1737
+ return shared && ((direction) => shared(field, direction));
1738
+ };
1739
+ /** Whether an expression uses a server-only operator anywhere */
1740
+ var containsServerNode = (node) => {
1741
+ if (node.op === "and" || node.op === "or") return node.items.some(containsServerNode);
1742
+ if (node.op === "not") return containsServerNode(node.item);
1743
+ return node.op === "server";
1744
+ };
1745
+ /** Whether a loader can send a condition. `and`, `or` and `not` run on the client. */
1746
+ var canSend = (loader, node, notation) => {
1747
+ if (node.op === "and" || node.op === "or" || node.op === "not") return false;
1748
+ return Boolean(getWhereMapping(loader, node, notation));
1749
+ };
1750
+ var canSendOrder = (loader, field, notation) => Boolean(getOrderMapping(loader, field, notation));
1751
+ /** Builds the id of the loaded subset that serves a plan, shared by every query with the same backend request */
1752
+ var getSubsetId = (collectionName, plan, definition) => {
1753
+ const sent = plan.sent.map((node) => stableStringify(node)).toSorted();
1754
+ return stableStringify([
1755
+ collectionName,
1756
+ plan.loaderIndex,
1757
+ sent,
1758
+ plan.sendOrder ? definition.orderBy : null,
1759
+ plan.sendLimit ? definition.limit : null
1760
+ ]);
1761
+ };
1762
+ /**
1763
+ * Picks how the db serves a query. Among the list loaders whose required filters the query sets, it picks the one that
1764
+ * can send the most of the query's top-level conditions; ties go to the loader declared first. A paginated loader is a
1765
+ * candidate only when it can send every condition and order, because filtering one page on the client is wrong.
1766
+ */
1767
+ var planQuery = ({ collectionName, config, definition, notation }) => {
1768
+ if (definition.one) {
1769
+ const index = config.loaders.findIndex((loader) => loader.kind === "byKeys");
1770
+ const byKey = config.loaders.findIndex((loader) => loader.kind === "byKey");
1771
+ const loaderIndex = index === -1 ? byKey : index;
1772
+ const usable = !definition.local && loaderIndex !== -1;
1773
+ return {
1774
+ kind: "one",
1775
+ key: definition.one.key,
1776
+ loaderIndex: usable ? loaderIndex : void 0
1777
+ };
1778
+ }
1779
+ if (definition.local) {
1780
+ if (definition.where && containsServerNode(definition.where)) return {
1781
+ kind: "error",
1782
+ error: /* @__PURE__ */ new Error("A local query cannot use a server-only operator")
1783
+ };
1784
+ return { kind: "local" };
1785
+ }
1786
+ const conditions = splitAnd(definition.where);
1787
+ const eqFields = new Set(conditions.filter((node) => node.op === "eq").map((node) => node.field));
1788
+ let best;
1789
+ config.loaders.forEach((loader, loaderIndex) => {
1790
+ if (loader.kind !== "list") return;
1791
+ if (!Object.keys(loader.where ?? {}).filter((field) => loader.where?.[field]?.required).every((field) => eqFields.has(field))) return;
1792
+ const sent = conditions.filter((node) => canSend(loader, node, notation));
1793
+ const local = conditions.filter((node) => !canSend(loader, node, notation));
1794
+ const ordersSendable = definition.orderBy.every((order) => canSendOrder(loader, order.field, notation));
1795
+ const paginated = isPaginatedLoader(loader);
1796
+ if (paginated && (local.length > 0 || !ordersSendable)) return;
1797
+ if (local.some((node) => containsServerNode(node))) return;
1798
+ if (best && best.sent.length >= sent.length) return;
1799
+ const serverOnly = new Set(loader.serverOnly);
1800
+ const readFields = [...conditions.flatMap((node) => getExpressionFields(node)), ...definition.orderBy.map((order) => order.field)];
1801
+ best = {
1802
+ kind: "list",
1803
+ loaderIndex,
1804
+ sent,
1805
+ local,
1806
+ sendOrder: ordersSendable && definition.orderBy.length > 0,
1807
+ sendLimit: Boolean(loader.limit && definition.limit !== void 0),
1808
+ paginated,
1809
+ serverOnly: readFields.some((field) => serverOnly.has(field)) || sent.some((node) => node.op === "server")
1810
+ };
1811
+ });
1812
+ if (!best) return {
1813
+ kind: "error",
1814
+ error: /* @__PURE__ */ new Error(`No loader of "${collectionName}" can serve this query. Set its required filters.`)
1815
+ };
1816
+ return {
1817
+ ...best,
1818
+ subsetId: getSubsetId(collectionName, best, definition)
1819
+ };
1820
+ };
1821
+ //#endregion
1822
+ //#region src/query/live-query.ts
1823
+ var isSameState = (left, right) => {
1824
+ return left.data === right.data && left.status === right.status && left.error === right.error && left.stale === right.stale && left.isFetching === right.isFetching && left.hasNextPage === right.hasNextPage;
1825
+ };
1826
+ var EMPTY_ROWS = [];
1827
+ /** Joined values are the same row, or arrays of the same rows */
1828
+ var sameJoined = (left, right) => {
1829
+ if (Array.isArray(left) && Array.isArray(right)) return left.length === right.length && left.every((item, index) => item === right[index]);
1830
+ return left === right;
1831
+ };
1832
+ var sameItems = (left, right) => {
1833
+ return Array.isArray(left) && left.length === right.length && left.every((item, index) => Object.is(item, right[index]));
1834
+ };
1835
+ /**
1836
+ * The running form of a query: it attaches to the loaded subset that serves it, keeps its result current as rows
1837
+ * change and tells its subscribers. Queries with the same definition share one live query.
1838
+ */
1839
+ var LiveQuery = class {
1840
+ plan;
1841
+ listeners = /* @__PURE__ */ new Set();
1842
+ source;
1843
+ keySubset;
1844
+ answeredLocally = false;
1845
+ /** The subset a query that nothing subscribes to reads, see `getSource` */
1846
+ peeked;
1847
+ sorted = [];
1848
+ members = /* @__PURE__ */ new Set();
1849
+ selections = /* @__PURE__ */ new Map();
1850
+ /** Key subsets that load the joined rows, by `collection:key` */
1851
+ joinSubsets = /* @__PURE__ */ new Map();
1852
+ /** Live queries that load the rows of one-to-many joins, by join name */
1853
+ joinQueries = /* @__PURE__ */ new Map();
1854
+ /** The rows of each one-to-many join by the value of its `on` field, built when first read */
1855
+ childIndex = /* @__PURE__ */ new Map();
1856
+ state = {
1857
+ data: void 0,
1858
+ status: "loading",
1859
+ error: null,
1860
+ stale: false,
1861
+ isFetching: false,
1862
+ hasNextPage: false
1863
+ };
1864
+ constructor(collection, definition, key) {
1865
+ this.collection = collection;
1866
+ this.definition = definition;
1867
+ this.key = key;
1868
+ this.plan = planQuery({
1869
+ collectionName: collection.name,
1870
+ config: collection.config,
1871
+ definition,
1872
+ notation: collection.db.notation
1873
+ });
1874
+ this.state = this.computeState();
1875
+ }
1876
+ /** The current state. A query nobody subscribes to is computed from the rows the db holds right now. */
1877
+ getState = () => {
1878
+ if (!this.isActive()) this.rebuild();
1879
+ return this.state;
1880
+ };
1881
+ subscribe = (listener) => {
1882
+ this.listeners.add(listener);
1883
+ if (this.listeners.size === 1) this.attach();
1884
+ return () => {
1885
+ this.listeners.delete(listener);
1886
+ if (this.listeners.size === 0) this.detach();
1887
+ };
1888
+ };
1889
+ /** Whether anything subscribes to the query */
1890
+ isActive = () => this.listeners.size > 0;
1891
+ /** How many listeners subscribe to the query */
1892
+ get subscriberCount() {
1893
+ return this.listeners.size;
1894
+ }
1895
+ refetch = () => {
1896
+ return (this.source ?? this.keySubset)?.load() ?? Promise.resolve();
1897
+ };
1898
+ /** How the query's loader pages: by cursor, by a growing `limit`, or not at all */
1899
+ getPaging = () => {
1900
+ if (this.plan.kind !== "list") return "none";
1901
+ const loader = this.collection.config.loaders[this.plan.loaderIndex];
1902
+ if (loader.cursor) return "cursor";
1903
+ return loader.limit ? "limit" : "none";
1904
+ };
1905
+ fetchNextPage = () => {
1906
+ return this.source?.loadNext() ?? Promise.resolve();
1907
+ };
1908
+ /** Refetches the query's subset when it is stale, after focus or reconnect */
1909
+ revalidate = () => {
1910
+ (this.source ?? this.keySubset)?.revalidate();
1911
+ };
1912
+ explain = () => {
1913
+ const { plan } = this;
1914
+ const syncs = ((this.source ?? this.keySubset)?.subscriptions ?? []).map((subscription) => ({
1915
+ type: subscription.sync.type,
1916
+ topic: subscription.listener.topic
1917
+ }));
1918
+ if (plan.kind === "error") return {
1919
+ kind: "error",
1920
+ sent: [],
1921
+ local: [],
1922
+ answeredLocally: false,
1923
+ syncs,
1924
+ error: plan.error
1925
+ };
1926
+ if (plan.kind === "local") return {
1927
+ kind: "local",
1928
+ sent: [],
1929
+ local: this.definition.where ? [this.definition.where] : [],
1930
+ answeredLocally: true,
1931
+ syncs
1932
+ };
1933
+ if (plan.kind === "one") return {
1934
+ kind: "one",
1935
+ loader: plan.loaderIndex,
1936
+ sent: [],
1937
+ local: [],
1938
+ answeredLocally: plan.loaderIndex === void 0,
1939
+ syncs
1940
+ };
1941
+ const container = this.source ? void 0 : this.collection.findContainingSubset(plan);
1942
+ const answeredLocally = this.source ? this.answeredLocally : Boolean(container && container.id !== plan.subsetId);
1943
+ return {
1944
+ kind: "list",
1945
+ loader: plan.loaderIndex,
1946
+ sent: plan.sent,
1947
+ local: plan.local,
1948
+ answeredLocally,
1949
+ syncs
1950
+ };
1951
+ };
1952
+ /** Rows changed: update membership and order of just those rows */
1953
+ onRowsChanged = (keys) => {
1954
+ if (this.plan.kind === "error" || !this.isActive()) return;
1955
+ const touched = [...keys].filter((key) => this.members.has(key) || this.isMember(key));
1956
+ if (touched.length === 0) return;
1957
+ const compare = this.getComparator();
1958
+ touched.forEach((key) => {
1959
+ if (this.members.has(key)) {
1960
+ this.sorted.splice(this.sorted.indexOf(key), 1);
1961
+ this.members.delete(key);
1962
+ }
1963
+ if (this.isMember(key)) this.insertSorted(key, compare);
1964
+ });
1965
+ this.syncJoins();
1966
+ this.emit();
1967
+ };
1968
+ /** The subset's rows or status changed */
1969
+ onSubsetChange = () => {
1970
+ this.collection.db.markQueryDirty(this);
1971
+ };
1972
+ /** Recomputes the whole result */
1973
+ rebuild = () => {
1974
+ this.childIndex.clear();
1975
+ this.peeked = this.peekSource();
1976
+ const readable = this.plan.kind !== "list" || this.getSource() !== void 0;
1977
+ if (this.plan.kind !== "error") {
1978
+ const compare = this.getComparator();
1979
+ this.members = new Set(readable ? this.collection.store.keys().filter((key) => this.isMember(key)) : []);
1980
+ this.sorted = [...this.members].toSorted(compare);
1981
+ }
1982
+ if (this.isActive()) this.syncJoins();
1983
+ this.emit();
1984
+ };
1985
+ attach = () => {
1986
+ const { plan, collection } = this;
1987
+ if (plan.kind === "one") {
1988
+ if (plan.loaderIndex !== void 0) {
1989
+ this.keySubset = collection.getKeySubset(collection.resolveKey(plan.key), plan.loaderIndex);
1990
+ this.keySubset.attach(this);
1991
+ if (!collection.store.get(collection.resolveKey(plan.key)) || !this.keySubset.isFresh()) this.keySubset.revalidate();
1992
+ }
1993
+ } else if (plan.kind === "list") {
1994
+ const container = collection.findContainingSubset(plan);
1995
+ this.answeredLocally = Boolean(container && container.id !== plan.subsetId);
1996
+ this.source = this.answeredLocally ? container : collection.getListSubset(plan, this.definition);
1997
+ this.source.attach(this);
1998
+ if (!this.answeredLocally) this.source.revalidate();
1999
+ }
2000
+ this.rebuild();
2001
+ };
2002
+ detach = () => {
2003
+ this.collection.db.releaseLater(this);
2004
+ this.source?.detach(this);
2005
+ this.keySubset?.detach(this);
2006
+ this.joinSubsets.forEach((subset) => subset.detach(this));
2007
+ this.joinSubsets.clear();
2008
+ this.joinQueries.forEach((entry) => entry.unsubscribe());
2009
+ this.joinQueries.clear();
2010
+ this.source = void 0;
2011
+ this.keySubset = void 0;
2012
+ this.answeredLocally = false;
2013
+ this.members.clear();
2014
+ this.sorted = [];
2015
+ this.selections.clear();
2016
+ };
2017
+ getComparator = () => this.collection.createComparator(this.definition.orderBy, this.getSource());
2018
+ insertSorted = (key, compare) => {
2019
+ let low = 0;
2020
+ let high = this.sorted.length;
2021
+ while (low < high) {
2022
+ const middle = low + high >>> 1;
2023
+ if (compare(this.sorted[middle], key) <= 0) low = middle + 1;
2024
+ else high = middle;
2025
+ }
2026
+ this.sorted.splice(low, 0, key);
2027
+ this.members.add(key);
2028
+ };
2029
+ isMember = (key) => {
2030
+ const { plan, collection, definition } = this;
2031
+ const row = collection.store.get(key);
2032
+ if (!row) return false;
2033
+ if (plan.kind === "one") return key === collection.resolveKey(plan.key);
2034
+ if (definition.where && !evaluate(definition.where, row)) return false;
2035
+ if (plan.kind === "local") return true;
2036
+ const source = this.getSource();
2037
+ const fixed = collection.config.loaders[plan.loaderIndex].fixed ?? {};
2038
+ if (!Object.keys(fixed).every((field) => evaluate({
2039
+ op: "eq",
2040
+ field,
2041
+ value: fixed[field]
2042
+ }, row))) return false;
2043
+ if (source.ownsOnly) return source.holds(key);
2044
+ return !source.excluded.has(key);
2045
+ };
2046
+ /** The joined value of a row: the row with that key, or every row whose `on` field holds the value */
2047
+ resolveJoin = (join, row) => {
2048
+ const value = row[join.field];
2049
+ if (!join.on) return this.collection.db.collections.get(join.collection).store.get(value);
2050
+ return this.getChildren(join).get(value) ?? EMPTY_ROWS;
2051
+ };
2052
+ getChildren = (join) => {
2053
+ const existing = this.childIndex.get(join.name);
2054
+ if (existing) return existing;
2055
+ const { store } = this.collection.db.collections.get(join.collection);
2056
+ const index = /* @__PURE__ */ new Map();
2057
+ store.keys().forEach((childKey) => {
2058
+ const child = store.get(childKey);
2059
+ const value = child[join.on];
2060
+ index.set(value, [...index.get(value) ?? [], child]);
2061
+ });
2062
+ this.childIndex.set(join.name, index);
2063
+ return index;
2064
+ };
2065
+ hasInnerJoins = () => (this.definition.joins ?? []).some((join) => join.type === "inner");
2066
+ /** Whether a row has every row its inner joins need */
2067
+ passesInnerJoins = (key) => {
2068
+ const row = this.collection.store.get(key);
2069
+ return (this.definition.joins ?? []).every((join) => {
2070
+ if (join.type !== "inner") return true;
2071
+ const joined = this.resolveJoin(join, row);
2072
+ return Array.isArray(joined) ? joined.length > 0 : joined !== void 0;
2073
+ });
2074
+ };
2075
+ select = (key) => {
2076
+ const row = this.collection.store.get(key);
2077
+ const joins = this.definition.joins ?? [];
2078
+ const joined = joins.map((join) => this.resolveJoin(join, row));
2079
+ const cached = this.selections.get(key);
2080
+ const sameJoins = Boolean(cached?.joined.every((item, index) => sameJoined(item, joined[index])));
2081
+ if (cached && cached.row === row && sameJoins) return cached.value;
2082
+ const { select } = this.definition;
2083
+ if (cached && select && sameJoins && Object.values(select).every((field) => Object.is(cached.row[field], row[field]))) {
2084
+ this.selections.set(key, {
2085
+ ...cached,
2086
+ row
2087
+ });
2088
+ return cached.value;
2089
+ }
2090
+ const selected = select ? Object.fromEntries(Object.entries(select).map(([output, field]) => [output, row[field]])) : row;
2091
+ const value = joins.length > 0 ? {
2092
+ ...selected,
2093
+ ...Object.fromEntries(joins.map(({ name }, index) => [name, joined[index]]))
2094
+ } : selected;
2095
+ this.selections.set(key, {
2096
+ row,
2097
+ joined,
2098
+ value
2099
+ });
2100
+ return value;
2101
+ };
2102
+ /** Whether the query reads rows of a collection, its own or a joined one */
2103
+ dependsOn = (collection) => {
2104
+ return (this.definition.joins ?? []).some((join) => join.collection === collection.name);
2105
+ };
2106
+ /** Rows of a joined collection changed: results that point at them select again */
2107
+ onJoinedRowsChanged = () => {
2108
+ this.childIndex.clear();
2109
+ this.syncJoins();
2110
+ this.emit();
2111
+ };
2112
+ /** Attaches the key subsets that load the joined rows of the current result and releases the others */
2113
+ syncJoins = () => {
2114
+ const needed = /* @__PURE__ */ new Map();
2115
+ const joins = this.definition.local ? [] : this.definition.joins ?? [];
2116
+ this.syncChildQueries(joins.filter((join) => join.on));
2117
+ joins.filter((join) => !join.on).forEach(({ collection: name, field }) => {
2118
+ const collection = this.collection.db.collections.get(name);
2119
+ this.members.forEach((member) => {
2120
+ const key = this.collection.store.get(member)[field];
2121
+ if (key !== null && key !== void 0) needed.set(`${name}:${String(key)}`, {
2122
+ collection,
2123
+ key
2124
+ });
2125
+ });
2126
+ });
2127
+ this.joinSubsets.forEach((subset, id) => {
2128
+ if (!needed.has(id)) {
2129
+ subset.detach(this);
2130
+ this.joinSubsets.delete(id);
2131
+ }
2132
+ });
2133
+ needed.forEach(({ collection, key }, id) => {
2134
+ const loaderIndex = collection.config.loaders.findIndex((loader) => loader.kind !== "list");
2135
+ if (this.joinSubsets.has(id) || loaderIndex === -1) return;
2136
+ const subset = collection.getKeySubset(key, loaderIndex);
2137
+ subset.attach(this);
2138
+ subset.revalidate();
2139
+ this.joinSubsets.set(id, subset);
2140
+ });
2141
+ };
2142
+ /**
2143
+ * Loads the rows of one-to-many joins: one query of the joined collection for the values of the whole result, when
2144
+ * one of its list loaders can send `inArray` on the joined field. Otherwise the join reads the rows the db holds.
2145
+ */
2146
+ syncChildQueries = (joins) => {
2147
+ joins.forEach((join) => {
2148
+ const values = [...new Set([...this.members].map((member) => this.collection.store.get(member)[join.field]).filter((value) => value !== null && value !== void 0))].toSorted();
2149
+ const definition = {
2150
+ collection: join.collection,
2151
+ where: {
2152
+ op: "inArray",
2153
+ field: join.on,
2154
+ value: values
2155
+ },
2156
+ orderBy: [],
2157
+ local: false
2158
+ };
2159
+ const query = this.collection.db.getLiveQuery(definition);
2160
+ const current = this.joinQueries.get(join.name);
2161
+ if (current?.key === query.key) return;
2162
+ current?.unsubscribe();
2163
+ this.joinQueries.delete(join.name);
2164
+ const sendsValues = query.plan.kind === "list" && query.plan.sent.some((node) => node.op === "inArray" && node.field === join.on);
2165
+ if (values.length > 0 && sendsValues) this.joinQueries.set(join.name, {
2166
+ key: query.key,
2167
+ unsubscribe: query.subscribe(() => {})
2168
+ });
2169
+ });
2170
+ };
2171
+ buildList = () => {
2172
+ const { plan, definition } = this;
2173
+ const paginated = plan.kind === "list" && plan.paginated;
2174
+ const included = this.hasInnerJoins() ? this.sorted.filter(this.passesInnerJoins) : this.sorted;
2175
+ const items = (definition.limit !== void 0 && !paginated ? included.slice(0, definition.limit) : included).map((key) => this.select(key));
2176
+ [...this.selections.keys()].forEach((key) => {
2177
+ if (!this.members.has(key)) this.selections.delete(key);
2178
+ });
2179
+ return sameItems(this.state.data, items) ? this.state.data : items;
2180
+ };
2181
+ computeState = () => {
2182
+ const { plan, collection } = this;
2183
+ const { db } = collection;
2184
+ const base = {
2185
+ error: null,
2186
+ stale: false,
2187
+ isFetching: false,
2188
+ hasNextPage: false
2189
+ };
2190
+ if (plan.kind === "error") return {
2191
+ ...base,
2192
+ data: void 0,
2193
+ status: "error",
2194
+ error: plan.error
2195
+ };
2196
+ if (!db.isReady && !this.getSource()?.hasLoaded && !(plan.kind === "one" && this.members.size > 0)) return {
2197
+ ...base,
2198
+ data: void 0,
2199
+ status: "loading"
2200
+ };
2201
+ if (plan.kind === "local") return {
2202
+ ...base,
2203
+ data: this.buildList(),
2204
+ status: "ready"
2205
+ };
2206
+ if (plan.kind === "one") {
2207
+ const subset = this.keySubset;
2208
+ const key = collection.resolveKey(plan.key);
2209
+ const row = this.members.has(key) && this.passesInnerJoins(key) ? this.select(key) : void 0;
2210
+ let status = "loading";
2211
+ if (row || !subset || subset.hasLoaded) status = "ready";
2212
+ else if (subset.error) status = "error";
2213
+ return {
2214
+ data: row,
2215
+ status,
2216
+ error: subset?.error ?? null,
2217
+ stale: subset ? !subset.isFresh() : false,
2218
+ isFetching: subset?.isLoading ?? false,
2219
+ hasNextPage: false
2220
+ };
2221
+ }
2222
+ const source = this.getSource();
2223
+ if (!source) return {
2224
+ ...base,
2225
+ data: void 0,
2226
+ status: "loading"
2227
+ };
2228
+ let status = "loading";
2229
+ if (source.hasLoaded) status = "ready";
2230
+ else if (source.error) status = "error";
2231
+ return {
2232
+ data: status === "ready" ? this.buildList() : void 0,
2233
+ status,
2234
+ error: source.error,
2235
+ stale: !source.isFresh(),
2236
+ isFetching: source.isLoading,
2237
+ hasNextPage: plan.paginated && source.hasMore
2238
+ };
2239
+ };
2240
+ /**
2241
+ * The subset that serves a list query. Before anything subscribes, such as on a component's first render, it is the
2242
+ * loaded subset that would serve it, read without attaching to it or loading it.
2243
+ */
2244
+ getSource = () => this.source ?? this.peeked;
2245
+ peekSource = () => {
2246
+ const { collection, plan } = this;
2247
+ if (this.source || plan.kind !== "list") return;
2248
+ return collection.findContainingSubset(plan) ?? collection.listSubsets.get(plan.subsetId);
2249
+ };
2250
+ emit = () => {
2251
+ const next = this.computeState();
2252
+ if (isSameState(this.state, next)) return;
2253
+ this.state = next;
2254
+ this.listeners.forEach((listener) => {
2255
+ try {
2256
+ listener();
2257
+ } catch (error) {
2258
+ this.collection.db.emitError({
2259
+ type: "subscriber",
2260
+ error,
2261
+ collection: this.collection.name
2262
+ });
2263
+ }
2264
+ });
2265
+ };
2266
+ };
2267
+ //#endregion
2268
+ //#region src/subset/base-subset.ts
2269
+ var getStaleTime = (loader) => loader.request.staleTime;
2270
+ var BaseSubset = class {
2271
+ hasLoaded = false;
2272
+ isLoading = false;
2273
+ error = null;
2274
+ loadedAt = 0;
2275
+ /** Set when events may have been missed, so only a load makes the subset fresh again */
2276
+ invalidated = false;
2277
+ subscriptions = [];
2278
+ observers = /* @__PURE__ */ new Set();
2279
+ pending;
2280
+ gcTimer;
2281
+ constructor(collection, loader) {
2282
+ this.collection = collection;
2283
+ this.loader = loader;
2284
+ }
2285
+ /** Whether a query is attached */
2286
+ isUsed = () => this.observers.size > 0;
2287
+ /** How many queries read the subset */
2288
+ get observerCount() {
2289
+ return this.observers.size;
2290
+ }
2291
+ attach = (observer) => {
2292
+ if (this.gcTimer) {
2293
+ clearTimeout(this.gcTimer);
2294
+ this.gcTimer = void 0;
2295
+ }
2296
+ this.observers.add(observer);
2297
+ if (this.observers.size === 1 && this.subscriptions.length === 0) this.subscriptions = this.collection.subscribeSyncs(this);
2298
+ };
2299
+ detach = (observer) => {
2300
+ this.observers.delete(observer);
2301
+ if (this.observers.size > 0) return;
2302
+ this.gcTimer = setTimeout(() => this.dispose(), this.collection.db.gcTime);
2303
+ };
2304
+ /**
2305
+ * Moves the subset to the sync subscriptions its values pick now, for example when the row a key subset holds moved
2306
+ * to another team, and leaves the ones it no longer needs.
2307
+ */
2308
+ refreshSyncs = () => {
2309
+ if (!this.isUsed()) return;
2310
+ const next = this.collection.subscribeSyncs(this);
2311
+ this.subscriptions.filter((subscription) => !next.includes(subscription)).forEach((item) => item.removeUser(this));
2312
+ this.subscriptions = next;
2313
+ };
2314
+ /** Stops the garbage collection timer, for `destroy` */
2315
+ cancelGc = () => {
2316
+ clearTimeout(this.gcTimer);
2317
+ this.gcTimer = void 0;
2318
+ };
2319
+ /** Releases the subset: stops its syncs and removes the rows nothing else holds */
2320
+ dispose = () => {
2321
+ this.gcTimer = void 0;
2322
+ this.subscriptions.forEach((subscription) => subscription.removeUser(this));
2323
+ this.subscriptions = [];
2324
+ this.collection.removeSubset(this);
2325
+ };
2326
+ /** Whether syncs deliver every insert, update and delete for the subset */
2327
+ isLive = () => {
2328
+ const types = new Set(this.subscriptions.filter((subscription) => subscription.isLive()).map((item) => item.sync.type));
2329
+ return types.has("changes") || types.has("insert") && types.has("update") && types.has("delete");
2330
+ };
2331
+ isFresh = () => {
2332
+ if (!this.hasLoaded || this.invalidated) return false;
2333
+ if (this.isLive()) return true;
2334
+ return this.loadedAt > 0 && Date.now() - this.loadedAt < getStaleTime(this.loader);
2335
+ };
2336
+ /** Marks the subset stale, for example after a reconnect that may have missed events */
2337
+ invalidate = () => {
2338
+ this.invalidated = true;
2339
+ this.notify();
2340
+ };
2341
+ notify = () => {
2342
+ this.observers.forEach((observer) => observer.onSubsetChange());
2343
+ };
2344
+ /** Whether the load in flight loads the whole subset, rather than its next page */
2345
+ pendingIsFull = true;
2346
+ /** Loads the subset unless a load of the whole subset is in flight. One asked during a next page runs after it. */
2347
+ load = (options = {}) => {
2348
+ if (this.pending && !this.pendingIsFull) return this.pending.then(() => this.load(options));
2349
+ if (!this.pending) {
2350
+ this.pendingIsFull = true;
2351
+ const pending = this.run(options).finally(() => {
2352
+ if (this.pending === pending) this.pending = void 0;
2353
+ });
2354
+ this.pending = pending;
2355
+ }
2356
+ return this.pending;
2357
+ };
2358
+ /** Loads again after the load in flight, so the result is newer than anything sent before */
2359
+ reload = async (options = {}) => {
2360
+ await this.pending;
2361
+ return this.load(options);
2362
+ };
2363
+ /** Refetches when the subset is stale and no load is in flight */
2364
+ revalidate = () => {
2365
+ if (!this.isLoading && !this.isFresh()) this.load();
2366
+ };
2367
+ beginLoad = () => {
2368
+ this.isLoading = true;
2369
+ this.subscriptions.forEach((subscription) => subscription.beginLoad(this));
2370
+ this.notify();
2371
+ };
2372
+ endLoad = () => {
2373
+ this.isLoading = false;
2374
+ this.subscriptions.forEach((subscription) => subscription.endLoad(this));
2375
+ };
2376
+ };
2377
+ //#endregion
2378
+ //#region src/subset/list-subset.ts
2379
+ /**
2380
+ * The rows one list loader returned for one set of sent conditions, order and range. It owns those rows until it is
2381
+ * released, and records which rows a refetch no longer returned.
2382
+ */
2383
+ var ListSubset = class extends BaseSubset {
2384
+ owned = /* @__PURE__ */ new Set();
2385
+ /** Rows that inserts added inside a paginated subset's range */
2386
+ inserted = /* @__PURE__ */ new Set();
2387
+ /** Rows a refetch no longer returned, which another subset still holds */
2388
+ excluded = /* @__PURE__ */ new Set();
2389
+ orderIndex = /* @__PURE__ */ new Map();
2390
+ cursor = void 0;
2391
+ hasMore = false;
2392
+ /** How many pages a paginated subset has loaded, so a refetch reloads all of them */
2393
+ pages = 0;
2394
+ listLoader;
2395
+ plan;
2396
+ definition;
2397
+ constructor(collection, options) {
2398
+ super(collection, options.loader);
2399
+ this.listLoader = options.loader;
2400
+ this.plan = options.plan;
2401
+ this.definition = options.definition;
2402
+ }
2403
+ get id() {
2404
+ return this.plan.subsetId;
2405
+ }
2406
+ /** The values of the subset's sent `eq` conditions, which syncs use to pick their subscription */
2407
+ getEqValues = () => {
2408
+ return Object.fromEntries(this.plan.sent.filter((node) => node.op === "eq").map((node) => [node.field, node.value]));
2409
+ };
2410
+ /** Whether a row matches what the backend was asked for, including the loader's fixed filters */
2411
+ matchesSent = (row) => {
2412
+ const fixed = this.listLoader.fixed ?? {};
2413
+ return Object.keys(fixed).every((field) => evaluate({
2414
+ op: "eq",
2415
+ field,
2416
+ value: fixed[field]
2417
+ }, row)) && this.plan.sent.every((node) => evaluate(node, row));
2418
+ };
2419
+ /** Whether the backend decides membership alone: pages, or a server-only operator the client cannot evaluate */
2420
+ get ownsOnly() {
2421
+ return this.plan.paginated || this.plan.sent.some((node) => node.op === "server");
2422
+ }
2423
+ holds = (key) => {
2424
+ if (this.ownsOnly) return this.owned.has(key) || this.inserted.has(key);
2425
+ if (this.excluded.has(key)) return false;
2426
+ const row = this.collection.store.getServerRow(key);
2427
+ return this.owned.has(key) || Boolean(row && this.matchesSent(row));
2428
+ };
2429
+ /** Adds an inserted row to a paginated subset when it sorts inside the loaded range */
2430
+ noteInsert = (key) => {
2431
+ this.excluded.delete(key);
2432
+ if (!this.plan.paginated) {
2433
+ if (this.ownsOnly && this.hasLoaded) this.invalidate();
2434
+ return;
2435
+ }
2436
+ const row = this.collection.store.get(key);
2437
+ if (!row || !this.matchesSent(row)) return;
2438
+ if (!this.hasMore) {
2439
+ this.inserted.add(key);
2440
+ return;
2441
+ }
2442
+ const compare = this.collection.createComparator(this.definition.orderBy, this);
2443
+ const last = [...this.owned].toSorted(compare).pop();
2444
+ if (last !== void 0 && compare(key, last) < 0) this.inserted.add(key);
2445
+ };
2446
+ /** Loads the page after the last loaded one */
2447
+ loadNext = () => {
2448
+ if (!this.hasMore || this.isLoading) return this.pending ?? Promise.resolve();
2449
+ this.pendingIsFull = false;
2450
+ const pending = this.loadPages(false).finally(() => {
2451
+ if (this.pending === pending) this.pending = void 0;
2452
+ });
2453
+ this.pending = pending;
2454
+ return pending;
2455
+ };
2456
+ run = (options) => this.loadPages(true, options.waitForWrites !== false);
2457
+ buildRequest = (cursor) => {
2458
+ const loader = this.listLoader;
2459
+ const { notation } = this.collection.db;
2460
+ const patches = this.plan.sent.map((node) => getWhereMapping(loader, node, notation)(node.value));
2461
+ if (this.plan.sendOrder) this.definition.orderBy.forEach(({ field, direction }) => {
2462
+ patches.push(getOrderMapping(loader, field, notation)(direction));
2463
+ });
2464
+ if (this.plan.sendLimit) patches.push(loader.limit(this.definition.limit));
2465
+ if (cursor && loader.page) patches.push(loader.page(cursor.value));
2466
+ return applyRequestPatches(loader.request.setCache(false), patches);
2467
+ };
2468
+ /**
2469
+ * Loads from the first page, or the page after the last loaded one. A paginated subset is a prefix of its result, so
2470
+ * loading from the first page reloads every page loaded so far, in order, and then releases the rows none of them
2471
+ * returned. The rows stay until the last page is back, so the list does not jump while it reloads.
2472
+ */
2473
+ loadPages = async (fromStart, waitForWrites = true) => {
2474
+ const { db } = this.collection;
2475
+ const { generation } = db;
2476
+ this.beginLoad();
2477
+ const timeout = this.startNetworkTimeout();
2478
+ const returned = fromStart ? [] : [...this.orderIndex.keys()];
2479
+ let loadSeq = 0;
2480
+ let result;
2481
+ try {
2482
+ await db.ready;
2483
+ if (waitForWrites) await this.collection.mutationsSettled();
2484
+ loadSeq = db.tick();
2485
+ result = await this.fetchPages({
2486
+ cursor: fromStart ? void 0 : { value: this.cursor },
2487
+ remaining: fromStart ? Math.max(1, this.pages) : 1,
2488
+ returned,
2489
+ timeout,
2490
+ generation
2491
+ });
2492
+ } catch (error) {
2493
+ clearTimeout(timeout);
2494
+ result = {
2495
+ success: false,
2496
+ error
2497
+ };
2498
+ db.emitError({
2499
+ type: "load",
2500
+ error,
2501
+ collection: this.collection.name
2502
+ });
2503
+ }
2504
+ if (db.generation !== generation) {
2505
+ db.batch(() => {
2506
+ this.endLoad();
2507
+ this.collection.markSubsetChanged(this);
2508
+ });
2509
+ return;
2510
+ }
2511
+ if (!result.success) {
2512
+ const { error } = result;
2513
+ db.batch(() => {
2514
+ this.error = error;
2515
+ this.endLoad();
2516
+ this.collection.markSubsetChanged(this);
2517
+ });
2518
+ return;
2519
+ }
2520
+ const { cursor, loaded } = result;
2521
+ db.batch(() => {
2522
+ if (fromStart) this.release(returned, loadSeq);
2523
+ this.orderIndex.clear();
2524
+ returned.forEach((key, index) => this.orderIndex.set(key, index));
2525
+ this.cursor = cursor;
2526
+ this.hasMore = cursor !== void 0 && cursor !== null;
2527
+ this.pages = (fromStart ? 0 : this.pages) + loaded;
2528
+ this.hasLoaded = true;
2529
+ this.loadedAt = Date.now();
2530
+ this.invalidated = false;
2531
+ this.error = null;
2532
+ this.endLoad();
2533
+ this.collection.markSubsetChanged(this);
2534
+ });
2535
+ };
2536
+ /** Loads pages one after another, each with the cursor the previous one returned, until `remaining` are loaded */
2537
+ fetchPages = async (options) => {
2538
+ const result = await this.fetchPage(options.cursor, options.returned, options.generation);
2539
+ clearTimeout(options.timeout);
2540
+ if (!result.success) return result;
2541
+ if (!(result.next !== void 0 && result.next !== null) || options.remaining <= 1) return {
2542
+ success: true,
2543
+ cursor: result.next,
2544
+ loaded: 1
2545
+ };
2546
+ const rest = await this.fetchPages({
2547
+ ...options,
2548
+ cursor: { value: result.next },
2549
+ remaining: options.remaining - 1
2550
+ });
2551
+ return rest.success ? {
2552
+ ...rest,
2553
+ loaded: rest.loaded + 1
2554
+ } : rest;
2555
+ };
2556
+ /** Sends one page's request and writes its rows, adding their keys to `returned` in order */
2557
+ fetchPage = async (cursor, returned, generation) => {
2558
+ const { db } = this.collection;
2559
+ const seq = db.tick();
2560
+ const wall = Date.now();
2561
+ db.trackRequest(seq);
2562
+ try {
2563
+ const response = await this.buildRequest(cursor).send();
2564
+ if (!response.success) return {
2565
+ success: false,
2566
+ error: response.error ?? response
2567
+ };
2568
+ const items = this.collection.readItems(this.listLoader, response.data);
2569
+ const next = this.listLoader.cursor?.(response.data);
2570
+ const rows = await this.collection.prepareServerRows(items);
2571
+ if (db.generation !== generation) return {
2572
+ success: false,
2573
+ error: /* @__PURE__ */ new Error("Cleared")
2574
+ };
2575
+ db.batch(() => {
2576
+ const keys = this.collection.writeServerRows(rows, true, {
2577
+ kind: "sent",
2578
+ seq,
2579
+ wall
2580
+ });
2581
+ keys.forEach((key) => {
2582
+ this.owned.add(key);
2583
+ this.excluded.delete(key);
2584
+ if (!this.orderIndex.has(key)) this.orderIndex.set(key, this.orderIndex.size);
2585
+ });
2586
+ returned.push(...keys);
2587
+ this.collection.markSubsetChanged(this);
2588
+ });
2589
+ return {
2590
+ success: true,
2591
+ next
2592
+ };
2593
+ } finally {
2594
+ db.settleRequest(seq);
2595
+ }
2596
+ };
2597
+ /**
2598
+ * Releases rows a complete reload no longer returned: rows it owned, rows inserts had added to its pages, and rows
2599
+ * nothing else holds that match what it sent, such as a confirmed insert someone else deleted since. The server
2600
+ * answered for its conditions, so such a row is not in them.
2601
+ */
2602
+ release = (returned, loadSeq) => {
2603
+ const returnedKeys = new Set(returned);
2604
+ const { store } = this.collection;
2605
+ const isNewer = (key) => store.getLastSeq(key) > loadSeq;
2606
+ this.inserted.forEach((key) => {
2607
+ this.inserted.delete(key);
2608
+ if (!returnedKeys.has(key)) this.owned.add(key);
2609
+ });
2610
+ if (!this.ownsOnly) this.collection.store.getServerKeys().forEach((key) => {
2611
+ const row = this.collection.store.getServerRow(key);
2612
+ const unheld = !this.collection.isHeldByOthers(key, this);
2613
+ if (!returnedKeys.has(key) && !isNewer(key) && this.matchesSent(row) && unheld) this.collection.store.drop(key);
2614
+ });
2615
+ this.owned.forEach((key) => {
2616
+ if (returnedKeys.has(key) || isNewer(key)) return;
2617
+ this.owned.delete(key);
2618
+ if (this.collection.isHeldByOthers(key, this)) this.excluded.add(key);
2619
+ else this.collection.store.drop(key);
2620
+ });
2621
+ };
2622
+ /** With persistence, a subset that restored no rows shows an empty result once the network took too long */
2623
+ startNetworkTimeout = () => {
2624
+ const { persistence } = this.collection.db;
2625
+ if (!persistence || this.hasLoaded) return;
2626
+ return setTimeout(() => {
2627
+ if (this.hasLoaded) return;
2628
+ this.hasLoaded = true;
2629
+ this.loadedAt = 0;
2630
+ this.invalidated = true;
2631
+ this.notify();
2632
+ }, persistence.networkTimeout);
2633
+ };
2634
+ };
2635
+ //#endregion
2636
+ //#region src/store/store.ts
2637
+ /**
2638
+ * Holds one collection's rows. Server rows and optimistic layers are kept apart: queries read the server row with
2639
+ * every pending layer applied on top, and dropping a layer reverts exactly what it changed.
2640
+ *
2641
+ * Writes are ordered per field. A field keeps its value when the write is older than the one that set it: an older
2642
+ * `version`, or a response to a request sent before the field was written.
2643
+ */
2644
+ var Store = class {
2645
+ rows = /* @__PURE__ */ new Map();
2646
+ meta = /* @__PURE__ */ new Map();
2647
+ tombstones = /* @__PURE__ */ new Map();
2648
+ layers = [];
2649
+ visible = /* @__PURE__ */ new Map();
2650
+ arrival = /* @__PURE__ */ new Map();
2651
+ arrivalCounter = 0;
2652
+ /** Stores of linked collections, which hold some of this store's fields for the same keys */
2653
+ links = [];
2654
+ constructor(options) {
2655
+ this.options = options;
2656
+ }
2657
+ /** Whether the server state holds the row */
2658
+ hasServerRow = (key) => this.rows.has(key);
2659
+ /** The pending optimistic layers, oldest first */
2660
+ getLayers = () => this.layers;
2661
+ /** The server row, without optimistic layers */
2662
+ getServerRow = (key) => this.rows.get(key);
2663
+ /** The newest `seq` that wrote any field of a server row, or 0 */
2664
+ getLastSeq = (key) => {
2665
+ const fields = this.meta.get(key);
2666
+ return fields ? Math.max(0, ...[...fields.values()].map((meta) => meta.seq)) : 0;
2667
+ };
2668
+ /** Every key with a server row */
2669
+ getServerKeys = () => [...this.rows.keys()];
2670
+ /** The row as queries see it: the server row with every pending layer applied */
2671
+ get = (key) => {
2672
+ if (this.visible.has(key)) return this.visible.get(key);
2673
+ let row = this.rows.get(key);
2674
+ for (const layer of this.layers) {
2675
+ if (layer.key !== key) continue;
2676
+ if (layer.type === "insert") row = { ...layer.values };
2677
+ else if (layer.type === "update") row = row ? {
2678
+ ...row,
2679
+ ...layer.values
2680
+ } : void 0;
2681
+ else row = void 0;
2682
+ }
2683
+ const visible = row && row !== this.rows.get(key) ? Object.freeze(row) : row;
2684
+ this.visible.set(key, visible);
2685
+ return visible;
2686
+ };
2687
+ /** Every key queries can see */
2688
+ keys = () => {
2689
+ const keys = new Set(this.rows.keys());
2690
+ this.layers.forEach((layer) => keys.add(layer.key));
2691
+ return [...keys].filter((key) => this.get(key) !== void 0);
2692
+ };
2693
+ /** The order in which the db first saw a row, used when a query has no `orderBy` */
2694
+ getArrival = (key) => this.arrival.get(key);
2695
+ /** Whether a pending write touches the row */
2696
+ hasLayer = (key) => this.layers.some((layer) => layer.key === key);
2697
+ /**
2698
+ * Writes server fields. A complete write creates the row or replaces its fields, a partial write changes only the
2699
+ * fields it carries and is ignored for a row the store does not hold. Returns whether the row changed.
2700
+ */
2701
+ /** Links another store: writes, deletes and layers on one change the fields the other has, for the same key */
2702
+ link = (store) => {
2703
+ this.links.push(store);
2704
+ };
2705
+ write = (key, written, { complete, stamp, linked = true }) => {
2706
+ const values = Object.fromEntries(Object.entries(written).filter(([, value]) => value !== void 0));
2707
+ const tombstone = this.tombstones.get(key);
2708
+ if (tombstone) {
2709
+ if (stamp.seq < tombstone.seq) return false;
2710
+ this.tombstones.delete(key);
2711
+ }
2712
+ const current = this.rows.get(key);
2713
+ if (!current && !complete) return false;
2714
+ const fieldsMeta = this.meta.get(key) ?? /* @__PURE__ */ new Map();
2715
+ const { versionField } = this.options;
2716
+ const incomingVersion = versionField ? values[versionField] : void 0;
2717
+ const hasVersion = incomingVersion !== void 0;
2718
+ const next = current ? { ...current } : {};
2719
+ const accepted = {};
2720
+ let changed = !current;
2721
+ Object.keys(values).forEach((field) => {
2722
+ const meta = fieldsMeta.get(field);
2723
+ if (!this.accepts(meta, stamp, hasVersion ? incomingVersion : void 0)) return;
2724
+ fieldsMeta.set(field, {
2725
+ seq: stamp.seq,
2726
+ wall: stamp.wall,
2727
+ version: hasVersion ? incomingVersion : meta?.version
2728
+ });
2729
+ accepted[field] = values[field];
2730
+ if (!current || !isEqualValue(current[field], values[field])) {
2731
+ next[field] = values[field];
2732
+ changed = true;
2733
+ }
2734
+ });
2735
+ if (complete && current) Object.keys(current).forEach((field) => {
2736
+ if (field in values || !this.accepts(fieldsMeta.get(field), stamp, hasVersion ? incomingVersion : void 0)) return;
2737
+ fieldsMeta.set(field, {
2738
+ seq: stamp.seq,
2739
+ wall: stamp.wall,
2740
+ version: hasVersion ? incomingVersion : void 0
2741
+ });
2742
+ delete next[field];
2743
+ changed = true;
2744
+ });
2745
+ this.meta.set(key, fieldsMeta);
2746
+ if (!this.arrival.has(key)) {
2747
+ this.arrivalCounter += 1;
2748
+ this.arrival.set(key, this.arrivalCounter);
2749
+ }
2750
+ if (changed) {
2751
+ this.rows.set(key, Object.freeze(next));
2752
+ this.invalidate(key);
2753
+ }
2754
+ if (linked) this.links.forEach((store) => store.mirrorWrite(key, accepted, stamp));
2755
+ return changed;
2756
+ };
2757
+ /** Removes a row the server deleted, and remembers the key so an older response cannot bring it back */
2758
+ remove = (key, stamp, linked = true) => {
2759
+ const tombstone = this.tombstones.get(key);
2760
+ if (!tombstone || tombstone.seq < stamp.seq) this.tombstones.set(key, {
2761
+ seq: stamp.seq,
2762
+ wall: stamp.wall
2763
+ });
2764
+ if (linked) this.links.forEach((store) => store.remove(key, stamp, false));
2765
+ if (this.getLastSeq(key) > stamp.seq) return false;
2766
+ return this.drop(key);
2767
+ };
2768
+ /** Removes a row without remembering it, for rows no subset holds any more */
2769
+ drop = (key) => {
2770
+ if (!this.rows.has(key)) return false;
2771
+ this.rows.delete(key);
2772
+ this.meta.delete(key);
2773
+ this.invalidate(key);
2774
+ return true;
2775
+ };
2776
+ /** Forgets deleted keys once every request sent before the delete has settled */
2777
+ forgetTombstones = (oldestPendingSeq) => {
2778
+ this.tombstones.forEach((tombstone, key) => {
2779
+ if (tombstone.seq < oldestPendingSeq) this.tombstones.delete(key);
2780
+ });
2781
+ };
2782
+ addLayer = (layer, linked = true) => {
2783
+ if (linked) this.links.forEach((store) => store.mirrorLayer(layer));
2784
+ this.layers.push(layer);
2785
+ if (!this.arrival.has(layer.key)) {
2786
+ this.arrivalCounter += 1;
2787
+ this.arrival.set(layer.key, this.arrivalCounter);
2788
+ }
2789
+ this.invalidate(layer.key);
2790
+ };
2791
+ removeLayer = (id, linked = true) => {
2792
+ if (linked) this.links.forEach((store) => store.removeLayer(`${id}@link`, false));
2793
+ const layer = this.layers.find((item) => item.id === id);
2794
+ if (!layer) return;
2795
+ this.layers = this.layers.filter((item) => item.id !== id);
2796
+ this.invalidate(layer.key);
2797
+ };
2798
+ /** Moves the pending layers of a temporary key to the key the server assigned */
2799
+ rekeyLayers = (from, to) => {
2800
+ if (this.arrival.has(from)) this.arrival.set(to, this.arrival.get(from));
2801
+ this.layers = this.layers.map((layer) => {
2802
+ if (layer.key !== from) return layer;
2803
+ return {
2804
+ ...layer,
2805
+ key: to,
2806
+ values: {
2807
+ ...layer.values,
2808
+ [this.options.keyField]: to
2809
+ }
2810
+ };
2811
+ });
2812
+ this.invalidate(from);
2813
+ this.invalidate(to);
2814
+ };
2815
+ /** Removes every row, layer and tombstone */
2816
+ clear = () => {
2817
+ const keys = new Set([...this.rows.keys(), ...this.layers.map((layer) => layer.key)]);
2818
+ this.rows.clear();
2819
+ this.meta.clear();
2820
+ this.tombstones.clear();
2821
+ this.layers = [];
2822
+ keys.forEach((key) => this.invalidate(key));
2823
+ };
2824
+ /** The fields a linked store wrote, limited to the fields this store's row has. Rows it does not hold stay away. */
2825
+ /** The fields of a row this store also has, by its server row, which a pending delete layer does not hide */
2826
+ pickLinked = (key, values) => {
2827
+ const row = this.rows.get(key) ?? this.get(key);
2828
+ if (!row) return;
2829
+ return Object.fromEntries(Object.entries(values).filter(([field]) => field in row));
2830
+ };
2831
+ mirrorWrite = (key, values, stamp) => {
2832
+ if (!this.rows.has(key)) return;
2833
+ this.write(key, this.pickLinked(key, values), {
2834
+ complete: false,
2835
+ stamp,
2836
+ linked: false
2837
+ });
2838
+ };
2839
+ /** Mirrors an update or delete layer. An insert cannot make a complete row of another shape, so it stays away. */
2840
+ mirrorLayer = (layer) => {
2841
+ const values = this.pickLinked(layer.key, layer.values);
2842
+ if (!values || layer.type === "insert") return;
2843
+ this.addLayer({
2844
+ ...layer,
2845
+ id: `${layer.id}@link`,
2846
+ values
2847
+ }, false);
2848
+ };
2849
+ accepts = (meta, stamp, version) => {
2850
+ if (version !== void 0) {
2851
+ if (meta?.version === void 0) return true;
2852
+ const order = compareValues(meta.version, version);
2853
+ return order < 0 || order === 0 && meta.seq <= stamp.seq;
2854
+ }
2855
+ if (!meta) return true;
2856
+ return meta.seq < stamp.seq;
2857
+ };
2858
+ invalidate = (key) => {
2859
+ this.visible.delete(key);
2860
+ this.options.onChange(key);
2861
+ };
2862
+ };
2863
+ //#endregion
2864
+ //#region src/subset/key-subset.ts
2865
+ /** One row read by key, for `findOne`. Keys read in the same tick are batched when the loader has `byKeys`. */
2866
+ var KeySubset = class extends BaseSubset {
2867
+ constructor(collection, loader, key) {
2868
+ super(collection, loader);
2869
+ this.key = key;
2870
+ }
2871
+ holds = (key) => key === this.key;
2872
+ /** The fields of the row the server sent, so syncs scoped by those fields keep it live */
2873
+ getEqValues = () => this.collection.store.getServerRow(this.key) ?? {};
2874
+ /** Called by the collection when the batched request for this key settled */
2875
+ complete = (result) => {
2876
+ if (result.success) {
2877
+ if (!result.found) this.collection.store.remove(this.key, result.stamp);
2878
+ this.hasLoaded = true;
2879
+ this.loadedAt = Date.now();
2880
+ this.invalidated = false;
2881
+ this.error = null;
2882
+ } else this.error = result.error;
2883
+ this.endLoad();
2884
+ this.collection.markSubsetChanged(this);
2885
+ };
2886
+ run = async (options) => {
2887
+ this.beginLoad();
2888
+ await this.collection.loadKey(this, options.waitForWrites !== false);
2889
+ };
2890
+ };
2891
+ //#endregion
2892
+ //#region src/sync/sync.ts
2893
+ /**
2894
+ * One server-side subscription of a sync, for one set of filter values. Subsets that need the same subscription
2895
+ * share it, and it stops when the last one releases it.
2896
+ *
2897
+ * While a subset that uses it is loading, events are buffered and applied after the response, so an `update` for a row
2898
+ * that only the response brings is not lost.
2899
+ */
2900
+ var SyncSubscription = class {
2901
+ started = false;
2902
+ users = /* @__PURE__ */ new Set();
2903
+ loading = /* @__PURE__ */ new Set();
2904
+ buffer = [];
2905
+ unsubscribe;
2906
+ id;
2907
+ sync;
2908
+ listener;
2909
+ host;
2910
+ constructor(options) {
2911
+ this.id = options.id;
2912
+ this.sync = options.sync;
2913
+ this.listener = options.listener;
2914
+ this.host = options.host;
2915
+ }
2916
+ /** Whether the server has started the subscription and the socket is connected */
2917
+ isLive = () => this.started && this.listener.socket.adapter.connected;
2918
+ addUser = (user) => {
2919
+ this.users.add(user);
2920
+ if (this.unsubscribe) return;
2921
+ const toMessage = (event) => this.sync.type === "changes" ? event : event.data;
2922
+ this.unsubscribe = this.listener.listen((event) => this.receive(toMessage(event)), {
2923
+ onStart: () => {
2924
+ this.started = true;
2925
+ this.host.onLiveChange();
2926
+ },
2927
+ onEnd: () => {
2928
+ this.started = false;
2929
+ this.unsubscribe = void 0;
2930
+ this.host.onLiveChange();
2931
+ }
2932
+ });
2933
+ };
2934
+ removeUser = (user) => {
2935
+ this.users.delete(user);
2936
+ this.endLoad(user);
2937
+ if (this.users.size > 0) return;
2938
+ this.unsubscribe?.();
2939
+ this.unsubscribe = void 0;
2940
+ this.started = false;
2941
+ this.host.onRemove(this);
2942
+ };
2943
+ getUsers = () => [...this.users];
2944
+ beginLoad = (user) => {
2945
+ this.loading.add(user);
2946
+ };
2947
+ endLoad = (user) => {
2948
+ this.loading.delete(user);
2949
+ if (this.loading.size > 0) return;
2950
+ const buffered = this.buffer;
2951
+ this.buffer = [];
2952
+ buffered.forEach(({ message, stamp }) => this.host.applySyncMessage(this.sync, message, stamp));
2953
+ };
2954
+ receive = (message) => {
2955
+ const stamp = {
2956
+ kind: "now",
2957
+ seq: this.host.tick(),
2958
+ wall: Date.now()
2959
+ };
2960
+ if (this.loading.size > 0) {
2961
+ this.buffer.push({
2962
+ message,
2963
+ stamp
2964
+ });
2965
+ return;
2966
+ }
2967
+ this.host.applySyncMessage(this.sync, message, stamp);
2968
+ };
2969
+ };
2970
+ //#endregion
2971
+ //#region src/db/collection.runtime.ts
2972
+ /** Everything the db keeps for one collection: its rows, loaded subsets, sync subscriptions and ingested requests */
2973
+ var CollectionRuntime = class {
2974
+ store;
2975
+ listSubsets = /* @__PURE__ */ new Map();
2976
+ keySubsets = /* @__PURE__ */ new Map();
2977
+ subscriptions = /* @__PURE__ */ new Map();
2978
+ /** Server keys that replaced temporary keys of inserts */
2979
+ aliases = /* @__PURE__ */ new Map();
2980
+ renderKeys = /* @__PURE__ */ new Map();
2981
+ keyRequests = [];
2982
+ cleanups = [];
2983
+ constructor(db, name, config) {
2984
+ this.db = db;
2985
+ this.name = name;
2986
+ this.config = config;
2987
+ this.store = new Store({
2988
+ keyField: config.key,
2989
+ versionField: config.version,
2990
+ onChange: (key) => db.markRowChanged(this, key)
2991
+ });
2992
+ config.ingests.forEach((ingest) => this.listenToIngest(ingest));
2993
+ }
2994
+ /** The stable key for rendering a row, which survives swapping a temporary key for the server's */
2995
+ getRenderKey = (key) => this.renderKeys.get(key) ?? String(key);
2996
+ setRenderKey = (key, renderKey) => {
2997
+ this.renderKeys.set(key, renderKey);
2998
+ };
2999
+ /** Resolves a temporary insert key to the key the server assigned, when it has */
3000
+ resolveKey = (key) => this.aliases.get(key) ?? key;
3001
+ getListSubset = (plan, definition) => {
3002
+ const existing = this.listSubsets.get(plan.subsetId);
3003
+ if (existing) return existing;
3004
+ const loader = this.config.loaders[plan.loaderIndex];
3005
+ const subset = new ListSubset(this, {
3006
+ loader,
3007
+ plan,
3008
+ definition: {
3009
+ orderBy: definition.orderBy,
3010
+ limit: definition.limit
3011
+ }
3012
+ });
3013
+ this.listSubsets.set(plan.subsetId, subset);
3014
+ return subset;
3015
+ };
3016
+ getKeySubset = (key, loaderIndex) => {
3017
+ const existing = this.keySubsets.get(key);
3018
+ if (existing) return existing;
3019
+ const subset = new KeySubset(this, this.config.loaders[loaderIndex], key);
3020
+ this.keySubsets.set(key, subset);
3021
+ return subset;
3022
+ };
3023
+ /**
3024
+ * Finds a fresh subset whose rows contain every row a query can return, so the query is answered locally. The
3025
+ * subset must not be paginated, its sent conditions must all be part of the query's, and its loader's fixed filters
3026
+ * must be part of the query loader's.
3027
+ */
3028
+ findContainingSubset = (plan) => {
3029
+ if (plan.paginated || plan.serverOnly) return;
3030
+ const queryLoader = this.config.loaders[plan.loaderIndex];
3031
+ const sent = new Set(plan.sent.map((node) => stableStringify(node)));
3032
+ return [...this.listSubsets.values()].find((subset) => {
3033
+ if (subset.plan.paginated || subset.plan.serverOnly || !subset.isFresh()) return false;
3034
+ const fixed = subset.listLoader.fixed ?? {};
3035
+ return Object.keys(fixed).every((field) => stableStringify(queryLoader.fixed?.[field]) === stableStringify(fixed[field])) && subset.plan.sent.every((node) => sent.has(stableStringify(node)));
3036
+ });
3037
+ };
3038
+ removeSubset = (subset) => {
3039
+ if (subset instanceof ListSubset) this.listSubsets.delete(subset.id);
3040
+ else this.keySubsets.delete(subset.key);
3041
+ this.sweep();
3042
+ };
3043
+ /** Every subset, list and key */
3044
+ getSubsets = () => [...this.listSubsets.values(), ...this.keySubsets.values()];
3045
+ /** Whether a subset other than `except`, or a pending write, holds the row */
3046
+ isHeldByOthers = (key, except) => {
3047
+ return this.store.hasLayer(key) || this.getSubsets().some((subset) => subset !== except && subset.holds(key));
3048
+ };
3049
+ /** The subsets whose rows include the key, which a refetch after a write reloads */
3050
+ getSubsetsHolding = (key) => this.getSubsets().filter((subset) => subset.holds(key));
3051
+ /** Removes rows that no subset and no pending write holds */
3052
+ sweep = () => {
3053
+ this.db.batch(() => {
3054
+ this.store.getServerKeys().forEach((key) => {
3055
+ if (!this.isHeldByOthers(key)) this.store.drop(key);
3056
+ });
3057
+ });
3058
+ };
3059
+ /** Tells the queries of a subset that its rows or status changed */
3060
+ markSubsetChanged = (subset) => {
3061
+ subset.notify();
3062
+ };
3063
+ /** Orders keys by the query's orders, then by the order the loader returned, then by arrival and key */
3064
+ createComparator = (orderBy, source) => {
3065
+ return (left, right) => {
3066
+ const leftRow = this.store.get(left);
3067
+ const rightRow = this.store.get(right);
3068
+ for (const { field, direction } of orderBy) {
3069
+ const result = compareValues(leftRow?.[field], rightRow?.[field]);
3070
+ if (result !== 0) return direction === "desc" ? -result : result;
3071
+ }
3072
+ if (orderBy.length === 0) {
3073
+ const leftIndex = source?.orderIndex.get(left) ?? Number.MAX_SAFE_INTEGER;
3074
+ const rightIndex = source?.orderIndex.get(right) ?? Number.MAX_SAFE_INTEGER;
3075
+ if (leftIndex !== rightIndex) return leftIndex - rightIndex;
3076
+ return this.store.getArrival(left) - this.store.getArrival(right);
3077
+ }
3078
+ return compareValues(left, right);
3079
+ };
3080
+ };
3081
+ /** Reads the items of a response: the `rows` mapping, or the response itself */
3082
+ readItems = (source, data) => {
3083
+ if (source.rows) return [...source.rows(data)];
3084
+ return Array.isArray(data) ? data : [data];
3085
+ };
3086
+ /** Validates rows when the collection validates server data */
3087
+ prepareServerRows = (items) => {
3088
+ const mapped = items;
3089
+ const { schema } = this.config;
3090
+ if (!schema || this.config.validate !== "all") return mapped;
3091
+ const results = mapped.map((row) => schema["~standard"].validate(row));
3092
+ const collect = (settled) => {
3093
+ const rows = [];
3094
+ settled.forEach((result) => {
3095
+ if (result.issues) this.db.emitError({
3096
+ type: "validation",
3097
+ error: result.issues,
3098
+ collection: this.name
3099
+ });
3100
+ else rows.push(result.value);
3101
+ });
3102
+ return rows;
3103
+ };
3104
+ if (results.some((result) => result instanceof Promise)) return Promise.all(results).then(collect);
3105
+ return collect(results);
3106
+ };
3107
+ /** Writes server rows and returns their keys in order */
3108
+ writeServerRows = (rows, complete, stamp) => {
3109
+ return rows.map((row) => {
3110
+ const key = row[this.config.key];
3111
+ this.store.write(key, row, {
3112
+ complete,
3113
+ stamp
3114
+ });
3115
+ if (complete) this.normalize(row, stamp);
3116
+ return key;
3117
+ });
3118
+ };
3119
+ /** Writes the rows nested in a complete row into the collections that hold them */
3120
+ normalize = (row, stamp) => {
3121
+ (this.config.normalize ?? []).forEach(({ target, extract }) => {
3122
+ const collection = this.db.getCollectionByConfig(target);
3123
+ const rows = collection.prepareServerRows([...extract(row)]);
3124
+ const write = (nested) => {
3125
+ this.db.batch(() => {
3126
+ collection.writeServerRows(nested, true, stamp).forEach((key) => collection.noteInsert(key));
3127
+ });
3128
+ };
3129
+ if (rows instanceof Promise) rows.then(write);
3130
+ else write(rows);
3131
+ });
3132
+ };
3133
+ /** Rows of this collection were written: key subsets move to the sync subscriptions their rows' values pick */
3134
+ refreshKeySyncs = (keys) => {
3135
+ [...keys].forEach((key) => this.keySubsets.get(key)?.refreshSyncs());
3136
+ };
3137
+ /** Tells paginated subsets about an inserted row, so it can join their loaded range */
3138
+ noteInsert = (key) => {
3139
+ this.listSubsets.forEach((subset) => {
3140
+ subset.noteInsert(key);
3141
+ });
3142
+ };
3143
+ /** Starts or joins the sync subscriptions that cover a subset */
3144
+ subscribeSyncs = (subset) => {
3145
+ const eqValues = subset.getEqValues();
3146
+ const subscriptions = [];
3147
+ this.config.syncs.forEach((sync, index) => {
3148
+ const target = this.getSyncTarget({
3149
+ sync,
3150
+ index,
3151
+ subset,
3152
+ eqValues
3153
+ });
3154
+ if (!target) return;
3155
+ const { id, patches } = target;
3156
+ let subscription = this.subscriptions.get(id);
3157
+ if (!subscription) {
3158
+ const listener = applyListenerPatches(sync.listener, patches);
3159
+ subscription = new SyncSubscription({
3160
+ id,
3161
+ sync,
3162
+ listener,
3163
+ host: {
3164
+ tick: this.db.tick,
3165
+ applySyncMessage: this.applySyncMessage,
3166
+ onLiveChange: () => this.getSubsets().forEach((item) => item.notify()),
3167
+ onRemove: (removed) => this.subscriptions.delete(removed.id)
3168
+ }
3169
+ });
3170
+ this.subscriptions.set(id, subscription);
3171
+ this.db.watchSocket(listener.socket);
3172
+ }
3173
+ subscription.addUser(subset);
3174
+ subscriptions.push(subscription);
3175
+ });
3176
+ return subscriptions;
3177
+ };
3178
+ /**
3179
+ * Which subscription of a sync covers a subset, and the listener params it needs.
3180
+ *
3181
+ * - A sync with `byKey` covers a row read by key with a listener of its own, and with a notation it also covers every
3182
+ * list subset with its sent conditions. Without `byKey`, a sync with a notation covers list subsets only, because
3183
+ * a listener on the whole collection for one row is wasteful and, on Firestore, billed.
3184
+ * - A sync with `where` covers subsets whose values fill every field it declares: the sent `eq` conditions of a list,
3185
+ * or the fields of the row a key subset holds, so a post read by key joins its team's subscription.
3186
+ */
3187
+ getSyncTarget = ({ sync, index, subset, eqValues }) => {
3188
+ if (subset instanceof KeySubset && sync.byKey) return {
3189
+ id: stableStringify([
3190
+ index,
3191
+ "key",
3192
+ subset.key
3193
+ ]),
3194
+ patches: [sync.byKey(subset.key)]
3195
+ };
3196
+ if (sync.notation) {
3197
+ if (subset instanceof KeySubset) return;
3198
+ const conditions = subset.plan.sent.filter((node) => node.op !== "server");
3199
+ return {
3200
+ id: stableStringify([index, conditions]),
3201
+ patches: [sync.notation(conditions)]
3202
+ };
3203
+ }
3204
+ if (sync.byKey && subset instanceof ListSubset) return;
3205
+ const fields = Object.keys(sync.where ?? {});
3206
+ if (!fields.every((field) => field in eqValues)) return;
3207
+ const values = Object.fromEntries(fields.map((field) => [field, eqValues[field]]));
3208
+ return {
3209
+ id: stableStringify([index, values]),
3210
+ patches: fields.map((field) => sync.where[field].eq(values[field]))
3211
+ };
3212
+ };
3213
+ /** Applies a `changes` event: complete rows to write and keys to delete */
3214
+ applyChanges = (sync, message, stamp) => {
3215
+ const { upsert, delete: deleted, refetch = [] } = sync.changes(message);
3216
+ refetch.forEach((key) => this.fetchByKey(key));
3217
+ const apply = (rows) => {
3218
+ this.db.batch(() => {
3219
+ rows.forEach((row) => {
3220
+ const key = row[this.config.key];
3221
+ this.writeServerRows([row], true, stamp);
3222
+ this.noteInsert(key);
3223
+ this.db.notifySyncWrite(this.name, key);
3224
+ });
3225
+ deleted.forEach((key) => {
3226
+ this.store.remove(key, stamp);
3227
+ this.db.notifySyncWrite(this.name, key);
3228
+ });
3229
+ });
3230
+ };
3231
+ const rows = this.prepareServerRows([...upsert]);
3232
+ if (rows instanceof Promise) rows.then(apply);
3233
+ else apply(rows);
3234
+ };
3235
+ /** Applies one sync event */
3236
+ /** Applies a sync event. A mapping that throws on one event is reported, and the next events still apply. */
3237
+ applySyncMessage = (sync, message, stamp) => {
3238
+ try {
3239
+ this.applySyncEvent(sync, message, stamp);
3240
+ } catch (error) {
3241
+ this.db.emitError({
3242
+ type: "sync",
3243
+ error,
3244
+ collection: this.name
3245
+ });
3246
+ }
3247
+ };
3248
+ applySyncEvent = (sync, message, stamp) => {
3249
+ const keyField = this.config.key;
3250
+ if (sync.type === "changes") {
3251
+ this.applyChanges(sync, message, stamp);
3252
+ return;
3253
+ }
3254
+ if (sync.type === "delete") {
3255
+ const key = sync.key ? sync.key(message) : message[keyField];
3256
+ this.db.batch(() => {
3257
+ this.store.remove(key, stamp);
3258
+ this.db.notifySyncWrite(this.name, key);
3259
+ });
3260
+ return;
3261
+ }
3262
+ const apply = (rows) => {
3263
+ this.db.batch(() => {
3264
+ rows.forEach((row) => {
3265
+ const key = row[keyField];
3266
+ if (sync.type === "insert") {
3267
+ this.writeServerRows([row], true, stamp);
3268
+ this.noteInsert(key);
3269
+ } else if (this.store.hasServerRow(key)) {
3270
+ this.store.write(key, row, {
3271
+ complete: false,
3272
+ stamp
3273
+ });
3274
+ this.listSubsets.forEach((subset) => subset.excluded.delete(key));
3275
+ } else if (sync.incomplete === "refetch") this.fetchByKey(key);
3276
+ this.db.notifySyncWrite(this.name, key);
3277
+ });
3278
+ });
3279
+ };
3280
+ const rows = this.prepareServerRows([sync.row ? sync.row(message) : message]);
3281
+ if (rows instanceof Promise) rows.then(apply);
3282
+ else apply(rows);
3283
+ };
3284
+ /** Loads one row by key without a query, for example for an incomplete sync event */
3285
+ fetchByKey = (key) => {
3286
+ const loaderIndex = this.config.loaders.findIndex((loader) => loader.kind !== "list");
3287
+ if (loaderIndex === -1) return Promise.resolve();
3288
+ const subset = this.getKeySubset(key, loaderIndex);
3289
+ const observer = { onSubsetChange: () => {} };
3290
+ subset.attach(observer);
3291
+ return subset.load().then(() => subset.detach(observer));
3292
+ };
3293
+ /** Loads a key subset's row, batched with the other keys requested in the same tick */
3294
+ loadKey = (subset, waitForWrites = true) => {
3295
+ return new Promise((resolve) => {
3296
+ this.keyRequests.push({
3297
+ subset,
3298
+ resolve,
3299
+ waitForWrites
3300
+ });
3301
+ if (this.keyRequests.length === 1) queueMicrotask(() => this.flushKeyRequests());
3302
+ });
3303
+ };
3304
+ /** Resolves once no write of this collection is in flight */
3305
+ mutationsSettled = () => this.db.mutations.settled(this.name);
3306
+ /** Removes every row and resets the loaded subsets, for example on sign-out */
3307
+ clear = () => {
3308
+ this.store.clear();
3309
+ this.listSubsets.forEach((subset) => {
3310
+ subset.owned.clear();
3311
+ subset.inserted.clear();
3312
+ subset.excluded.clear();
3313
+ subset.orderIndex.clear();
3314
+ subset.pages = 0;
3315
+ subset.hasLoaded = false;
3316
+ subset.loadedAt = 0;
3317
+ });
3318
+ this.keySubsets.forEach((subset) => {
3319
+ subset.hasLoaded = false;
3320
+ subset.loadedAt = 0;
3321
+ });
3322
+ this.getSubsets().forEach((subset) => subset.notify());
3323
+ };
3324
+ destroy = () => {
3325
+ this.cleanups.forEach((cleanup) => cleanup());
3326
+ this.cleanups = [];
3327
+ this.getSubsets().forEach((subset) => subset.cancelGc());
3328
+ this.subscriptions.forEach((subscription) => {
3329
+ subscription.getUsers().forEach((user) => subscription.removeUser(user));
3330
+ });
3331
+ };
3332
+ flushKeyRequests = async () => {
3333
+ const requests = this.keyRequests;
3334
+ this.keyRequests = [];
3335
+ await this.db.ready;
3336
+ if (requests.some((request) => request.waitForWrites)) await this.mutationsSettled();
3337
+ const groups = /* @__PURE__ */ new Map();
3338
+ requests.forEach((request) => {
3339
+ const { loader } = request.subset;
3340
+ groups.set(loader, [...groups.get(loader) ?? [], request]);
3341
+ });
3342
+ await Promise.all([...groups.entries()].map(([loader, group]) => {
3343
+ if (loader.kind === "byKeys") return this.sendKeyRequest(loader, group, loader.byKeys(group.map(({ subset }) => subset.key)));
3344
+ return Promise.all(group.map((request) => this.sendKeyRequest(loader, [request], loader.byKey(request.subset.key))));
3345
+ }));
3346
+ };
3347
+ sendKeyRequest = async (loader, group, patch) => {
3348
+ const seq = this.db.tick();
3349
+ const wall = Date.now();
3350
+ const { generation } = this.db;
3351
+ this.db.trackRequest(seq);
3352
+ try {
3353
+ const response = await applyRequestPatches(loader.request.setCache(false), [patch]).send();
3354
+ const items = response.success ? this.readItems(loader, response.data) : [];
3355
+ const rows = await this.prepareServerRows(items);
3356
+ if (this.db.generation !== generation) {
3357
+ group.forEach(({ subset }) => subset.complete({
3358
+ success: false,
3359
+ error: /* @__PURE__ */ new Error("Cleared")
3360
+ }));
3361
+ return;
3362
+ }
3363
+ const returnedKeys = new Set(items.filter(isPlainObject$1).map((item) => item[this.config.key]));
3364
+ this.db.batch(() => {
3365
+ if (response.success) {
3366
+ const keys = new Set(this.writeServerRows(rows, true, {
3367
+ kind: "sent",
3368
+ seq,
3369
+ wall
3370
+ }));
3371
+ const stamp = {
3372
+ kind: "sent",
3373
+ seq,
3374
+ wall
3375
+ };
3376
+ group.forEach(({ subset }) => {
3377
+ subset.complete({
3378
+ success: true,
3379
+ found: keys.has(subset.key) || returnedKeys.has(subset.key),
3380
+ stamp
3381
+ });
3382
+ });
3383
+ } else group.forEach(({ subset }) => subset.complete({
3384
+ success: false,
3385
+ error: response.error ?? response
3386
+ }));
3387
+ });
3388
+ } catch (error) {
3389
+ this.db.emitError({
3390
+ type: "load",
3391
+ error,
3392
+ collection: this.name
3393
+ });
3394
+ this.db.batch(() => group.forEach(({ subset }) => subset.complete({
3395
+ success: false,
3396
+ error
3397
+ })));
3398
+ } finally {
3399
+ this.db.settleRequest(seq);
3400
+ group.forEach(({ resolve }) => resolve());
3401
+ }
3402
+ };
3403
+ listenToIngest = (ingest) => {
3404
+ const { request: ingested } = ingest;
3405
+ const { events } = ingested.client.requestManager;
3406
+ const matches = (request) => request.requestOptions.endpoint === ingested.requestOptions.endpoint && request.method === ingested.method;
3407
+ const sentAt = /* @__PURE__ */ new Map();
3408
+ const generations = /* @__PURE__ */ new Map();
3409
+ const unsubscribeStart = events.onRequestStart(({ request, requestId }) => {
3410
+ if (matches(request)) {
3411
+ const seq = this.db.tick();
3412
+ sentAt.set(requestId, seq);
3413
+ generations.set(requestId, this.db.generation);
3414
+ this.db.trackRequest(seq);
3415
+ }
3416
+ });
3417
+ const unsubscribe = events.onResponse(({ request, requestId, response }) => {
3418
+ if (!matches(request)) return;
3419
+ const seq = sentAt.get(requestId);
3420
+ const generation = generations.get(requestId) ?? this.db.generation;
3421
+ sentAt.delete(requestId);
3422
+ generations.delete(requestId);
3423
+ if (seq !== void 0) this.db.settleRequest(seq);
3424
+ if (!response.success || generation !== this.db.generation) return;
3425
+ const items = this.readItems(ingest, response.data).filter(isPlainObject$1);
3426
+ const write = (rows) => {
3427
+ const stamp = {
3428
+ kind: "sent",
3429
+ seq: seq ?? this.db.tick(),
3430
+ wall: response.requestTimestamp
3431
+ };
3432
+ this.db.batch(() => {
3433
+ const keys = this.writeServerRows(rows, ingest.type === "insert", stamp);
3434
+ if (ingest.type === "insert") keys.forEach((key) => this.noteInsert(key));
3435
+ });
3436
+ };
3437
+ const rows = this.prepareServerRows(items);
3438
+ if (rows instanceof Promise) rows.then(write);
3439
+ else write(rows);
3440
+ });
3441
+ this.cleanups.push(unsubscribe, unsubscribeStart);
3442
+ };
3443
+ };
3444
+ //#endregion
3445
+ //#region src/db/db.runtime.ts
3446
+ var DEFAULT_GC_TIME = 300 * 1e3;
3447
+ var DEFAULT_SYNC_TIMEOUT = 5e3;
3448
+ /**
3449
+ * The running db. It owns the collections, batches writes into transactions so every query updates once, revalidates
3450
+ * stale subsets on focus and reconnect, and connects persistence, the outbox and other tabs.
3451
+ */
3452
+ var DbRuntime = class {
3453
+ collections = /* @__PURE__ */ new Map();
3454
+ gcTime;
3455
+ syncTimeout;
3456
+ notation;
3457
+ mutations;
3458
+ persistence;
3459
+ serializer;
3460
+ changeListeners = /* @__PURE__ */ new Set();
3461
+ /** Timers of sync waits, cleared on `destroy` */
3462
+ timers = /* @__PURE__ */ new Set();
3463
+ queryTimers = /* @__PURE__ */ new Map();
3464
+ tabs;
3465
+ ready;
3466
+ /** Changes on `clear`, so responses to requests sent before are never written */
3467
+ generation = 0;
3468
+ isReady = true;
3469
+ isDestroyed = false;
3470
+ seq = 0;
3471
+ batchDepth = 0;
3472
+ changedRows = /* @__PURE__ */ new Map();
3473
+ dirtyQueries = /* @__PURE__ */ new Set();
3474
+ liveQueries = /* @__PURE__ */ new Map();
3475
+ inflight = /* @__PURE__ */ new Set();
3476
+ errorListeners = /* @__PURE__ */ new Set();
3477
+ syncWaiters = /* @__PURE__ */ new Map();
3478
+ lastSyncWrite = /* @__PURE__ */ new Map();
3479
+ sockets = /* @__PURE__ */ new Set();
3480
+ cleanups = [];
3481
+ constructor(collections, options = {}) {
3482
+ this.gcTime = options.gcTime ?? DEFAULT_GC_TIME;
3483
+ this.syncTimeout = options.syncTimeout ?? DEFAULT_SYNC_TIMEOUT;
3484
+ this.notation = {
3485
+ where: options.where,
3486
+ orderBy: options.orderBy
3487
+ };
3488
+ this.mutations = new MutationEngine(this, options.offline, options.transactions);
3489
+ this.serializer = createSerializer(options.codecs);
3490
+ Object.entries(collections).forEach(([name, definition]) => {
3491
+ this.collections.set(name, new CollectionRuntime(this, name, definition.config));
3492
+ });
3493
+ this.collections.forEach((collection) => {
3494
+ (collection.config.normalize ?? []).forEach(({ target }) => {
3495
+ if (!this.getCollectionByConfig(target)) throw new Error(`"${collection.name}" normalizes into a collection that was not passed to createDb`);
3496
+ });
3497
+ });
3498
+ (options.links ?? []).forEach(([first, second]) => {
3499
+ const left = this.collections.get(first).store;
3500
+ const right = this.collections.get(second).store;
3501
+ left.link(right);
3502
+ right.link(left);
3503
+ });
3504
+ this.collections.forEach((collection) => {
3505
+ collection.config.loaders.forEach((loader) => this.watchClient(loader.request.client));
3506
+ Object.values(collection.config.mutations).forEach((mutation) => this.watchClient(mutation.request.client));
3507
+ });
3508
+ if (options.state) this.hydrate(options.state);
3509
+ if (options.persistence) {
3510
+ const scope = options.persistence.scope ?? "default";
3511
+ this.persistence = new Persistence(this, options.persistence, this.serializer);
3512
+ if (options.tabs !== false) this.tabs = new Tabs(`hf-db:${scope}`, options.tabs, {
3513
+ onLeader: this.takeLead,
3514
+ onMessage: this.onTabsMessage
3515
+ });
3516
+ this.isReady = false;
3517
+ this.ready = this.restore();
3518
+ this.tabs?.start();
3519
+ } else this.ready = Promise.resolve();
3520
+ }
3521
+ /** Listens to every change the db makes, once per batch of writes, load or outbox change. Returns the unsubscribe. */
3522
+ onChange = (listener) => {
3523
+ this.changeListeners.add(listener);
3524
+ return () => {
3525
+ this.changeListeners.delete(listener);
3526
+ };
3527
+ };
3528
+ notifyChange = () => {
3529
+ this.changeListeners.forEach((listener) => listener());
3530
+ };
3531
+ /** What the db holds right now: collections with their layers and subsets, live queries and the outbox */
3532
+ inspect = () => ({
3533
+ collections: [...this.collections.values()].map((collection) => ({
3534
+ name: collection.name,
3535
+ rows: collection.store.keys().length,
3536
+ layers: collection.store.getLayers().map(({ id, key, type }) => ({
3537
+ id,
3538
+ key,
3539
+ type
3540
+ })),
3541
+ subsets: collection.getSubsets().map((subset) => ({
3542
+ id: subset instanceof ListSubset ? subset.id : String(subset.key),
3543
+ kind: subset instanceof ListSubset ? "list" : "key",
3544
+ loader: collection.config.loaders.indexOf(subset.loader),
3545
+ rows: subset instanceof ListSubset ? subset.owned.size : Number(Boolean(collection.store.get(subset.key))),
3546
+ fresh: subset.isFresh(),
3547
+ live: subset.isLive(),
3548
+ loading: subset.isLoading,
3549
+ error: subset.error,
3550
+ loadedAt: subset.loadedAt,
3551
+ observers: subset.observerCount
3552
+ }))
3553
+ })),
3554
+ queries: [...this.liveQueries.values()].map((query) => {
3555
+ const state = query.getState();
3556
+ return {
3557
+ key: query.key,
3558
+ collection: query.collection.name,
3559
+ subscribers: query.subscriberCount,
3560
+ status: state.status,
3561
+ rows: Array.isArray(state.data) ? state.data.length : void 0,
3562
+ plan: query.explain()
3563
+ };
3564
+ }),
3565
+ outbox: [...this.mutations.outbox]
3566
+ });
3567
+ /** The server rows and loaded subsets of every collection that holds any, as type-tagged JSON */
3568
+ dehydrate = () => {
3569
+ const collections = Object.fromEntries([...this.collections.values()].map((collection) => [collection.name, snapshotCollection(collection)]).filter(([, snapshot]) => snapshot.rows.length > 0 || snapshot.subsets.length > 0));
3570
+ return {
3571
+ __dehydrated: true,
3572
+ collections: this.serializer.encode(collections)
3573
+ };
3574
+ };
3575
+ /** Writes a server's rows and subsets, before anything renders, so the first render matches the server's */
3576
+ hydrate = (state) => {
3577
+ const collections = this.serializer.decode(state.collections);
3578
+ Object.entries(collections).forEach(([name, snapshot]) => {
3579
+ const collection = this.collections.get(name);
3580
+ if (collection) restoreSnapshot(collection, snapshot);
3581
+ });
3582
+ };
3583
+ /** Whether this tab replays the outbox and writes persisted rows */
3584
+ get isLeader() {
3585
+ return this.tabs ? this.tabs.isLeader : true;
3586
+ }
3587
+ /** The collection a config belongs to, for references between collections such as `normalize` */
3588
+ getCollectionByConfig = (config) => {
3589
+ return [...this.collections.values()].find((item) => item.config === config);
3590
+ };
3591
+ tick = () => {
3592
+ this.seq += 1;
3593
+ return this.seq;
3594
+ };
3595
+ /** Runs writes as one transaction: every query updates once, after the last write */
3596
+ batch = (callback) => {
3597
+ this.batchDepth += 1;
3598
+ try {
3599
+ return callback();
3600
+ } finally {
3601
+ this.batchDepth -= 1;
3602
+ if (this.batchDepth === 0) this.flush();
3603
+ }
3604
+ };
3605
+ /** Records a changed row. Every store write runs inside `batch`, which flushes the changes once it ends. */
3606
+ markRowChanged = (collection, key) => {
3607
+ const keys = this.changedRows.get(collection) ?? /* @__PURE__ */ new Set();
3608
+ keys.add(key);
3609
+ this.changedRows.set(collection, keys);
3610
+ };
3611
+ markQueryDirty = (query) => {
3612
+ this.dirtyQueries.add(query);
3613
+ if (this.batchDepth === 0) this.flush();
3614
+ };
3615
+ /** The live query for a definition, shared by every query with the same structure */
3616
+ getLiveQuery = (definition) => {
3617
+ const key = stableStringify(definition);
3618
+ const existing = this.liveQueries.get(key);
3619
+ if (existing) return existing;
3620
+ const query = new LiveQuery(this.collections.get(definition.collection), definition, key);
3621
+ this.liveQueries.set(key, query);
3622
+ this.releaseLater(query);
3623
+ return query;
3624
+ };
3625
+ /**
3626
+ * Forgets a live query nobody subscribes to after `gcTime`, so queries made once, such as each search, do not pile
3627
+ * up and slow every write. A query read again later is made again.
3628
+ */
3629
+ releaseLater = (query) => {
3630
+ clearTimeout(this.queryTimers.get(query));
3631
+ const timer = setTimeout(() => {
3632
+ this.queryTimers.delete(query);
3633
+ if (!query.isActive() && this.liveQueries.get(query.key) === query) this.liveQueries.delete(query.key);
3634
+ }, this.gcTime);
3635
+ this.queryTimers.set(query, timer);
3636
+ };
3637
+ trackRequest = (seq) => {
3638
+ this.inflight.add(seq);
3639
+ };
3640
+ /** A request the db sent settled, so deletes made after every pending request no longer need remembering */
3641
+ settleRequest = (seq) => {
3642
+ this.inflight.delete(seq);
3643
+ const oldest = this.inflight.size > 0 ? Math.min(...this.inflight) : Number.POSITIVE_INFINITY;
3644
+ this.collections.forEach((collection) => collection.store.forgetTombstones(oldest));
3645
+ };
3646
+ onError = (listener) => {
3647
+ this.errorListeners.add(listener);
3648
+ return () => {
3649
+ this.errorListeners.delete(listener);
3650
+ };
3651
+ };
3652
+ emitError = (event) => {
3653
+ this.errorListeners.forEach((listener) => listener(event));
3654
+ };
3655
+ /** A sync event touched a row, which writes with `onSuccess: "sync"` wait for */
3656
+ notifySyncWrite = (collection, key) => {
3657
+ const id = `${collection}:${String(key)}`;
3658
+ this.lastSyncWrite.set(id, this.tick());
3659
+ const waiters = this.syncWaiters.get(id);
3660
+ this.syncWaiters.delete(id);
3661
+ waiters?.forEach((resolve) => resolve());
3662
+ };
3663
+ /**
3664
+ * Resolves with `true` when a sync event touched the row after `since`, also while the write was in flight, or with
3665
+ * `false` after the timeout
3666
+ */
3667
+ waitForSync = ({ collection, key, since, timeout }) => {
3668
+ const id = `${collection}:${String(key)}`;
3669
+ if ((this.lastSyncWrite.get(id) ?? 0) > since) return Promise.resolve(true);
3670
+ return new Promise((resolve) => {
3671
+ const waiters = this.syncWaiters.get(id) ?? /* @__PURE__ */ new Set();
3672
+ const timer = setTimeout(() => {
3673
+ this.timers.delete(timer);
3674
+ waiters.delete(onSync);
3675
+ resolve(false);
3676
+ }, timeout);
3677
+ this.timers.add(timer);
3678
+ const onSync = () => {
3679
+ clearTimeout(timer);
3680
+ this.timers.delete(timer);
3681
+ resolve(true);
3682
+ };
3683
+ waiters.add(onSync);
3684
+ this.syncWaiters.set(id, waiters);
3685
+ });
3686
+ };
3687
+ /** Marks the subsets a socket's syncs covered stale after a reconnect, unless their subscriptions resume */
3688
+ watchSocket = (socket) => {
3689
+ if (this.sockets.has(socket)) return;
3690
+ this.sockets.add(socket);
3691
+ let connectedBefore = socket.adapter.connected;
3692
+ const notifyAll = () => {
3693
+ this.collections.forEach((collection) => collection.getSubsets().forEach((subset) => subset.notify()));
3694
+ };
3695
+ this.cleanups.push(socket.events.onDisconnected(notifyAll), socket.events.onConnected(() => {
3696
+ if (connectedBefore) this.collections.forEach((collection) => {
3697
+ collection.subscriptions.forEach((subscription) => {
3698
+ if (subscription.listener.socket !== socket || subscription.sync.resumes) return;
3699
+ subscription.getUsers().forEach((user) => {
3700
+ const subset = user;
3701
+ subset.invalidate();
3702
+ if (subset.isUsed()) subset.revalidate();
3703
+ });
3704
+ });
3705
+ });
3706
+ connectedBefore = true;
3707
+ notifyAll();
3708
+ }));
3709
+ };
3710
+ /** Removes every row, loaded subset and pending write, and the persisted data of the scope */
3711
+ clear = async () => {
3712
+ this.tabs?.post({ type: "clear" });
3713
+ this.clearLocal();
3714
+ await this.persistence?.clear();
3715
+ this.revalidateActive();
3716
+ };
3717
+ /** Refetches the stale subsets of every mounted query */
3718
+ revalidateActive = () => {
3719
+ this.liveQueries.forEach((query) => {
3720
+ if (query.isActive()) query.revalidate();
3721
+ });
3722
+ };
3723
+ /**
3724
+ * Drops rows, subsets and pending writes in this tab. Responses to requests sent before belong to the previous user,
3725
+ * so the generation changes and they are never written.
3726
+ */
3727
+ clearLocal = () => {
3728
+ this.generation += 1;
3729
+ this.mutations.clear();
3730
+ this.batch(() => this.collections.forEach((collection) => collection.clear()));
3731
+ };
3732
+ /** This tab became the leader: it adopts the persisted outbox, so the previous leader's writes are replayed */
3733
+ takeLead = async () => {
3734
+ const stored = await this.persistence.loadOutbox();
3735
+ this.mutations.mergeOutbox(stored);
3736
+ this.tabs?.post({ type: "leader" });
3737
+ };
3738
+ destroy = () => {
3739
+ this.isDestroyed = true;
3740
+ this.mutations.destroy();
3741
+ this.timers.forEach((timer) => clearTimeout(timer));
3742
+ this.timers.clear();
3743
+ this.queryTimers.forEach((timer) => clearTimeout(timer));
3744
+ this.queryTimers.clear();
3745
+ this.liveQueries.clear();
3746
+ this.cleanups.forEach((cleanup) => cleanup());
3747
+ this.cleanups = [];
3748
+ this.collections.forEach((collection) => collection.destroy());
3749
+ this.persistence?.destroy();
3750
+ this.tabs?.close();
3751
+ };
3752
+ watchClients = /* @__PURE__ */ new Set();
3753
+ watchClient = (client) => {
3754
+ if (this.watchClients.has(client)) return;
3755
+ this.watchClients.add(client);
3756
+ const revalidate = () => {
3757
+ this.liveQueries.forEach((query) => {
3758
+ if (query.isActive()) query.revalidate();
3759
+ });
3760
+ };
3761
+ this.cleanups.push(client.appManager.events.onFocus(revalidate), client.appManager.events.onOnline(() => {
3762
+ revalidate();
3763
+ this.mutations.pump();
3764
+ }));
3765
+ };
3766
+ flush = () => {
3767
+ const changed = this.changedRows.size > 0 || this.dirtyQueries.size > 0;
3768
+ this.flushPending();
3769
+ if (changed) this.notifyChange();
3770
+ };
3771
+ flushPending = () => {
3772
+ while (this.changedRows.size > 0 || this.dirtyQueries.size > 0) {
3773
+ const rows = this.changedRows;
3774
+ const dirty = this.dirtyQueries;
3775
+ this.changedRows = /* @__PURE__ */ new Map();
3776
+ this.dirtyQueries = /* @__PURE__ */ new Set();
3777
+ this.liveQueries.forEach((query) => {
3778
+ const keys = rows.get(query.collection);
3779
+ if (keys && !dirty.has(query)) query.onRowsChanged(keys);
3780
+ if (!dirty.has(query) && query.isActive() && [...rows.keys()].some((collection) => query.dependsOn(collection))) query.onJoinedRowsChanged();
3781
+ });
3782
+ dirty.forEach((query) => query.rebuild());
3783
+ rows.forEach((keys, collection) => collection.refreshKeySyncs(keys));
3784
+ if (rows.size > 0) {
3785
+ this.persistence?.scheduleSave(rows.keys());
3786
+ this.forwardRows(rows);
3787
+ }
3788
+ }
3789
+ };
3790
+ /** Tabs that do not persist send their server rows to the tab that does */
3791
+ forwardRows = (rows) => {
3792
+ if (!this.tabs || this.isLeader || !this.isReady) return;
3793
+ rows.forEach((keys, collection) => {
3794
+ const entries = [...keys].map((key) => [key, collection.store.getServerRow(key)]).filter((entry) => Boolean(entry[1]));
3795
+ if (entries.length > 0) this.tabs.post({
3796
+ type: "rows",
3797
+ collection: collection.name,
3798
+ rows: entries.map(([key, row]) => [key, row])
3799
+ });
3800
+ });
3801
+ };
3802
+ onTabsMessage = (message) => {
3803
+ if (message.type === "outcome") {
3804
+ this.mutations.applyOutcome(message);
3805
+ return;
3806
+ }
3807
+ if (message.type === "clear") {
3808
+ this.clearLocal();
3809
+ this.revalidateActive();
3810
+ return;
3811
+ }
3812
+ if (message.type === "leader") {
3813
+ this.mutations.resendToLeader();
3814
+ return;
3815
+ }
3816
+ if (!this.isLeader) return;
3817
+ if (message.type === "enqueue") {
3818
+ this.mutations.mergeOutbox(message.records);
3819
+ return;
3820
+ }
3821
+ const collection = this.collections.get(message.collection);
3822
+ if (!collection) return;
3823
+ this.batch(() => {
3824
+ message.rows.forEach(([key, row]) => {
3825
+ if (!collection.store.hasServerRow(key)) collection.store.write(key, row, {
3826
+ complete: true,
3827
+ stamp: {
3828
+ kind: "sent",
3829
+ seq: 0,
3830
+ wall: 0
3831
+ }
3832
+ });
3833
+ });
3834
+ });
3835
+ };
3836
+ restore = async () => {
3837
+ let outbox = [];
3838
+ try {
3839
+ outbox = await this.persistence.restore();
3840
+ } catch (error) {
3841
+ this.emitError({
3842
+ type: "persistence",
3843
+ error
3844
+ });
3845
+ }
3846
+ this.isReady = true;
3847
+ this.mutations.restore(outbox);
3848
+ this.batch(() => this.liveQueries.forEach((query) => this.markQueryDirty(query)));
3849
+ };
3850
+ };
3851
+ //#endregion
3852
+ //#region src/db/db.ts
3853
+ var TEMPORARY_KEY_PREFIX = "tmp:";
3854
+ /** A collection inside a db: queries start here, and writes go through it */
3855
+ var CollectionHandle = class {
3856
+ /** The collection's name in `createDb` */
3857
+ collectionName;
3858
+ /** Adds an optimistic insert and sends it. A row without a key gets a temporary one until the server assigns it. */
3859
+ insert;
3860
+ /** Adds an optimistic update and sends it */
3861
+ update;
3862
+ /** Adds an optimistic delete and sends it */
3863
+ delete;
3864
+ constructor(runtime, name) {
3865
+ this.runtime = runtime;
3866
+ this.name = name;
3867
+ this.collectionName = name;
3868
+ this.insert = ((row, options) => this.write({
3869
+ op: "insert",
3870
+ key: void 0,
3871
+ input: row,
3872
+ options
3873
+ }));
3874
+ this.update = ((key, changes, options) => this.write({
3875
+ op: "update",
3876
+ key,
3877
+ input: changes,
3878
+ options
3879
+ }));
3880
+ this.delete = ((key, options) => this.write({
3881
+ op: "delete",
3882
+ key,
3883
+ input: {},
3884
+ options
3885
+ }));
3886
+ }
3887
+ where(callback) {
3888
+ return this.start().where(callback);
3889
+ }
3890
+ orderBy(callback, direction) {
3891
+ return this.start().orderBy(callback, direction);
3892
+ }
3893
+ select(callback) {
3894
+ return this.start().select(callback);
3895
+ }
3896
+ limit(limit) {
3897
+ return this.start().limit(limit);
3898
+ }
3899
+ /** Adds the row of another collection whose key is the given field. See `Query.join`. */
3900
+ join(name, collection, by) {
3901
+ return this.start().join(name, collection, by);
3902
+ }
3903
+ /** Reads only the rows the db holds and never sends a request */
3904
+ local() {
3905
+ return this.start().local();
3906
+ }
3907
+ /** Reads one row by key */
3908
+ findOne(key) {
3909
+ return new Query(this.runtime, {
3910
+ collection: this.name,
3911
+ orderBy: [],
3912
+ local: false,
3913
+ one: { key }
3914
+ });
3915
+ }
3916
+ /** The key to render a row with. It stays the same when a temporary key is swapped for the server's. */
3917
+ renderKey(key) {
3918
+ return this.getRuntime().getRenderKey(key);
3919
+ }
3920
+ start() {
3921
+ return new Query(this.runtime, {
3922
+ collection: this.name,
3923
+ orderBy: [],
3924
+ local: false
3925
+ });
3926
+ }
3927
+ getRuntime() {
3928
+ return this.runtime.collections.get(this.name);
3929
+ }
3930
+ write({ op, key: givenKey, input, options }) {
3931
+ const collection = this.getRuntime();
3932
+ const { mutations } = this.runtime;
3933
+ const key = givenKey === void 0 ? void 0 : collection.resolveKey(givenKey);
3934
+ const dependsOn = (options?.dependsOn ?? []).map((item) => typeof item === "string" ? item : item.id);
3935
+ const { key: keyField } = collection.config;
3936
+ const id = createId();
3937
+ const submit = (values) => {
3938
+ if (op !== "insert") return mutations.submit({
3939
+ collection,
3940
+ op,
3941
+ key,
3942
+ values,
3943
+ dependsOn,
3944
+ id
3945
+ });
3946
+ const rowKey = values[keyField];
3947
+ if (rowKey !== void 0 && rowKey !== null) return mutations.submit({
3948
+ collection,
3949
+ op,
3950
+ key: rowKey,
3951
+ values,
3952
+ dependsOn,
3953
+ id
3954
+ });
3955
+ const insertRequest = collection.config.mutations.insert?.request;
3956
+ if (mutations.usesOutbox && insertRequest && !insertRequest.client.appManager.isOnline) return mutations.reject(/* @__PURE__ */ new Error("An insert that leaves the key to the server cannot be made offline"), id);
3957
+ const temporaryKey = `${TEMPORARY_KEY_PREFIX}${id}`;
3958
+ return mutations.submit({
3959
+ collection,
3960
+ op,
3961
+ key: temporaryKey,
3962
+ values: {
3963
+ ...values,
3964
+ [keyField]: temporaryKey
3965
+ },
3966
+ dependsOn,
3967
+ id,
3968
+ temporaryKey: true
3969
+ });
3970
+ };
3971
+ const mistake = findWriteMistake({
3972
+ collection,
3973
+ op,
3974
+ key,
3975
+ input
3976
+ });
3977
+ if (mistake) {
3978
+ this.runtime.emitError({
3979
+ type: "mutation",
3980
+ error: mistake,
3981
+ collection: this.name
3982
+ });
3983
+ return mutations.reject(mistake, id);
3984
+ }
3985
+ const prepared = prepareWrite({
3986
+ collection,
3987
+ op,
3988
+ key,
3989
+ input
3990
+ });
3991
+ const finish = (result) => {
3992
+ if ("issues" in result) {
3993
+ this.runtime.emitError({
3994
+ type: "validation",
3995
+ error: result.issues,
3996
+ collection: this.name
3997
+ });
3998
+ return mutations.reject(result.issues, id);
3999
+ }
4000
+ return submit(result.values);
4001
+ };
4002
+ if (prepared instanceof Promise) return createTransaction(id, prepared.then(finish));
4003
+ return finish(prepared);
4004
+ }
4005
+ };
4006
+ /** A write that cannot be right whatever the server says: an insert of a key the db holds, or an update of the key */
4007
+ var findWriteMistake = ({ collection, op, key, input }) => {
4008
+ const keyField = collection.config.key;
4009
+ const insertedKey = input[keyField];
4010
+ if (op === "insert" && insertedKey !== void 0 && collection.store.get(insertedKey)) return /* @__PURE__ */ new Error(`"${collection.name}" already holds a row with the key ${String(insertedKey)}`);
4011
+ if (op === "update" && keyField in input && input[keyField] !== key) return /* @__PURE__ */ new Error(`An update cannot change the key of a row in "${collection.name}"`);
4012
+ };
4013
+ /**
4014
+ * Validates a write against the collection's schema. An insert is validated as a row; an update is validated merged
4015
+ * with the current row, and only its changed fields are kept. A delete, a collection without a schema, and an update of
4016
+ * a row the db does not hold pass as they are.
4017
+ */
4018
+ var prepareWrite = ({ collection, op, key, input }) => {
4019
+ const { schema } = collection.config;
4020
+ const current = op === "update" ? collection.store.get(key) : void 0;
4021
+ const defined = op === "update" ? Object.fromEntries(Object.entries(input).filter(([, value]) => value !== void 0)) : input;
4022
+ if (!schema || op === "delete" || op === "update" && !current) return { values: defined };
4023
+ const candidate = op === "update" ? {
4024
+ ...current,
4025
+ ...defined
4026
+ } : input;
4027
+ const finish = (result) => {
4028
+ if (result.issues) return { issues: result.issues };
4029
+ const output = result.value;
4030
+ return { values: op === "insert" ? output : Object.fromEntries(Object.keys(defined).map((field) => [field, output[field]])) };
4031
+ };
4032
+ const validation = schema["~standard"].validate(candidate);
4033
+ return validation instanceof Promise ? validation.then(finish) : finish(validation);
4034
+ };
4035
+ /** Records the writes a transaction callback makes, validates them, and submits them together */
4036
+ var runTransaction = (runtime, name, callback) => {
4037
+ const id = createId();
4038
+ const recorded = [];
4039
+ callback(Object.fromEntries([...runtime.collections.keys()].map((collection) => [collection, {
4040
+ insert: (row) => recorded.push({
4041
+ collection,
4042
+ op: "insert",
4043
+ key: void 0,
4044
+ input: row
4045
+ }),
4046
+ update: (key, changes) => recorded.push({
4047
+ collection,
4048
+ op: "update",
4049
+ key,
4050
+ input: changes
4051
+ }),
4052
+ delete: (key) => recorded.push({
4053
+ collection,
4054
+ op: "delete",
4055
+ key,
4056
+ input: {}
4057
+ })
4058
+ }])));
4059
+ const fail = (error) => runtime.mutations.reject(error, id);
4060
+ const writes = recorded.map((write) => {
4061
+ const collection = runtime.collections.get(write.collection);
4062
+ const key = write.op === "insert" ? write.input[collection.config.key] : write.key;
4063
+ return {
4064
+ collection,
4065
+ op: write.op,
4066
+ key,
4067
+ prepared: prepareWrite({
4068
+ collection,
4069
+ op: write.op,
4070
+ key,
4071
+ input: write.input
4072
+ })
4073
+ };
4074
+ });
4075
+ if (writes.some((write) => write.key === void 0 || write.key === null)) return fail(/* @__PURE__ */ new Error("An insert in a transaction needs its key, such as a UUID generated on the client"));
4076
+ const submit = (results) => {
4077
+ const invalid = results.find((result) => "issues" in result);
4078
+ if (invalid) {
4079
+ runtime.emitError({
4080
+ type: "validation",
4081
+ error: invalid.issues
4082
+ });
4083
+ return fail(invalid.issues);
4084
+ }
4085
+ return runtime.mutations.submitTransaction({
4086
+ id,
4087
+ name,
4088
+ writes: writes.map((write, index) => ({
4089
+ collection: write.collection,
4090
+ op: write.op,
4091
+ key: write.key,
4092
+ values: results[index].values
4093
+ }))
4094
+ });
4095
+ };
4096
+ const prepared = writes.map((write) => write.prepared);
4097
+ if (prepared.some((item) => item instanceof Promise)) return createTransaction(id, Promise.all(prepared).then(submit));
4098
+ return submit(prepared);
4099
+ };
4100
+ /**
4101
+ * Creates the db that queries and writes go through. The names given to it are the names on the db, as in `db.post`.
4102
+ * Requests carry their Client and listeners carry their Socket, so it needs neither.
4103
+ *
4104
+ * @example
4105
+ * const db = createDb({ post: Post, user: User });
4106
+ */
4107
+ var createDb = (collections, options) => {
4108
+ const runtime = new DbRuntime(collections, options);
4109
+ const methods = {
4110
+ ready: runtime.ready,
4111
+ clear: runtime.clear,
4112
+ destroy: runtime.destroy,
4113
+ onError: runtime.onError,
4114
+ dehydrate: runtime.dehydrate,
4115
+ inspect: runtime.inspect,
4116
+ onChange: runtime.onChange
4117
+ };
4118
+ const handles = Object.fromEntries(Object.keys(collections).map((name) => [name, new CollectionHandle(runtime, name)]));
4119
+ const transaction = (first, second) => {
4120
+ const [name, callback] = typeof first === "string" ? [first, second] : [void 0, first];
4121
+ return runTransaction(runtime, name, callback);
4122
+ };
4123
+ return {
4124
+ ...handles,
4125
+ ...methods,
4126
+ transaction
4127
+ };
4128
+ };
4129
+ //#endregion
4130
+ //#region src/graphql/connection.ts
4131
+ /**
4132
+ * Reads the rows and the next cursor of a Relay connection (`edges` / `node`), for a paginated GraphQL loader. Spread it
4133
+ * into the loader options and add `page` to send the cursor.
4134
+ *
4135
+ * @example
4136
+ * collection(PostSchema, { key: "id" }).load(getPosts, {
4137
+ * ...relayConnection((response: PostsResponse) => response.posts),
4138
+ * page: (after) => ({ payload: { after } }),
4139
+ * });
4140
+ */
4141
+ var relayConnection = (select) => ({
4142
+ rows: (response) => (select(response).edges ?? []).flatMap((edge) => edge ? [edge.node] : []),
4143
+ cursor: (response) => {
4144
+ const { pageInfo } = select(response);
4145
+ return pageInfo.hasNextPage ? pageInfo.endCursor ?? null : null;
4146
+ }
4147
+ });
4148
+ //#endregion
4149
+ //#region src/operators/operators.ts
4150
+ var comparison = (op, ref, value) => {
4151
+ return {
4152
+ kind: "condition",
4153
+ node: {
4154
+ op,
4155
+ field: ref.field,
4156
+ value
4157
+ }
4158
+ };
4159
+ };
4160
+ /** Matches rows whose field equals the value. Dates are equal when they are the same instant. */
4161
+ var eq = (ref, value) => comparison("eq", ref, value);
4162
+ /** Matches rows whose field is greater than the value */
4163
+ var gt = (ref, value) => comparison("gt", ref, value);
4164
+ /** Matches rows whose field is greater than or equal to the value */
4165
+ var gte = (ref, value) => comparison("gte", ref, value);
4166
+ /** Matches rows whose field is less than the value */
4167
+ var lt = (ref, value) => comparison("lt", ref, value);
4168
+ /** Matches rows whose field is less than or equal to the value */
4169
+ var lte = (ref, value) => comparison("lte", ref, value);
4170
+ /** Matches rows whose field equals one of the values */
4171
+ var inArray = (ref, values) => comparison("inArray", ref, values);
4172
+ /**
4173
+ * A server-only operator, such as full-text search, which has no meaning on the client. A loader maps it under its
4174
+ * name like any operator, as in `title: { search: (text: string) => ({ queryParams: { q: text } }) }`. A query that
4175
+ * uses one must send it, or it does not compile. Its subset never answers other queries, and new rows never join it:
4176
+ * an insert marks it stale instead.
4177
+ *
4178
+ * @example
4179
+ * db.post.where((post) => op("search", post.title, "tea"));
4180
+ */
4181
+ var op = (name, ref, value) => ({
4182
+ kind: "condition",
4183
+ node: {
4184
+ op: "server",
4185
+ name,
4186
+ field: ref.field,
4187
+ value
4188
+ }
4189
+ });
4190
+ /**
4191
+ * Matches rows that match every condition. Top-level `and` is where the db splits a query: the conditions a loader
4192
+ * declares are sent to the backend and the rest run on the rows the db holds.
4193
+ */
4194
+ var and = (...conditions) => ({
4195
+ kind: "condition",
4196
+ node: {
4197
+ op: "and",
4198
+ items: conditions.map((condition) => condition.node)
4199
+ }
4200
+ });
4201
+ /** Matches rows that match at least one condition. It runs on the rows the db holds. */
4202
+ var or = (...conditions) => ({
4203
+ kind: "condition",
4204
+ node: {
4205
+ op: "or",
4206
+ items: conditions.map((condition) => condition.node)
4207
+ }
4208
+ });
4209
+ /** Matches rows that do not match the condition. It runs on the rows the db holds. */
4210
+ var not = (condition) => ({
4211
+ kind: "condition",
4212
+ node: {
4213
+ op: "not",
4214
+ item: condition.node
4215
+ }
4216
+ });
4217
+ //#endregion
4218
+ export { Collection, CollectionHandle, DependencyError, InfiniteQuery, MutationEngine, Query, and, collection, createDb, createSerializer, createTransaction, eq, gt, gte, inArray, isTemporaryFailure, lt, lte, not, op, or, relayConnection, rowType };
4219
+
4220
+ //# sourceMappingURL=index.mjs.map