@signaldb/svelte 2.0.0-beta.21 → 2.0.0-beta.22

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 (105) hide show
  1. package/package.json +3 -3
  2. package/dist/base/core/src/AsyncDataAdapter.d.ts +0 -112
  3. package/dist/base/core/src/AsyncDataAdapter.js +0 -549
  4. package/dist/base/core/src/AutoFetchDataAdapter.d.ts +0 -112
  5. package/dist/base/core/src/AutoFetchDataAdapter.js +0 -612
  6. package/dist/base/core/src/Collection/Cursor.d.ts +0 -165
  7. package/dist/base/core/src/Collection/Cursor.js +0 -352
  8. package/dist/base/core/src/Collection/Observer.d.ts +0 -95
  9. package/dist/base/core/src/Collection/Observer.js +0 -227
  10. package/dist/base/core/src/Collection/index.d.ts +0 -341
  11. package/dist/base/core/src/Collection/index.js +0 -761
  12. package/dist/base/core/src/Collection/types.d.ts +0 -28
  13. package/dist/base/core/src/Collection/types.js +0 -2
  14. package/dist/base/core/src/DataAdapter.d.ts +0 -54
  15. package/dist/base/core/src/DataAdapter.js +0 -2
  16. package/dist/base/core/src/DefaultDataAdapter.d.ts +0 -35
  17. package/dist/base/core/src/DefaultDataAdapter.js +0 -408
  18. package/dist/base/core/src/WorkerDataAdapter.d.ts +0 -79
  19. package/dist/base/core/src/WorkerDataAdapter.js +0 -749
  20. package/dist/base/core/src/WorkerDataAdapterHost.d.ts +0 -64
  21. package/dist/base/core/src/WorkerDataAdapterHost.js +0 -430
  22. package/dist/base/core/src/createIndex.d.ts +0 -7
  23. package/dist/base/core/src/createIndex.js +0 -120
  24. package/dist/base/core/src/createIndexProvider.d.ts +0 -8
  25. package/dist/base/core/src/createIndexProvider.js +0 -11
  26. package/dist/base/core/src/createReactivityAdapter.d.ts +0 -8
  27. package/dist/base/core/src/createReactivityAdapter.js +0 -11
  28. package/dist/base/core/src/createStorageAdapter.d.ts +0 -9
  29. package/dist/base/core/src/createStorageAdapter.js +0 -11
  30. package/dist/base/core/src/getIndexInfo.d.ts +0 -39
  31. package/dist/base/core/src/getIndexInfo.js +0 -188
  32. package/dist/base/core/src/index.d.ts +0 -26
  33. package/dist/base/core/src/index.js +0 -39
  34. package/dist/base/core/src/types/Dependency.d.ts +0 -4
  35. package/dist/base/core/src/types/Dependency.js +0 -2
  36. package/dist/base/core/src/types/IndexProvider.d.ts +0 -26
  37. package/dist/base/core/src/types/IndexProvider.js +0 -2
  38. package/dist/base/core/src/types/Modifier.d.ts +0 -46
  39. package/dist/base/core/src/types/Modifier.js +0 -3
  40. package/dist/base/core/src/types/ReactivityAdapter.d.ts +0 -6
  41. package/dist/base/core/src/types/ReactivityAdapter.js +0 -2
  42. package/dist/base/core/src/types/Selector.d.ts +0 -46
  43. package/dist/base/core/src/types/Selector.js +0 -3
  44. package/dist/base/core/src/types/Signal.d.ts +0 -4
  45. package/dist/base/core/src/types/Signal.js +0 -2
  46. package/dist/base/core/src/types/StorageAdapter.d.ts +0 -28
  47. package/dist/base/core/src/types/StorageAdapter.js +0 -2
  48. package/dist/base/core/src/utils/EventEmitter.d.ts +0 -71
  49. package/dist/base/core/src/utils/EventEmitter.js +0 -144
  50. package/dist/base/core/src/utils/applyQueryOptions.d.ts +0 -15
  51. package/dist/base/core/src/utils/applyQueryOptions.js +0 -36
  52. package/dist/base/core/src/utils/batchOnNextTick.d.ts +0 -16
  53. package/dist/base/core/src/utils/batchOnNextTick.js +0 -72
  54. package/dist/base/core/src/utils/compact.d.ts +0 -9
  55. package/dist/base/core/src/utils/compact.js +0 -21
  56. package/dist/base/core/src/utils/createSignal.d.ts +0 -14
  57. package/dist/base/core/src/utils/createSignal.js +0 -38
  58. package/dist/base/core/src/utils/deepClone.d.ts +0 -17
  59. package/dist/base/core/src/utils/deepClone.js +0 -68
  60. package/dist/base/core/src/utils/get.d.ts +0 -9
  61. package/dist/base/core/src/utils/get.js +0 -27
  62. package/dist/base/core/src/utils/getMatchingKeys.d.ts +0 -19
  63. package/dist/base/core/src/utils/getMatchingKeys.js +0 -49
  64. package/dist/base/core/src/utils/idIndexQuery.d.ts +0 -20
  65. package/dist/base/core/src/utils/idIndexQuery.js +0 -49
  66. package/dist/base/core/src/utils/incrementalQueryUpdate.d.ts +0 -62
  67. package/dist/base/core/src/utils/incrementalQueryUpdate.js +0 -197
  68. package/dist/base/core/src/utils/intersection.d.ts +0 -9
  69. package/dist/base/core/src/utils/intersection.js +0 -16
  70. package/dist/base/core/src/utils/isEqual.d.ts +0 -14
  71. package/dist/base/core/src/utils/isEqual.js +0 -43
  72. package/dist/base/core/src/utils/isFieldExpression.d.ts +0 -11
  73. package/dist/base/core/src/utils/isFieldExpression.js +0 -52
  74. package/dist/base/core/src/utils/match.d.ts +0 -12
  75. package/dist/base/core/src/utils/match.js +0 -16
  76. package/dist/base/core/src/utils/modify.d.ts +0 -14
  77. package/dist/base/core/src/utils/modify.js +0 -29
  78. package/dist/base/core/src/utils/project.d.ts +0 -15
  79. package/dist/base/core/src/utils/project.js +0 -43
  80. package/dist/base/core/src/utils/projectItems.d.ts +0 -12
  81. package/dist/base/core/src/utils/projectItems.js +0 -25
  82. package/dist/base/core/src/utils/queryDelta.d.ts +0 -83
  83. package/dist/base/core/src/utils/queryDelta.js +0 -231
  84. package/dist/base/core/src/utils/queryId.d.ts +0 -9
  85. package/dist/base/core/src/utils/queryId.js +0 -61
  86. package/dist/base/core/src/utils/randomId.d.ts +0 -7
  87. package/dist/base/core/src/utils/randomId.js +0 -12
  88. package/dist/base/core/src/utils/reactiveOrAsync.d.ts +0 -59
  89. package/dist/base/core/src/utils/reactiveOrAsync.js +0 -93
  90. package/dist/base/core/src/utils/serializeValue.d.ts +0 -12
  91. package/dist/base/core/src/utils/serializeValue.js +0 -27
  92. package/dist/base/core/src/utils/set.d.ts +0 -13
  93. package/dist/base/core/src/utils/set.js +0 -43
  94. package/dist/base/core/src/utils/sortItems.d.ts +0 -12
  95. package/dist/base/core/src/utils/sortItems.js +0 -23
  96. package/dist/base/core/src/utils/storageIndexQuery.d.ts +0 -20
  97. package/dist/base/core/src/utils/storageIndexQuery.js +0 -75
  98. package/dist/base/core/src/utils/uniqueBy.d.ts +0 -10
  99. package/dist/base/core/src/utils/uniqueBy.js +0 -19
  100. package/dist/index.cjs +0 -38
  101. package/dist/index.cjs.map +0 -1
  102. package/dist/index.mjs +0 -38
  103. package/dist/index.mjs.map +0 -1
  104. package/dist/reactivity-adapters/svelte/index.svelte.d.ts +0 -10
  105. package/dist/reactivity-adapters/svelte/index.svelte.js +0 -36
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@signaldb/svelte",
3
3
  "type": "module",
4
- "version": "2.0.0-beta.21",
4
+ "version": "2.0.0-beta.22",
5
5
  "scripts": {
6
6
  "build": "tsc -d --noEmit false",
7
7
  "analyze-bundle": "bundle-analyzer ./dist --upload-token=$BUNDLE_ANALYZER_UPLOAD_TOKEN --bundle-name=@signaldb/svelte",
@@ -45,7 +45,7 @@
45
45
  "svelte": "^5.7.0"
46
46
  },
47
47
  "devDependencies": {
48
- "@sveltejs/vite-plugin-svelte": "7.1.2",
49
- "svelte": "5.56.1"
48
+ "@sveltejs/vite-plugin-svelte": "7.3.0",
49
+ "svelte": "5.57.0"
50
50
  }
51
51
  }
@@ -1,112 +0,0 @@
1
- import type { BaseItem } from './Collection';
2
- import type Collection from './Collection';
3
- import type DataAdapter from './DataAdapter';
4
- import type { CollectionBackend } from './DataAdapter';
5
- import type StorageAdapter from './types/StorageAdapter';
6
- export interface AsyncDataAdapterOptions {
7
- /** Factory to obtain a StorageAdapter per collection name */
8
- storage: (name: string) => StorageAdapter<any, any>;
9
- /** Optional logical id (handy if you run multiple adapters side-by-side) */
10
- id?: string;
11
- /** Optional error hook (mirrors WorkerDataAdapterHost) */
12
- onError?: (error: Error) => void;
13
- /**
14
- * How often a failing query is retried before it is published as `'error'`.
15
- * A query that fails is otherwise a dead end for the rest of the session —
16
- * cursors only requery on `'complete'`, so they keep serving their neutral
17
- * empty value, which consumers cannot tell apart from "there is no data".
18
- */
19
- retry?: {
20
- /** Total attempts including the first one. Default 3. */
21
- attempts?: number;
22
- /** Delay in ms before attempt N+1. Default 100 * 4 ** (attempt - 1). */
23
- delay?: (attempt: number) => number;
24
- };
25
- }
26
- /**
27
- * Carries the context needed to act on a failed query. The bare storage error
28
- * on its own does not say which collection or selector produced it, which made
29
- * the default `console.error` hook close to useless.
30
- */
31
- export declare class QueryError extends Error {
32
- readonly collectionName: string;
33
- readonly selector: unknown;
34
- readonly options: unknown;
35
- readonly attempts: number;
36
- constructor(collectionName: string, selector: unknown, options: unknown, attempts: number, cause: unknown);
37
- }
38
- /**
39
- * AsyncDataAdapter
40
- * Combines WorkerDataAdapter + WorkerDataAdapterHost into a single, transport-free adapter.
41
- * - Keeps the DataAdapter/CollectionBackend surface identical to the Worker version.
42
- * - Executes queries and mutations directly against the provided StorageAdapter.
43
- * - Preserves index-aware query optimization and push-style query updates to listeners.
44
- */
45
- export default class AsyncDataAdapter implements DataAdapter {
46
- private options;
47
- private id;
48
- private onError;
49
- private retryAttempts;
50
- private retryDelay;
51
- private storageAdapters;
52
- private storageAdapterReady;
53
- private collectionIndices;
54
- private queries;
55
- constructor(options: AsyncDataAdapterOptions);
56
- createCollectionBackend<T extends BaseItem<I>, I = any, E extends BaseItem = T, U = E>(collection: Collection<T, I, E, U>, indices: string[]): CollectionBackend<T, I>;
57
- private setupStorage;
58
- private ensureStorageAdapter;
59
- /**
60
- * Compute and publish the result for a specific query
61
- * @param collectionName - name of the collection
62
- * @param selector - query selector
63
- * @param options - query options
64
- */
65
- private fulfillQuery;
66
- /**
67
- * Executes a query, retrying transient failures before giving up. The state
68
- * stays `'active'` across retries — consumers should see "still loading",
69
- * not "failed", until we actually stop trying. Only the final failure is
70
- * published as `'error'` and reported through `onError`; previously that
71
- * error was swallowed entirely (`fulfillQuery` caught it internally, so the
72
- * `.catch(this.onError)` on its call site was unreachable) and the query
73
- * stayed dead for the rest of the session.
74
- * @param collectionName - name of the collection
75
- * @param selector - query selector
76
- * @param options - query options
77
- */
78
- private runQuery;
79
- /**
80
- * Notify listeners about state changes and keep the cache updated
81
- * @param collectionName - name of the collection
82
- * @param qid - query id
83
- * @param state - new state
84
- * @param error - error if state is 'error', null otherwise
85
- * @param delta - what changed about the result, when that is known
86
- */
87
- private publishState;
88
- private publishResult;
89
- private queryItemIds;
90
- private getIndexInfo;
91
- private queryItems;
92
- private executeQuery;
93
- /**
94
- * After mutations, bring every affected active query up to date.
95
- *
96
- * A query whose previous result is enough to answer the change is brought up to date from that
97
- * result alone — no round trip to the storage, and no detour through `'active'`, because there is
98
- * no window in which the query is stale. Only a query the change cannot be reasoned about
99
- * locally — a window onto a larger set, or one that has never been answered — goes back to the
100
- * store, and that one gets the same retry and reporting behaviour a freshly registered query
101
- * gets: a refresh that fails silently leaves exactly the same dead cursor.
102
- * @param collectionName - name of the collection
103
- * @param changes - the items the write created, updated or removed
104
- */
105
- private checkQueryUpdates;
106
- private insert;
107
- private updateOne;
108
- private updateMany;
109
- private replaceOne;
110
- private removeOne;
111
- private removeMany;
112
- }
@@ -1,549 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.QueryError = void 0;
7
- const deepClone_1 = __importDefault(require("./utils/deepClone"));
8
- const match_1 = __importDefault(require("./utils/match"));
9
- const modify_1 = __importDefault(require("./utils/modify"));
10
- const queryId_1 = __importDefault(require("./utils/queryId"));
11
- const isEqual_1 = __importDefault(require("./utils/isEqual"));
12
- const getIndexInfo_1 = __importDefault(require("./getIndexInfo"));
13
- const storageIndexQuery_1 = __importDefault(require("./utils/storageIndexQuery"));
14
- const idIndexQuery_1 = __importDefault(require("./utils/idIndexQuery"));
15
- const sortItems_1 = __importDefault(require("./utils/sortItems"));
16
- const projectItems_1 = __importDefault(require("./utils/projectItems"));
17
- const incrementalQueryUpdate_1 = __importDefault(require("./utils/incrementalQueryUpdate"));
18
- const queryDelta_1 = require("./utils/queryDelta");
19
- /**
20
- * Carries the context needed to act on a failed query. The bare storage error
21
- * on its own does not say which collection or selector produced it, which made
22
- * the default `console.error` hook close to useless.
23
- */
24
- class QueryError extends Error {
25
- collectionName;
26
- selector;
27
- options;
28
- attempts;
29
- constructor(collectionName, selector, options, attempts, cause) {
30
- const reason = cause instanceof Error ? cause.message : String(cause);
31
- super(`Query on "${collectionName}" failed after ${attempts} attempt(s): ${reason}`);
32
- this.name = 'QueryError';
33
- this.collectionName = collectionName;
34
- this.selector = selector;
35
- this.options = options;
36
- this.attempts = attempts;
37
- this.cause = cause;
38
- }
39
- }
40
- exports.QueryError = QueryError;
41
- /**
42
- * Turns the item states a write produced into the upsert/delete split a query update needs.
43
- *
44
- * The two lists are not symmetric: an item that is still there after the write is described by its
45
- * new state, while an item that is gone — removed, or given a new id — is described by the id it
46
- * used to have and nothing else. Mixing the states from before and after a write into one list
47
- * loses exactly that distinction.
48
- * @template T - The type of the items.
49
- * @param previousItems - The items as they were before the write.
50
- * @param modifiedItems - The items as they are after it.
51
- * @returns The changeset describing the write.
52
- */
53
- function toChangeset(previousItems, modifiedItems) {
54
- const modifiedIds = new Set(modifiedItems.map(item => item.id));
55
- return {
56
- upserts: modifiedItems,
57
- deletes: previousItems
58
- .map(item => item.id)
59
- .filter(id => !modifiedIds.has(id)),
60
- };
61
- }
62
- const DEFAULT_RETRY_ATTEMPTS = 3;
63
- const defaultRetryDelay = (attempt) => 100 * (4 ** (attempt - 1));
64
- const wait = (ms) => new Promise((resolve) => {
65
- setTimeout(resolve, ms);
66
- });
67
- /**
68
- * AsyncDataAdapter
69
- * Combines WorkerDataAdapter + WorkerDataAdapterHost into a single, transport-free adapter.
70
- * - Keeps the DataAdapter/CollectionBackend surface identical to the Worker version.
71
- * - Executes queries and mutations directly against the provided StorageAdapter.
72
- * - Preserves index-aware query optimization and push-style query updates to listeners.
73
- */
74
- class AsyncDataAdapter {
75
- options;
76
- id;
77
- onError;
78
- retryAttempts;
79
- retryDelay;
80
- // Per-collection resources
81
- storageAdapters = new Map();
82
- storageAdapterReady = new Map();
83
- collectionIndices = new Map();
84
- // Per-collection query registries
85
- queries = new Map();
86
- constructor(options) {
87
- this.options = options;
88
- this.id = options.id || 'async-data-adapter';
89
- this.onError = options.onError ?? ((error) => {
90
- /* eslint-disable no-console */ console.error(error);
91
- });
92
- this.retryAttempts = Math.max(1, options.retry?.attempts ?? DEFAULT_RETRY_ATTEMPTS);
93
- this.retryDelay = options.retry?.delay ?? defaultRetryDelay;
94
- }
95
- createCollectionBackend(collection, indices) {
96
- // init per-collection state
97
- this.collectionIndices.set(collection.name, indices);
98
- this.queries.set(collection.name, new Map());
99
- this.ensureStorageAdapter(collection.name);
100
- const ready = (async () => {
101
- try {
102
- await this.setupStorage(collection.name, indices);
103
- }
104
- catch (error) {
105
- // Handle inside the same async task to avoid unhandled rejections
106
- this.onError(error);
107
- throw error;
108
- }
109
- })();
110
- this.storageAdapterReady.set(collection.name, ready);
111
- // don't block createCollectionBackend; callers can await isReady()
112
- const registerQuery = (selector, options) => {
113
- const qid = (0, queryId_1.default)(selector, options);
114
- const registry = this.queries.get(collection.name);
115
- if (!registry)
116
- throw new Error(`Collection ${collection.name} not initialized!`);
117
- registry.set(qid, {
118
- selector,
119
- options,
120
- items: [],
121
- listeners: new Set(),
122
- ...registry.get(qid),
123
- state: 'active',
124
- error: null,
125
- });
126
- // kick async execution
127
- void this.fulfillQuery(collection.name, selector, options).catch(this.onError);
128
- };
129
- const unregisterQuery = (selector, options) => {
130
- const qid = (0, queryId_1.default)(selector, options);
131
- this.queries.get(collection.name)?.delete(qid);
132
- };
133
- const getQueryState = (selector, options) => {
134
- const q = this.queries.get(collection.name)?.get((0, queryId_1.default)(selector, options));
135
- return q?.state ?? 'active';
136
- };
137
- const getQueryError = (selector, options) => {
138
- const q = this.queries.get(collection.name)?.get((0, queryId_1.default)(selector, options));
139
- return q?.error ?? null;
140
- };
141
- const getQueryResult = (selector, options) => {
142
- const q = this.queries.get(collection.name)?.get((0, queryId_1.default)(selector, options));
143
- return q?.items ?? [];
144
- };
145
- const retryQuery = (selector, options) => {
146
- const qid = (0, queryId_1.default)(selector, options);
147
- const rec = this.queries.get(collection.name)?.get(qid);
148
- if (!rec)
149
- return;
150
- this.publishState(collection.name, qid, 'active', null);
151
- void this.runQuery(collection.name, selector, options);
152
- };
153
- const onQueryStateChange = (selector, options, callback) => {
154
- const qid = (0, queryId_1.default)(selector, options);
155
- const registry = this.queries.get(collection.name);
156
- if (!registry)
157
- throw new Error(`Collection ${collection.name} not initialized!`);
158
- // ensure the record exists so we have a listener bucket
159
- if (!registry.has(qid)) {
160
- registry.set(qid, {
161
- selector,
162
- options,
163
- state: 'active',
164
- error: null,
165
- items: [],
166
- listeners: new Set(),
167
- });
168
- }
169
- registry.get(qid)?.listeners.add(callback);
170
- // A query that has already failed would otherwise stay failed forever:
171
- // `registerQuery` only runs for the *first* cursor on a selector, so
172
- // every later observer inherited the dead state without anything ever
173
- // retrying it. A new observer is a natural moment to try again.
174
- if (registry.get(qid)?.state === 'error')
175
- retryQuery(selector, options);
176
- return () => registry.get(qid)?.listeners.delete(callback);
177
- };
178
- return {
179
- insert: async (item) => {
180
- await ready;
181
- const inserted = await this.insert(collection.name, item);
182
- return inserted;
183
- },
184
- updateOne: async (selector, modifier) => {
185
- await ready;
186
- return this.updateOne(collection.name, selector, modifier);
187
- },
188
- updateMany: async (selector, modifier) => {
189
- await ready;
190
- return this.updateMany(collection.name, selector, modifier);
191
- },
192
- replaceOne: async (selector, replacement) => {
193
- await ready;
194
- return this.replaceOne(collection.name, selector, replacement);
195
- },
196
- removeOne: async (selector) => {
197
- await ready;
198
- return this.removeOne(collection.name, selector);
199
- },
200
- removeMany: async (selector) => {
201
- await ready;
202
- return this.removeMany(collection.name, selector);
203
- },
204
- registerQuery,
205
- unregisterQuery,
206
- retryQuery,
207
- getQueryState,
208
- getQueryError,
209
- getQueryResult,
210
- onQueryStateChange,
211
- executeQuery: async (selector, options) => {
212
- await ready;
213
- return this.executeQuery(collection.name, selector, options);
214
- },
215
- dispose: async () => {
216
- // mirror host.unregisterCollection semantics
217
- this.storageAdapters.delete(collection.name);
218
- this.queries.delete(collection.name);
219
- this.collectionIndices.delete(collection.name);
220
- this.storageAdapterReady.delete(collection.name);
221
- },
222
- isReady: async () => {
223
- await ready;
224
- },
225
- };
226
- }
227
- async setupStorage(collectionName, indices) {
228
- const storage = this.storageAdapters.get(collectionName);
229
- if (!storage)
230
- throw new Error(`No persistence adapter for collection ${collectionName}`);
231
- await storage.setup();
232
- await Promise.all(indices.map(index => storage.createIndex(index)));
233
- }
234
- ensureStorageAdapter(name) {
235
- if (this.storageAdapters.has(name))
236
- return;
237
- const adapter = this.options.storage(name);
238
- if (!adapter)
239
- return;
240
- this.storageAdapters.set(name, adapter);
241
- }
242
- /**
243
- * Compute and publish the result for a specific query
244
- * @param collectionName - name of the collection
245
- * @param selector - query selector
246
- * @param options - query options
247
- */
248
- async fulfillQuery(collectionName, selector, options) {
249
- const qid = (0, queryId_1.default)(selector, options);
250
- const registry = this.queries.get(collectionName);
251
- if (!registry)
252
- throw new Error(`Collection ${collectionName} not initialized!`);
253
- const rec = registry.get(qid);
254
- if (!rec)
255
- return;
256
- this.publishState(collectionName, qid, 'active', null);
257
- await this.runQuery(collectionName, selector, options);
258
- }
259
- /**
260
- * Executes a query, retrying transient failures before giving up. The state
261
- * stays `'active'` across retries — consumers should see "still loading",
262
- * not "failed", until we actually stop trying. Only the final failure is
263
- * published as `'error'` and reported through `onError`; previously that
264
- * error was swallowed entirely (`fulfillQuery` caught it internally, so the
265
- * `.catch(this.onError)` on its call site was unreachable) and the query
266
- * stayed dead for the rest of the session.
267
- * @param collectionName - name of the collection
268
- * @param selector - query selector
269
- * @param options - query options
270
- */
271
- async runQuery(collectionName, selector, options) {
272
- const qid = (0, queryId_1.default)(selector, options);
273
- let lastError;
274
- for (let attempt = 1; attempt <= this.retryAttempts; attempt += 1) {
275
- // The query can be unregistered while a retry is waiting — dropping out
276
- // here keeps a disposed cursor from resurrecting its record.
277
- if (!this.queries.get(collectionName)?.has(qid))
278
- return;
279
- try {
280
- const items = await this.executeQuery(collectionName, selector, options);
281
- const rec = this.queries.get(collectionName)?.get(qid);
282
- // A query answered for the first time has no previous result to be relative to; whoever is
283
- // waiting on it holds nothing yet and needs the whole thing.
284
- const delta = rec?.answered
285
- ? (0, queryDelta_1.diffQueryResults)(rec.items, items)
286
- : undefined;
287
- this.publishResult(collectionName, qid, items);
288
- this.publishState(collectionName, qid, 'complete', null, delta);
289
- return;
290
- }
291
- catch (error) {
292
- lastError = error;
293
- if (attempt < this.retryAttempts)
294
- await wait(this.retryDelay(attempt));
295
- }
296
- }
297
- const queryError = new QueryError(collectionName, selector, options, this.retryAttempts, lastError);
298
- this.publishState(collectionName, qid, 'error', queryError);
299
- this.onError(queryError);
300
- }
301
- /**
302
- * Notify listeners about state changes and keep the cache updated
303
- * @param collectionName - name of the collection
304
- * @param qid - query id
305
- * @param state - new state
306
- * @param error - error if state is 'error', null otherwise
307
- * @param delta - what changed about the result, when that is known
308
- */
309
- publishState(collectionName, qid, state, error, delta) {
310
- const rec = this.queries.get(collectionName)?.get(qid);
311
- if (!rec)
312
- return;
313
- rec.state = state;
314
- rec.error = error;
315
- // Notify over a snapshot, never the live set: a subscriber is free to
316
- // resubscribe from inside its own callback — a reactive scope that reads
317
- // the query state does exactly that when it re-runs — and `Set` iteration
318
- // visits entries added while it is still running, so notifying in place
319
- // turns one state change into an unbounded loop.
320
- const subscribers = [...rec.listeners];
321
- for (const callback of subscribers) {
322
- try {
323
- (0, queryDelta_1.callWithDelta)(callback, state, delta);
324
- }
325
- catch (error_) {
326
- this.onError(error_);
327
- }
328
- }
329
- }
330
- publishResult(collectionName, qid, items) {
331
- const rec = this.queries.get(collectionName)?.get(qid);
332
- if (!rec)
333
- return;
334
- rec.items = items;
335
- rec.itemIds = undefined;
336
- rec.answered = true;
337
- }
338
- queryItemIds(rec) {
339
- if (!rec.itemIds)
340
- rec.itemIds = new Set(rec.items.map(item => item.id));
341
- return rec.itemIds;
342
- }
343
- async getIndexInfo(collectionName, selector) {
344
- const storageAdapter = this.storageAdapters.get(collectionName);
345
- if (!storageAdapter)
346
- throw new Error(`No persistence adapter for collection ${collectionName}`);
347
- if (selector != null && Object.keys(selector).length === 1 && 'id' in selector) {
348
- const idResult = (0, idIndexQuery_1.default)(selector);
349
- if (idResult.matched) {
350
- return {
351
- matched: true,
352
- ids: idResult.ids.filter(Boolean),
353
- optimizedSelector: {},
354
- };
355
- }
356
- }
357
- if (selector == null) {
358
- return {
359
- matched: false,
360
- ids: [],
361
- optimizedSelector: {},
362
- };
363
- }
364
- const indices = this.collectionIndices.get(collectionName) ?? [];
365
- return (0, getIndexInfo_1.default)(indices.map(field => (0, storageIndexQuery_1.default)(storageAdapter, field)), selector);
366
- }
367
- async queryItems(collectionName, selector) {
368
- const storage = this.storageAdapters.get(collectionName);
369
- if (!storage)
370
- throw new Error(`No persistence adapter for collection ${collectionName}`);
371
- const index = await this.getIndexInfo(collectionName, selector);
372
- const matchItems = (item) => {
373
- if (index.optimizedSelector == null)
374
- return true;
375
- if (Object.keys(index.optimizedSelector).length <= 0)
376
- return true;
377
- return (0, match_1.default)(item, index.optimizedSelector);
378
- };
379
- if (index.matched) {
380
- const items = await storage.readIds(index.ids);
381
- if ((0, isEqual_1.default)(index.optimizedSelector, {}))
382
- return items;
383
- return items.filter(matchItems);
384
- }
385
- else {
386
- const allItems = await storage.readAll();
387
- if ((0, isEqual_1.default)(selector, {}))
388
- return allItems;
389
- return allItems.filter(matchItems);
390
- }
391
- }
392
- async executeQuery(collectionName, selector, options) {
393
- const items = await this.queryItems(collectionName, selector || {});
394
- const { sort, skip, limit, fields } = options || {};
395
- const sorted = sort ? (0, sortItems_1.default)(items, sort) : items;
396
- const skipped = skip ? sorted.slice(skip) : sorted;
397
- const limited = limit ? skipped.slice(0, limit) : skipped;
398
- return (0, projectItems_1.default)(limited, fields);
399
- }
400
- /**
401
- * After mutations, bring every affected active query up to date.
402
- *
403
- * A query whose previous result is enough to answer the change is brought up to date from that
404
- * result alone — no round trip to the storage, and no detour through `'active'`, because there is
405
- * no window in which the query is stale. Only a query the change cannot be reasoned about
406
- * locally — a window onto a larger set, or one that has never been answered — goes back to the
407
- * store, and that one gets the same retry and reporting behaviour a freshly registered query
408
- * gets: a refresh that fails silently leaves exactly the same dead cursor.
409
- * @param collectionName - name of the collection
410
- * @param changes - the items the write created, updated or removed
411
- */
412
- async checkQueryUpdates(collectionName, changes) {
413
- const registry = this.queries.get(collectionName);
414
- if (!registry)
415
- throw new Error(`Collection ${collectionName} not initialized!`);
416
- if (registry.size === 0)
417
- return;
418
- if (changes.upserts.length === 0 && changes.deletes.length === 0)
419
- return;
420
- // A query is affected when the write produces something it should hold, or takes away
421
- // something it already holds. The second half is what the written items cannot tell us on
422
- // their own: an item that no longer matches, or that is gone, is invisible to the matcher.
423
- const affected = [...registry.values()].filter((rec) => {
424
- const ids = this.queryItemIds(rec);
425
- if (changes.deletes.some(id => ids.has(id)))
426
- return true;
427
- return changes.upserts.some(item => ids.has(item.id) || (0, match_1.default)(item, rec.selector));
428
- });
429
- if (affected.length === 0)
430
- return;
431
- const needsReExecution = [];
432
- for (const rec of affected) {
433
- const { selector, options } = rec;
434
- const incremental = rec.answered
435
- ? (0, incrementalQueryUpdate_1.default)(rec.items, selector, options, changes)
436
- : null;
437
- if (incremental == null) {
438
- needsReExecution.push(rec);
439
- continue;
440
- }
441
- const qid = (0, queryId_1.default)(selector, options);
442
- const delta = (0, queryDelta_1.diffQueryResults)(rec.items, incremental);
443
- if ((0, queryDelta_1.isEmptyQueryDelta)(delta))
444
- continue;
445
- this.publishResult(collectionName, qid, incremental);
446
- this.publishState(collectionName, qid, 'complete', null, delta);
447
- }
448
- for (const { selector, options } of needsReExecution) {
449
- this.publishState(collectionName, (0, queryId_1.default)(selector, options), 'active', null);
450
- }
451
- await Promise.all(needsReExecution.map(({ selector, options }) => this.runQuery(collectionName, selector, options)));
452
- }
453
- async insert(collectionName, newItem) {
454
- const storage = this.storageAdapters.get(collectionName);
455
- if (!storage)
456
- throw new Error(`No persistence adapter for collection ${collectionName}`);
457
- const existingItems = await storage.readIds([newItem.id]);
458
- if (existingItems.length > 0)
459
- throw new Error(`Item with id ${String(newItem.id)} already exists`);
460
- await storage.insert([newItem]);
461
- await this.checkQueryUpdates(collectionName, { upserts: [newItem], deletes: [] });
462
- return newItem;
463
- }
464
- async updateOne(collectionName, selector, modifier) {
465
- const storage = this.storageAdapters.get(collectionName);
466
- if (!storage)
467
- throw new Error(`No persistence adapter for collection ${collectionName}`);
468
- const items = await this.executeQuery(collectionName, selector, { limit: 1 });
469
- const [item] = items;
470
- const { $setOnInsert, ...rest } = modifier;
471
- if (item == null)
472
- return [];
473
- const modified = (0, modify_1.default)((0, deepClone_1.default)(item), rest);
474
- if (item.id !== modified.id) {
475
- const existing = await storage.readIds([modified.id]);
476
- if (existing.length > 0)
477
- throw new Error(`Item with id ${String(modified.id)} already exists`);
478
- }
479
- await storage.replace([modified]);
480
- await this.checkQueryUpdates(collectionName, toChangeset([item], [modified]));
481
- return [modified];
482
- }
483
- async updateMany(collectionName, selector, modifier) {
484
- const storage = this.storageAdapters.get(collectionName);
485
- if (!storage)
486
- throw new Error(`No persistence adapter for collection ${collectionName}`);
487
- const items = await this.executeQuery(collectionName, selector);
488
- if (items.length === 0)
489
- return [];
490
- const { $setOnInsert, ...rest } = modifier;
491
- const changed = await Promise.all(items.map(async (item) => {
492
- const modified = (0, modify_1.default)((0, deepClone_1.default)(item), rest);
493
- if (item.id !== modified.id) {
494
- const existing = await storage.readIds([modified.id]);
495
- if (existing.length > 0)
496
- throw new Error(`Item with id ${String(modified.id)} already exists`);
497
- }
498
- return modified;
499
- }));
500
- await storage.replace(changed);
501
- await this.checkQueryUpdates(collectionName, toChangeset(items, changed));
502
- return changed;
503
- }
504
- async replaceOne(collectionName, selector, replacement) {
505
- const storage = this.storageAdapters.get(collectionName);
506
- if (!storage)
507
- throw new Error(`No persistence adapter for collection ${collectionName}`);
508
- const items = await this.executeQuery(collectionName, selector, { limit: 1 });
509
- const [item] = items;
510
- if (item == null)
511
- return [];
512
- const modified = { ...replacement, id: replacement.id ?? item.id };
513
- if (item.id !== modified.id) {
514
- const existing = await storage.readIds([modified.id]);
515
- if (existing.length > 0)
516
- throw new Error(`Item with id ${String(modified.id)} already exists`);
517
- }
518
- await storage.replace([modified]);
519
- await this.checkQueryUpdates(collectionName, toChangeset([item], [modified]));
520
- return [modified];
521
- }
522
- async removeOne(collectionName, selector) {
523
- const storage = this.storageAdapters.get(collectionName);
524
- if (!storage)
525
- throw new Error(`No persistence adapter for collection ${collectionName}`);
526
- const items = await this.executeQuery(collectionName, selector, { limit: 1 });
527
- const [item] = items;
528
- if (item == null)
529
- return [];
530
- await storage.remove([item]);
531
- await this.checkQueryUpdates(collectionName, { upserts: [], deletes: [item.id] });
532
- return [item];
533
- }
534
- async removeMany(collectionName, selector) {
535
- const storage = this.storageAdapters.get(collectionName);
536
- if (!storage)
537
- throw new Error(`No persistence adapter for collection ${collectionName}`);
538
- const items = await this.executeQuery(collectionName, selector);
539
- if (items.length === 0)
540
- return [];
541
- await storage.remove(items);
542
- await this.checkQueryUpdates(collectionName, {
543
- upserts: [],
544
- deletes: items.map(item => item.id),
545
- });
546
- return items;
547
- }
548
- }
549
- exports.default = AsyncDataAdapter;