@tech4good/platform-data 0.1.0-alpha.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.
@@ -0,0 +1,2190 @@
1
+ import * as i0 from '@angular/core';
2
+ import { InjectionToken, makeEnvironmentProviders, DestroyRef, effect, untracked, computed, Inject, Injectable, inject } from '@angular/core';
3
+ import { EMPTY, Subject, Observable } from 'rxjs';
4
+ import { signalStoreFeature, withMethods, patchState } from '@ngrx/signals';
5
+ import { withEntities, setEntities, removeEntities, removeEntity, setEntity, updateEntity, setAllEntities } from '@ngrx/signals/entities';
6
+ import { map, startWith, pairwise, filter, mergeMap, take, share, takeUntil } from 'rxjs/operators';
7
+ import { NOOP_LOGGER, injectLogger } from '@tech4good/platform-logging';
8
+
9
+ /**
10
+ * Declare an entity for t4g-entities to discover; this does not create a database
11
+ * collection or register Angular providers. Export a top-level const with a
12
+ * literal collection name so discovery can read it without executing app code.
13
+ *
14
+ * @example
15
+ * export const problemEntity = defineEntity<Problem>({ collection: 'problems' });
16
+ */
17
+ function defineEntity(definition) {
18
+ const name = definition.collection;
19
+ if (!name || name.trim() !== name || name.includes('/') || name === '.' || name === '..' || /^__.*__$/.test(name)) {
20
+ throw new Error(`Invalid entity collection name: ${JSON.stringify(name)}`);
21
+ }
22
+ return Object.freeze({ collection: name });
23
+ }
24
+
25
+ /**
26
+ * Construct an immutable value from already-normalized parts; out-of-range
27
+ * nanoseconds are rejected, not carried into seconds. Negative instants use
28
+ * negative seconds and positive nanoseconds: (-1, 500000000) is 0.5s before epoch.
29
+ */
30
+ function dataTimestamp(seconds, nanoseconds = 0) {
31
+ if (!Number.isSafeInteger(seconds) || !Number.isInteger(nanoseconds) || nanoseconds < 0 || nanoseconds >= 1e9) {
32
+ throw new RangeError('A DataTimestamp requires safe integer seconds and nanoseconds from 0 to 999999999.');
33
+ }
34
+ return Object.freeze({ __type: 'DataTimestamp', seconds: seconds === 0 ? 0 : seconds, nanoseconds: nanoseconds === 0 ? 0 : nanoseconds });
35
+ }
36
+ /** Validate the marker and numeric parts, including values read back from JSON. */
37
+ function isDataTimestamp(value) {
38
+ if (!value || typeof value !== 'object')
39
+ return false;
40
+ const timestamp = value;
41
+ return timestamp.__type === 'DataTimestamp' && Number.isSafeInteger(timestamp.seconds) &&
42
+ Number.isInteger(timestamp.nanoseconds) && timestamp.nanoseconds >= 0 && timestamp.nanoseconds < 1e9;
43
+ }
44
+ /** Millisecond input is rounded to the nearest nanosecond; use dataTimestamp for exact values. */
45
+ function dataTimestampFromMillis(milliseconds) {
46
+ if (!Number.isFinite(milliseconds))
47
+ throw new RangeError('Timestamp milliseconds must be finite.');
48
+ const seconds = Math.floor(milliseconds / 1000);
49
+ const nanoseconds = Math.round((milliseconds - seconds * 1000) * 1e6);
50
+ return nanoseconds === 1e9 ? dataTimestamp(seconds + 1) : dataTimestamp(seconds, nanoseconds);
51
+ }
52
+ /** Local clock estimate for optimistic records; database adapters own authoritative write times. */
53
+ function dataTimestampNow() { return dataTimestampFromMillis(Date.now()); }
54
+ /** Convert a valid Date; its timezone display does not change the represented instant. */
55
+ function dataTimestampFromDate(date) { return dataTimestampFromMillis(date.getTime()); }
56
+ /** Potentially lossy numeric conversion, intended for display and the existing load-time clock. */
57
+ function dataTimestampToMillis(value) {
58
+ return value.seconds * 1000 + value.nanoseconds / 1e6;
59
+ }
60
+ /** Millisecond display conversion. Do not use this to round-trip database timestamps. */
61
+ function dataTimestampToDate(value) {
62
+ const date = new Date(dataTimestampToMillis(value));
63
+ if (!Number.isFinite(date.getTime()))
64
+ throw new RangeError('Timestamp is outside the JavaScript Date range.');
65
+ return date;
66
+ }
67
+ /** Exact chronological comparison without floating-point epoch conversion. */
68
+ function compareDataTimestamps(a, b) {
69
+ return a.seconds === b.seconds ? Math.sign(a.nanoseconds - b.nanoseconds) : a.seconds < b.seconds ? -1 : 1;
70
+ }
71
+ /** Compare timestamp values rather than object identity; matching null/undefined also compare equal. */
72
+ function dataTimestampEquals(a, b) {
73
+ return a === b || (isDataTimestamp(a) && isDataTimestamp(b) && a.seconds === b.seconds && a.nanoseconds === b.nanoseconds);
74
+ }
75
+
76
+ /** Provide the selected adapter here; core stores never inject a backend SDK. */
77
+ const DATA_ACCESS = new InjectionToken('PlatformDataAccess');
78
+ /** Compatibility alias; this is the same token, not another provider. */
79
+ const DATABASE_SERVICE = DATA_ACCESS;
80
+
81
+ /** Silent default: writes still work, but no notification or undo action is presented. */
82
+ const NOOP_DATA_FEEDBACK = {
83
+ open: () => ({ onAction: () => EMPTY }),
84
+ };
85
+ const DATA_FEEDBACK = new InjectionToken('PlatformDataFeedback', {
86
+ providedIn: 'root', factory: () => NOOP_DATA_FEEDBACK,
87
+ });
88
+
89
+ /**
90
+ * Configure write feedback in the application's providers. App-wide diagnostic
91
+ * logging is configured separately with providePlatformLogging from platform-logging.
92
+ * This does not select a database: also provide a DATA_ACCESS adapter and a
93
+ * matching batch service, using provideFirestoreData or provideMockData.
94
+ */
95
+ function providePlatformData(options = {}) {
96
+ return makeEnvironmentProviders([
97
+ ...(options.feedback ? [{ provide: DATA_FEEDBACK, useValue: options.feedback }] : []),
98
+ ]);
99
+ }
100
+
101
+ /** Read dotted field paths; local __name__ queries refer to the record's __id. */
102
+ function fieldValue(entity, path) {
103
+ if (path === '__name__')
104
+ return entity.__id;
105
+ return path.split('.').reduce((value, key) => value?.[key], entity);
106
+ }
107
+ /** Compare objects by their contents and preserve types when building cache keys. */
108
+ function canonical(value) {
109
+ if (value === undefined)
110
+ return ['undefined'];
111
+ if (value === null)
112
+ return ['null'];
113
+ if (typeof value === 'number')
114
+ return ['number', String(value)];
115
+ if (typeof value !== 'object')
116
+ return [typeof value, value];
117
+ if (value instanceof Date)
118
+ return ['date', value.toISOString()];
119
+ if (isDataTimestamp(value)) {
120
+ return ['timestamp', value.seconds, value.nanoseconds];
121
+ }
122
+ if (Array.isArray(value))
123
+ return ['array', value.map(canonical)];
124
+ return ['object', Object.keys(value).sort().map(key => [key, canonical(value[key])])];
125
+ }
126
+ /** Stable, type-preserving keys; never mutates a query supplied by the app. */
127
+ function stableQueryKey(collection, params = [], options = {}) {
128
+ return JSON.stringify([collection, params.map(param => JSON.stringify(canonical(param))).sort(), canonical(options ?? {})]);
129
+ }
130
+ /** Separately created timestamps, arrays and objects can still have equal values. */
131
+ function equals(a, b) {
132
+ return Object.is(a, b) || JSON.stringify(canonical(a)) === JSON.stringify(canonical(b));
133
+ }
134
+ /** Order different supported types consistently, without JavaScript's type coercion. */
135
+ function valueRank(value) {
136
+ if (value === null)
137
+ return 0;
138
+ if (typeof value === 'boolean')
139
+ return 1;
140
+ if (typeof value === 'number')
141
+ return 2;
142
+ if (value instanceof Date || isDataTimestamp(value))
143
+ return 3;
144
+ if (typeof value === 'string')
145
+ return 4;
146
+ if (Array.isArray(value))
147
+ return 5;
148
+ if (value && Object.getPrototypeOf(value) === Object.prototype)
149
+ return 6;
150
+ throw new Error('Unsupported local ordering value; validate this query with the configured data adapter.');
151
+ }
152
+ /** Sort by type first, then by value; timestamps keep their nanosecond precision. */
153
+ function compare(a, b) {
154
+ if (equals(a, b))
155
+ return 0;
156
+ const aRank = valueRank(a);
157
+ const bRank = valueRank(b);
158
+ if (aRank !== bRank)
159
+ return Math.sign(aRank - bRank);
160
+ if (aRank === 2) {
161
+ if (Number.isNaN(a))
162
+ return -1;
163
+ if (Number.isNaN(b))
164
+ return 1;
165
+ return a < b ? -1 : a > b ? 1 : 0;
166
+ }
167
+ if (aRank === 3) {
168
+ // Compare whole seconds, then the fraction within that second. Date has only
169
+ // millisecond precision; a shared timestamp can represent finer differences.
170
+ const tuple = (v) => v instanceof Date ? [Math.floor(v.getTime() / 1000), (v.getTime() % 1000 + 1000) % 1000 * 1e6] : [v.seconds, v.nanoseconds];
171
+ const [as, an] = tuple(a);
172
+ const [bs, bn] = tuple(b);
173
+ return as === bs ? Math.sign(an - bn) : Math.sign(as - bs);
174
+ }
175
+ if (aRank === 5) {
176
+ // The first differing element decides array order; otherwise the shorter wins.
177
+ for (let i = 0; i < Math.min(a.length, b.length); i++) {
178
+ const result = compare(a[i], b[i]);
179
+ if (result)
180
+ return result;
181
+ }
182
+ return Math.sign(a.length - b.length);
183
+ }
184
+ if (aRank === 6) {
185
+ // Sort keys first so object insertion order does not affect the comparison.
186
+ const ak = Object.keys(a).sort();
187
+ const bk = Object.keys(b).sort();
188
+ for (let i = 0; i < Math.min(ak.length, bk.length); i++) {
189
+ const keyResult = compare(ak[i], bk[i]);
190
+ if (keyResult)
191
+ return keyResult;
192
+ const valueResult = compare(a[ak[i]], b[bk[i]]);
193
+ if (valueResult)
194
+ return valueResult;
195
+ }
196
+ return Math.sign(ak.length - bk.length);
197
+ }
198
+ return a < b ? -1 : a > b ? 1 : 0;
199
+ }
200
+ /**
201
+ * Apply the field filters together: if any defined filter fails, exclude the record.
202
+ * An undefined query operand is ignored, as explained by the optional __hashtagId
203
+ * example in runQuery. That is different from a record missing the field needed
204
+ * to satisfy a defined filter. For example, a record without an optional tags
205
+ * array cannot match ['tags', 'array-contains', 'algebra'].
206
+ */
207
+ function matches(entity, params) {
208
+ return (params ?? []).every(([field, operator, operand]) => {
209
+ if (operand === undefined)
210
+ return true;
211
+ const value = fieldValue(entity, field);
212
+ if (value === undefined)
213
+ return false;
214
+ switch (operator) {
215
+ case '==': return equals(value, operand);
216
+ case '!=': return !equals(value, operand);
217
+ case '>': return compare(value, operand) > 0;
218
+ case '>=': return compare(value, operand) >= 0;
219
+ case '<': return compare(value, operand) < 0;
220
+ case '<=': return compare(value, operand) <= 0;
221
+ case 'in': return Array.isArray(operand) && operand.some(v => equals(value, v));
222
+ case 'not-in': return Array.isArray(operand) && value !== null && !operand.includes(null) && !operand.some(v => equals(value, v));
223
+ case 'array-contains': return Array.isArray(value) && value.some(v => equals(v, operand));
224
+ case 'array-contains-any': return Array.isArray(value) && Array.isArray(operand) && value.some(v => operand.some(o => equals(v, o)));
225
+ default: throw new Error(`Unsupported query operator: ${operator}`);
226
+ }
227
+ });
228
+ }
229
+ /** Normalize the three supported orderBy shapes without changing the caller's options. */
230
+ function queryOrderings(options = {}) {
231
+ const order = options?.orderBy;
232
+ if (!order)
233
+ return [];
234
+ if (typeof order === 'string')
235
+ return [[order, 'asc']];
236
+ return Array.isArray(order[0]) ? order : [order];
237
+ }
238
+ /**
239
+ * Filter using startAt/startAfter/endAt/endBefore in the requested sort order.
240
+ * The original local selector only supported a single ordered field. This helper
241
+ * also handles multiple fields: with orderBy [['group', 'asc'], ['score', 'desc']],
242
+ * startAfter ['algebra', 5] means after algebra/5 in that combined ordering.
243
+ * Each descending field reverses its comparison; inclusive bounds keep equal values.
244
+ */
245
+ function withinCursors(entity, options, orders) {
246
+ return ['startAt', 'startAfter', 'endAt', 'endBefore'].every(key => {
247
+ if (options?.[key] === undefined)
248
+ return true;
249
+ if (!orders.length)
250
+ throw new Error('Local query cursors require orderBy.');
251
+ const cursor = Array.isArray(options[key]) ? options[key] : [options[key]];
252
+ if (!cursor.length || cursor.length > orders.length)
253
+ throw new Error('Cursor values must match the query orderings.');
254
+ let result = 0;
255
+ for (let i = 0; i < cursor.length; i++) {
256
+ result = compare(fieldValue(entity, orders[i][0]), cursor[i]) * (orders[i][1] === 'desc' ? -1 : 1);
257
+ if (result)
258
+ break;
259
+ }
260
+ return key === 'startAt' ? result >= 0 : key === 'startAfter' ? result > 0 : key === 'endAt' ? result <= 0 : result < 0;
261
+ });
262
+ }
263
+ /**
264
+ * Check whether the entity satisfies the query results.
265
+ * We use this to double-check whether a 'removed' change was truly removed from
266
+ * the backend or whether it just doesn't match the query anymore. For example,
267
+ * a post whose authorId changes leaves the old author's query, but can still be
268
+ * needed by another query and should not be removed from the shared store solely
269
+ * for leaving that result set.
270
+ *
271
+ * This checks filters, ordered fields and cursor bounds. A single entity cannot
272
+ * establish membership in a limited result window; that also depends on other records.
273
+ */
274
+ function entityInQueryResults(entity, params = [], options = {}) {
275
+ if (!entity || !matches(entity, params))
276
+ return false;
277
+ const orders = queryOrderings(options);
278
+ // If orderBy is provided, only return entities that have each ordered property,
279
+ // just like Firestore. A null value is present; an undefined field is missing.
280
+ return orders.every(([field]) => fieldValue(entity, field) !== undefined) && withinCursors(entity, options, orders);
281
+ }
282
+ /**
283
+ * The selection steps shared by frontend selectors and mock database reads:
284
+ * narrow by ID, apply the remaining filters, then order and limit the results.
285
+ * Entity maps are keyed by the record's string __id, as required by DataEntity.
286
+ * activeOnly hides deleted records for the frontend; the mock needs to query them.
287
+ */
288
+ function runQuery(entityMap, queryParams, queryOptions, activeOnly) {
289
+ // 1. START WITH ID FILTERS so a small ID query does not scan the whole store.
290
+ // Note: Firestore supports setting and querying for null, but not undefined.
291
+ // We filter out cases where the value is undefined to protect against cases
292
+ // when people are doing a nested query and some entity does not have a
293
+ // particular field, e.g. [['__hashtagId', '==', q.__hashtagId]] when
294
+ // __hashtagId is an optional parameter.
295
+ // This ignores only that filter: other filters still apply. It does not skip
296
+ // the whole query, and a defined ID that is not loaded must still return [].
297
+ const filters = (queryParams ?? []).filter(([, , value]) => value !== undefined);
298
+ const selectIdEqQueries = filters.filter(([key, rel]) => key === '__id' && rel === '==');
299
+ const uniqSelectEqIds = [...new Set(selectIdEqQueries.map(([, , id]) => id))];
300
+ const selectIdInQueries = filters.filter(([key, rel]) => key === '__id' && rel === 'in');
301
+ let filteredEntities = [];
302
+ if (uniqSelectEqIds.length === 1) {
303
+ // Exactly one required ID: look it up directly, even if it is not loaded.
304
+ const id = uniqSelectEqIds[0];
305
+ const entity = typeof id === 'string' && Object.hasOwn(entityMap, id) ? entityMap[id] : undefined;
306
+ // Missing IDs have no matches. Do not fall through to all loaded records.
307
+ if (!entity)
308
+ return [];
309
+ filteredEntities.push(entity);
310
+ }
311
+ else if (uniqSelectEqIds.length > 1) {
312
+ // One record cannot have two different IDs (e.g. __id == 'a' AND __id == 'b').
313
+ return [];
314
+ }
315
+ else if (selectIdInQueries.length > 0) {
316
+ // Start with the first ID list, looking up each unique ID directly.
317
+ // Empty lists match nothing; missing IDs and undefined list entries add nothing.
318
+ const firstInIds = selectIdInQueries[0][2];
319
+ if (!Array.isArray(firstInIds))
320
+ return [];
321
+ filteredEntities = [...new Set(firstInIds)]
322
+ .filter(id => typeof id === 'string' && Object.hasOwn(entityMap, id))
323
+ .map(id => entityMap[id]);
324
+ }
325
+ else {
326
+ // Without an ID ==/in filter, consider every record already in the map.
327
+ filteredEntities = Object.values(entityMap);
328
+ }
329
+ // Every ID list must also match, including when the == branch supplied the record.
330
+ // For example, __id == 'a' AND __id in ['b'] must return nothing.
331
+ const allowedIdSets = selectIdInQueries.map(([, , ids]) => new Set(Array.isArray(ids) ? ids : []));
332
+ filteredEntities = filteredEntities.filter(entity => entity && allowedIdSets.every(ids => ids.has(entity['__id'])) &&
333
+ (!activeOnly || !entity['_deleted']));
334
+ // 2. APPLY THE REMAINING FILTERS. ID ==/in have been fully handled above.
335
+ // The common predicate helper also checks ordered fields and cursor bounds.
336
+ const remainingFilters = filters.filter(([key, rel]) => !(key === '__id' && (rel === '==' || rel === 'in')));
337
+ filteredEntities = filteredEntities.filter(entity => entityInQueryResults(entity, remainingFilters, queryOptions));
338
+ // 3. SORT BY EACH REQUESTED FIELD, using the ID to break ties consistently.
339
+ const orders = queryOrderings(queryOptions);
340
+ if (orders.length) {
341
+ filteredEntities.sort((a, b) => {
342
+ for (const [field, direction] of orders) {
343
+ const result = compare(fieldValue(a, field), fieldValue(b, field));
344
+ if (result)
345
+ return result * (direction === 'desc' ? -1 : 1);
346
+ }
347
+ return compare(fieldValue(a, '__id'), fieldValue(b, '__id')) * (orders.at(-1)[1] === 'desc' ? -1 : 1);
348
+ });
349
+ }
350
+ // 4. APPLY THE LIMIT LAST, after filtering (including deletion) and ordering.
351
+ if (queryOptions?.limit !== undefined) {
352
+ if (!Number.isInteger(queryOptions.limit) || queryOptions.limit < 1)
353
+ throw new Error('Query limit must be a positive integer.');
354
+ filteredEntities = filteredEntities.slice(0, queryOptions.limit);
355
+ }
356
+ return filteredEntities;
357
+ }
358
+ /**
359
+ * Mock database query: use the ID-first steps in runQuery without hiding deletions.
360
+ * In particular, the loader's _deleted == true query must return those records.
361
+ */
362
+ function queryEntities(entityMap, params = [], options = {}) {
363
+ return runQuery(entityMap, params, options, false);
364
+ }
365
+ /**
366
+ * Select entities already in the store, given its entityMap and query constraints.
367
+ * Filters out records marked _deleted even if a caller explicitly includes a
368
+ * _deleted filter, so a frontend selector cannot expose a soft-deleted record.
369
+ * The mock backend instead uses queryEntities: the loader needs its separate
370
+ * _deleted == true query to return deletion markers and remove cached records.
371
+ */
372
+ function selectEntities(entityMap, params = [], options = {}) {
373
+ return runQuery(entityMap, params, options, true);
374
+ }
375
+
376
+ /**
377
+ * Expand child-load descriptors for parent records and execute compatible groups
378
+ * together. Each position in the callback's returned array represents one child
379
+ * relationship; batching also checks collection/store/callback identity before
380
+ * combining requests. Firestore rejects an empty `in` list, so the helper skips
381
+ * the entire descriptor containing it. Other descriptors still run, and skipping
382
+ * a load does not clear records already held in the frontend store.
383
+ */
384
+ async function processLoadQueries(entities, loadQueries) {
385
+ if (entities.length > 0) {
386
+ // create a matrix of queries, each row corresponding to a given entity
387
+ const queriesByEntity = entities.map((entity) => loadQueries(entity));
388
+ // transpose the matrix so each row corresponds to all queries for the same query type
389
+ const queriesByQueryType = Array.from({ length: Math.max(0, ...queriesByEntity.map(row => row.length)) }, (_, colIndex) => queriesByEntity.map(row => row[colIndex]).filter(Boolean));
390
+ // Process all query types concurrently
391
+ await Promise.all(queriesByQueryType.map(async (queriesForOneType) => {
392
+ // Seeing if we can optimize by collapsing equality queries into 'in' queries
393
+ const optimizedQueries = EntityLoadQuery.optimize(queriesForOneType);
394
+ // Process queries concurrently using Promise.all
395
+ await Promise.all(optimizedQueries.filter((q) => !!q).map(async (query) => {
396
+ // Firestore throws an error if an 'in' query is executed with an empty array.
397
+ // Therefore, we skip executing any queries that have an 'in' clause with an empty array.
398
+ // Example: ['__id', 'in', []]
399
+ if (!query.queryParams.some((param) => Array.isArray(param[2]) && param[2].length === 0 && param[1] === 'in')) {
400
+ await query.store.load(query.queryParams, query.queryOptions, query.loadQueries);
401
+ }
402
+ }));
403
+ }));
404
+ }
405
+ }
406
+ /**
407
+ * Description of a nested one-shot load. Construction does not run the query;
408
+ * processLoadQueries passes it to the owning store. Generated Load<Entity>
409
+ * subclasses supply collection identity and the entity's domain type.
410
+ */
411
+ class EntityLoadQuery {
412
+ collection;
413
+ queryParams;
414
+ queryOptions;
415
+ loadQueries;
416
+ store;
417
+ constructor(collection, store, queryParams, queryOptions, loadQueries) {
418
+ this.collection = collection;
419
+ this.queryParams = queryParams;
420
+ this.queryOptions = queryOptions;
421
+ this.loadQueries = loadQueries;
422
+ this.store = store;
423
+ }
424
+ // Checks if there is a single equality query of the same type
425
+ // that could be transformed into an 'in' query
426
+ static areBatchableEqualityQueries(queries) {
427
+ if (queries.length === 0)
428
+ return false;
429
+ // check if there is only one queryParam for each query and no queryOptions
430
+ const hasSingleQueryParamAndNoOptions = queries.every((q) => {
431
+ return q.queryParams.length === 1 && (!q.queryOptions || Object.keys(q.queryOptions).length === 0);
432
+ });
433
+ if (!hasSingleQueryParamAndNoOptions)
434
+ return false;
435
+ // Finally, verify that every query is filtering on the exact same field
436
+ // (e.g., they are all querying '__userId') AND that they are all using the
437
+ // exact equality operator ('=='). This ensures they can be safely collapsed
438
+ // into a single 'in' query (e.g., '__userId in [1, 2, 3]').
439
+ const firstField = queries[0].queryParams[0][0];
440
+ return queries.every((q) => q.collection === queries[0].collection && q.store === queries[0].store && q.loadQueries === queries[0].loadQueries && q.queryParams[0][2] !== undefined && q.queryParams[0][0] === firstField && q.queryParams[0][1] === '==');
441
+ }
442
+ /**
443
+ * Optimize N+1 loads: N parents requesting children with one equality filter
444
+ * each (e.g. [['__postId', '==', x]]) would otherwise cause N separate requests.
445
+ * With no queryOptions, compatible requests can be combined into an 'in' query;
446
+ * load() then splits it into backend-sized chunks of at most 30 values.
447
+ * See https://firebase.google.com/docs/firestore/query-data/queries#in_and_array-contains-any.
448
+ *
449
+ * Batching changes the query key when a parent is added or removed. Tracking
450
+ * only the whole query's lastLoadTime would then lose incremental-load reuse
451
+ * and could refetch already-loaded children. The current loader tracks cutoff
452
+ * times per field/value and groups compatible times before chunking, retaining
453
+ * that reuse while reducing separate backend requests.
454
+ */
455
+ static optimize(queries) {
456
+ if (this.areBatchableEqualityQueries(queries)) {
457
+ // get the field we are querying against
458
+ const collection = queries[0].collection;
459
+ const field = queries[0].queryParams[0][0];
460
+ const loadQs = queries[0].loadQueries;
461
+ // We no longer chunk into groups of 30 here. Instead, we bundle ALL IDs into a single 'in'
462
+ // query. The `load()` method will intercept this unified query, generate a single `newLoadTime`,
463
+ // and perform the 30-item chunking internally. This guarantees that all entities requested
464
+ // together receive the exact same timestamp.
465
+ const ids = queries.map((q) => q.queryParams[0][2]);
466
+ return [new EntityLoadQuery(collection, queries[0].store, [[field, 'in', ids]], {}, loadQs)];
467
+ }
468
+ else {
469
+ return queries;
470
+ }
471
+ }
472
+ }
473
+ /**
474
+ * Description of a nested live query. CachedListenersService establishes the
475
+ * listener using the caller's injector and processes further child descriptors
476
+ * as parent records change. Constructing a descriptor alone opens no listener.
477
+ */
478
+ class EntityStreamQuery {
479
+ collection;
480
+ queryParams;
481
+ queryOptions;
482
+ streamQueries;
483
+ store;
484
+ constructor(collection, store, queryParams, queryOptions, streamQueries) {
485
+ this.collection = collection;
486
+ this.queryParams = queryParams;
487
+ this.queryOptions = queryOptions;
488
+ this.streamQueries = streamQueries;
489
+ this.store = store;
490
+ }
491
+ // Checks if there is a single equality query of the same type
492
+ // that could be transformed into an 'in' query
493
+ static areBatchableEqualityQueries(queries) {
494
+ if (queries.length === 0)
495
+ return false;
496
+ // check if there is only one queryParam for each query and no queryOptions
497
+ const hasSingleQueryParamAndNoOptions = queries.every((q) => {
498
+ return q.queryParams.length === 1 && (!q.queryOptions || Object.keys(q.queryOptions).length === 0);
499
+ });
500
+ if (!hasSingleQueryParamAndNoOptions)
501
+ return false;
502
+ // Finally, verify that every query is filtering on the exact same field
503
+ // (e.g., they are all querying '__userId') AND that they are all using the
504
+ // exact equality operator ('=='). This ensures they can be safely collapsed
505
+ // into a single 'in' query (e.g., '__userId in [1, 2, 3]').
506
+ const firstField = queries[0].queryParams[0][0];
507
+ return queries.every((q) => q.collection === queries[0].collection && q.store === queries[0].store && q.streamQueries === queries[0].streamQueries && q.queryParams[0][2] !== undefined && q.queryParams[0][0] === firstField && q.queryParams[0][1] === '==');
508
+ }
509
+ /**
510
+ * Optimize N+1 streams: combine compatible single-equality child queries such
511
+ * as [['__postId', '==', x]], with no queryOptions, into one descriptor. The
512
+ * multiplexer opens 'in' listeners with at most 30 values per batch downstream.
513
+ * See https://firebase.google.com/docs/firestore/query-data/queries#in_and_array-contains-any.
514
+ *
515
+ * The pairwise diff in CachedListenersService re-evaluates nested queries only
516
+ * for changed parents. The initial N parents can be collapsed together, while
517
+ * later individual changes typically request a single value; the multiplexer
518
+ * manages those sparse listeners and repacks them when appropriate.
519
+ *
520
+ * Batched listeners share the parent component's DestroyRef for cleanup, just
521
+ * as individual listeners do. Batching does not give them a longer lifetime.
522
+ */
523
+ static optimize(queries) {
524
+ // Keep all requested IDs in one descriptor. Listener chunking and reference
525
+ // counting happen downstream, where component DestroyRefs are available.
526
+ if (this.areBatchableEqualityQueries(queries)) {
527
+ // get the field we are querying against
528
+ const collection = queries[0].collection;
529
+ const field = queries[0].queryParams[0][0];
530
+ const streamQs = queries[0].streamQueries;
531
+ const ids = queries.map((q) => q.queryParams[0][2]);
532
+ return [new EntityStreamQuery(collection, queries[0].store, [[field, 'in', ids]], {}, streamQs)];
533
+ }
534
+ else {
535
+ return queries;
536
+ }
537
+ }
538
+ }
539
+
540
+ /**
541
+ * Combines component requests for one store/collection/field into batched 'in'
542
+ * queries through DataAccess. The current batch size follows Firestore's limit.
543
+ *
544
+ * It manages two pools of logical listeners (transport connections belong to the adapter):
545
+ * 1. `batchedListeners`: fully packed 'in' queries (chunks of 30 IDs).
546
+ * 2. `singleListeners`: sparse 'in' queries handling newly requested IDs.
547
+ *
548
+ * It balances stream connection limits with UI rendering performance by maintaining
549
+ * sparse streams until a threshold is reached, at which point it automatically triggers
550
+ * an `executeSmartRepack` to consolidate streams and release redundant listeners.
551
+ *
552
+ * It tracks component lifecycles using `DestroyRef` to gracefully tear down streams
553
+ * when components are destroyed and their requested IDs become "orphaned".
554
+ */
555
+ class StreamMultiplexer {
556
+ collection;
557
+ field;
558
+ db;
559
+ store;
560
+ queryLogger;
561
+ onError;
562
+ retiring = new Set();
563
+ generation = 0;
564
+ // Maps a unique query value ID (e.g., a specific user ID) to the set of component DestroyRefs that requested it.
565
+ destroyRefsById = new Map();
566
+ // Maps a component's DestroyRef to the set of IDs it requested. This allows us to safely clean up all of a component's
567
+ // requested IDs when it is destroyed, even if it called registerIds multiple times.
568
+ idsByDestroyRef = new Map();
569
+ // Tracks optimized batches of up to 30 IDs
570
+ batchedListeners = [];
571
+ // Tracks newly added small groups of IDs that haven't been repacked yet
572
+ singleListeners = [];
573
+ // Threshold for determining when a batch is "sparse" enough to warrant evaluating a repack operation.
574
+ MAX_ORPHANED_IDS_PER_BATCH = 10;
575
+ // Threshold for determining when we have accumulated enough single listeners to warrant repacking them into a batch.
576
+ MAX_SINGLE_LISTENERS_BEFORE_REPACK = 10;
577
+ constructor(collection, field, db, store, // NgRx Signal Store with handleStreamChanges
578
+ queryLogger = NOOP_LOGGER, onError = () => { }) {
579
+ this.collection = collection;
580
+ this.field = field;
581
+ this.db = db;
582
+ this.store = store;
583
+ this.queryLogger = queryLogger;
584
+ this.onError = onError;
585
+ }
586
+ /**
587
+ * Checks if an ID is currently being actively streamed by any component.
588
+ */
589
+ isIdActive(id) {
590
+ return this.destroyRefsById.has(id) && this.destroyRefsById.get(id).size > 0;
591
+ }
592
+ /**
593
+ * Registers a list of query values to stream through the configured adapter.
594
+ * Duplicate requests for the same ID are deduplicated.
595
+ * Automatically handles teardown when the provided destroyRef fires.
596
+ */
597
+ registerIds(ids, destroyRef) {
598
+ this.queryLogger.log(`[StreamMultiplexer] registerIds called with: [${Array.from(ids).join(', ')}]`);
599
+ const newIds = [];
600
+ // We maintain a reverse lookup from DestroyRef -> IDs to easily clean up when the component is destroyed.
601
+ let idsForDestroyRef = this.idsByDestroyRef.get(destroyRef);
602
+ const isFirstRegistrationForRef = !idsForDestroyRef;
603
+ // Initialize the set if this is the very first time this DestroyRef is calling registerIds()
604
+ if (!idsForDestroyRef) {
605
+ idsForDestroyRef = new Set();
606
+ this.idsByDestroyRef.set(destroyRef, idsForDestroyRef);
607
+ }
608
+ ids.forEach((id) => {
609
+ // Add the requested ID to the component's tracking set so it can be safely cleaned up later
610
+ idsForDestroyRef.add(id);
611
+ // Look up if this exact ID is already being actively streamed by anyone else in the application
612
+ let registeredSet = this.destroyRefsById.get(id);
613
+ if (!registeredSet) {
614
+ // First time this ID has been requested anywhere!
615
+ // We create a new Set to track all the specific DestroyRefs that have requested it.
616
+ registeredSet = new Set();
617
+ this.destroyRefsById.set(id, registeredSet);
618
+ // Track this as a new ID that needs to be streamed
619
+ newIds.push(id);
620
+ }
621
+ registeredSet.add(destroyRef);
622
+ });
623
+ // Handle teardown when the component is destroyed
624
+ if (isFirstRegistrationForRef) {
625
+ destroyRef.onDestroy(() => {
626
+ setTimeout(() => {
627
+ let triggeredRemove = false;
628
+ // Retrieve the dynamically accumulated set of IDs that were requested by this specific component's DestroyRef.
629
+ // By pulling from this Map instead of a closed-over lexical variable, we ensure we clean up ALL IDs
630
+ // requested across multiple calls to registerIds() by the same component.
631
+ const idsToClean = this.idsByDestroyRef.get(destroyRef);
632
+ if (idsToClean) {
633
+ this.queryLogger.log(`[StreamMultiplexer] Component destroyed 5 seconds ago! Releasing its holds on IDs: [${Array.from(idsToClean).join(', ')}]`);
634
+ idsToClean.forEach((id) => {
635
+ const registeredSet = this.destroyRefsById.get(id);
636
+ if (registeredSet && registeredSet.has(destroyRef)) {
637
+ // Remove this component's claim to the ID
638
+ registeredSet.delete(destroyRef);
639
+ // If no other components are currently listening to this ID,
640
+ // completely remove it from the globally active set.
641
+ if (registeredSet.size === 0) {
642
+ this.destroyRefsById.delete(id);
643
+ triggeredRemove = true;
644
+ }
645
+ }
646
+ });
647
+ // Cleanup the tracking Map itself to prevent memory leaks
648
+ this.idsByDestroyRef.delete(destroyRef);
649
+ }
650
+ if (triggeredRemove) {
651
+ this.cleanupEmptyListeners();
652
+ if (this.hasBatchWithTooManyOrphans()) {
653
+ this.executeSmartRepack();
654
+ }
655
+ }
656
+ }, 5000); // 5-second graceful shutdown period
657
+ });
658
+ }
659
+ this.checkAndExecuteRepack(newIds);
660
+ }
661
+ /**
662
+ * Evaluates whether the multiplexer should execute a repack operation.
663
+ * A repack is executed if either:
664
+ * 1. A new ID request pushes the projected single listener count over the MAX_SINGLE_LISTENERS_BEFORE_REPACK threshold.
665
+ * 2. An orphaned batch cleanup check triggered this evaluation.
666
+ *
667
+ * If new IDs are requested but the threshold is not met, this method simply spins up
668
+ * a single sparse stream for those IDs to prioritize immediate UI rendering speed.
669
+ *
670
+ * @param newIds - Array of newly requested IDs that are not yet streamed.
671
+ */
672
+ checkAndExecuteRepack(newIds) {
673
+ if (newIds.length > 0) {
674
+ const numNewBatches = Math.ceil(newIds.length / 30);
675
+ const projectedSingleListeners = this.singleListeners.length + numNewBatches;
676
+ // If adding these new IDs would push us over the threshold, just execute a repack directly.
677
+ // The repack logic will automatically pick up all unstreamed IDs.
678
+ if (projectedSingleListeners >= this.MAX_SINGLE_LISTENERS_BEFORE_REPACK) {
679
+ this.executeSmartRepack(newIds);
680
+ }
681
+ else {
682
+ // Otherwise, spin up a new listener for the newly requested IDs
683
+ const newChunks = this.chunkArray(newIds, 30);
684
+ const newBatches = this.startNewBatches(newChunks, []);
685
+ // We separate full batches from sparse single listeners
686
+ newBatches.forEach((b) => {
687
+ if (b.ids.length === 30) {
688
+ this.batchedListeners.push(b);
689
+ }
690
+ else {
691
+ this.singleListeners.push(b);
692
+ }
693
+ });
694
+ }
695
+ }
696
+ }
697
+ /**
698
+ * Completely tears down all active streams and resets the multiplexer state.
699
+ * Useful when the user logs out or the entire parent collection listener is destroyed.
700
+ */
701
+ teardownAll() {
702
+ this.generation++;
703
+ this.teardownOldListeners([...this.retiring]);
704
+ this.retiring.clear();
705
+ this.batchedListeners.forEach((b) => {
706
+ if (b.unsubscribe)
707
+ b.unsubscribe();
708
+ });
709
+ this.batchedListeners = [];
710
+ this.singleListeners.forEach((s) => {
711
+ if (s.unsubscribe)
712
+ s.unsubscribe();
713
+ });
714
+ this.singleListeners = [];
715
+ this.destroyRefsById.clear();
716
+ this.idsByDestroyRef.clear();
717
+ }
718
+ /**
719
+ * Identifies any listeners (both single and batched) where EVERY SINGLE ID has 0 active holds.
720
+ * If an entire stream is completely abandoned, it is immediately unsubscribed and purged to prevent
721
+ * dead sockets from hanging around indefinitely.
722
+ */
723
+ cleanupEmptyListeners() {
724
+ const activeIds = new Set(this.destroyRefsById.keys());
725
+ const emptyBatches = this.batchedListeners.filter((b) => b.ids.every((id) => !activeIds.has(id)));
726
+ if (emptyBatches.length > 0) {
727
+ this.queryLogger.log(`[StreamMultiplexer] Purging ${emptyBatches.length} completely empty batched stream(s).`);
728
+ emptyBatches.forEach((b) => {
729
+ if (b.unsubscribe) {
730
+ b.unsubscribe();
731
+ b.unsubscribe = null;
732
+ }
733
+ });
734
+ this.batchedListeners = this.batchedListeners.filter((b) => !emptyBatches.includes(b));
735
+ }
736
+ const emptySingles = this.singleListeners.filter((s) => s.ids.every((id) => !activeIds.has(id)));
737
+ if (emptySingles.length > 0) {
738
+ this.queryLogger.log(`[StreamMultiplexer] Purging ${emptySingles.length} completely empty single stream(s).`);
739
+ emptySingles.forEach((s) => {
740
+ if (s.unsubscribe) {
741
+ s.unsubscribe();
742
+ s.unsubscribe = null;
743
+ }
744
+ });
745
+ this.singleListeners = this.singleListeners.filter((s) => !emptySingles.includes(s));
746
+ }
747
+ }
748
+ /**
749
+ * Checks if any of the currently active websocket listeners has too many "orphaned" IDs
750
+ * (IDs that are being streamed from Firestore but are no longer requested by any component).
751
+ */
752
+ hasBatchWithTooManyOrphans() {
753
+ return this.batchedListeners.some((batch) => {
754
+ const orphans = batch.ids.filter((id) => {
755
+ const refs = this.destroyRefsById.get(id);
756
+ return !refs || refs.size === 0;
757
+ }).length;
758
+ return orphans >= this.MAX_ORPHANED_IDS_PER_BATCH;
759
+ });
760
+ }
761
+ /**
762
+ * Consolidates sparse streams and tears down bloated batches.
763
+ *
764
+ * It uses a greedy mathematical algorithm to evaluate "candidate batches" (those with <= 25 active IDs)
765
+ * and determine if tearing them down and bundling their active IDs with the single listeners will
766
+ * result in a net reduction in the total number of websocket streams.
767
+ *
768
+ * Note: This method does not check threshold conditions before executing. Callers
769
+ * (e.g. checkAndExecuteRepack) must verify that a repack is strictly necessary
770
+ * before invoking this method.
771
+ *
772
+ * @param newIds - Array of newly requested IDs that need to be streamed.
773
+ */
774
+ executeSmartRepack(newIds = []) {
775
+ this.queryLogger.log(`[StreamMultiplexer] Smart Repack Triggered!`);
776
+ const activeIds = new Set(this.destroyRefsById.keys());
777
+ // 1. Gather all single listeners and new IDs into one pool
778
+ const singleIds = [];
779
+ this.singleListeners.forEach((s) => singleIds.push(...s.ids.filter((id) => activeIds.has(id))));
780
+ singleIds.push(...newIds);
781
+ const S = singleIds.length;
782
+ // 2. Identify sparse batches (<= 25 active IDs) as candidates for mathematical reduction
783
+ const candidateBatches = this.batchedListeners
784
+ .map((batch) => ({
785
+ batch,
786
+ activeCount: batch.ids.filter((id) => activeIds.has(id)).length,
787
+ }))
788
+ .filter((b) => b.activeCount <= 25);
789
+ // 3. Sort candidates ascending so we combine the sparsest batches first
790
+ candidateBatches.sort((a, b) => a.activeCount - b.activeCount);
791
+ // Baseline reduction: bundling all single listeners into tight chunks
792
+ let bestReduction = S > 0 ? S - Math.ceil(S / 30) : 0;
793
+ let bestT = [];
794
+ let currentA = 0;
795
+ const currentT = [];
796
+ // 4. Greedily evaluate absorbing sparse batches to maximize stream reduction
797
+ for (let i = 0; i < candidateBatches.length; i++) {
798
+ currentT.push(candidateBatches[i].batch);
799
+ currentA += candidateBatches[i].activeCount;
800
+ const newBatchesCount = Math.ceil((S + currentA) / 30);
801
+ const reduction = S + currentT.length - newBatchesCount;
802
+ if (reduction > bestReduction) {
803
+ bestReduction = reduction;
804
+ bestT = [...currentT];
805
+ }
806
+ }
807
+ // 5. Ensure we also forcibly tear down any bloated batches (>= 10 orphans)
808
+ // even if they didn't mathematically reduce the total stream count.
809
+ const bloatedBatches = this.batchedListeners.filter((batch) => {
810
+ const orphans = batch.ids.filter((id) => !activeIds.has(id)).length;
811
+ return orphans >= this.MAX_ORPHANED_IDS_PER_BATCH;
812
+ });
813
+ bloatedBatches.forEach((b) => {
814
+ if (!bestT.includes(b)) {
815
+ bestT.push(b);
816
+ }
817
+ });
818
+ const batchesToTeardown = bestT;
819
+ const singleListenersToTeardown = [...this.singleListeners];
820
+ // 6. Collect all the actively requested IDs from the streams we are about to tear down
821
+ const idsToChunk = [...singleIds];
822
+ batchesToTeardown.forEach((b) => {
823
+ idsToChunk.push(...b.ids.filter((id) => activeIds.has(id)));
824
+ });
825
+ // 7. If there's nothing left to stream, just clean up state and return
826
+ if (idsToChunk.length === 0) {
827
+ this.finalizeRepackState(batchesToTeardown, singleListenersToTeardown, []);
828
+ return;
829
+ }
830
+ // 8. Break the collected IDs into optimal chunks of 30 for Firestore 'in' queries
831
+ const newChunks = this.chunkArray(idsToChunk, 30);
832
+ // 9. Spin up the new websocket streams, passing the old ones to be torn down only AFTER the new ones emit data
833
+ const newBatches = this.startNewBatches(newChunks, [...batchesToTeardown, ...singleListenersToTeardown]);
834
+ // 10. Update our internal tracking arrays to reflect the new state
835
+ this.finalizeRepackState(batchesToTeardown, singleListenersToTeardown, newBatches);
836
+ }
837
+ /**
838
+ * Opens new Firestore snapshot streams for the given chunks of IDs.
839
+ *
840
+ * @param newChunks - The fully chunked arrays of IDs to stream (max 30 per chunk).
841
+ * @param oldBatchesToTeardown - The old websocket listeners that these new chunks are replacing.
842
+ * They are only torn down *after* the new stream emits its first
843
+ * payload, preventing UI flickering.
844
+ */
845
+ startNewBatches(newChunks, oldBatchesToTeardown) {
846
+ if (newChunks.length > 0) {
847
+ this.queryLogger.log(`[StreamMultiplexer] Opening ${newChunks.length} new websocket stream(s) for chunks:`);
848
+ newChunks.forEach((c) => this.queryLogger.log(` - [${c.join(', ')}]`));
849
+ }
850
+ const newBatches = [];
851
+ const epoch = this.generation;
852
+ let remaining = newChunks.length;
853
+ oldBatchesToTeardown.forEach(batch => this.retiring.add(batch));
854
+ for (const chunk of newChunks) {
855
+ if (epoch !== this.generation)
856
+ break;
857
+ let isFirstEmission = true;
858
+ const queryParams = chunk.length === 1 ?
859
+ [[this.field, '==', chunk[0]]] : [[this.field, 'in', chunk]];
860
+ const subscription = this.db.streamEntitiesChanges(this.collection, queryParams, {}).subscribe({
861
+ next: changes => {
862
+ if (epoch !== this.generation)
863
+ return;
864
+ this.patchToStore(changes, queryParams);
865
+ if (isFirstEmission) {
866
+ isFirstEmission = false;
867
+ if (--remaining === 0)
868
+ this.teardownOldListeners(oldBatchesToTeardown);
869
+ }
870
+ },
871
+ error: error => {
872
+ this.onError(error);
873
+ this.queryLogger.error('Data stream failed; a subsequent stream request can retry.', error);
874
+ this.teardownAll();
875
+ },
876
+ });
877
+ if (epoch === this.generation)
878
+ newBatches.push({ ids: chunk, unsubscribe: () => subscription.unsubscribe() });
879
+ else
880
+ subscription.unsubscribe();
881
+ }
882
+ return newBatches;
883
+ }
884
+ /**
885
+ * Unsubscribes from the old listener sockets to clean up the network connections.
886
+ */
887
+ teardownOldListeners(oldBatches) {
888
+ if (oldBatches.length > 0) {
889
+ this.queryLogger.log(`[StreamMultiplexer] Tearing down ${oldBatches.length} old websocket stream(s).`);
890
+ oldBatches.forEach((b) => {
891
+ this.retiring.delete(b);
892
+ this.queryLogger.log(` - [${b.ids.join(', ')}]`);
893
+ if (b.unsubscribe) {
894
+ b.unsubscribe();
895
+ b.unsubscribe = null;
896
+ }
897
+ });
898
+ }
899
+ }
900
+ /**
901
+ * Cleans up the multiplexer state arrays by removing the objects for the torn down streams
902
+ * and pushing the newly created streams into the correct `batchedListeners` or `singleListeners` array.
903
+ */
904
+ finalizeRepackState(oldBatchesToTeardown, oldSingleListenersToTeardown, newBatches) {
905
+ this.batchedListeners = this.batchedListeners.filter((b) => !oldBatchesToTeardown.includes(b));
906
+ this.singleListeners = this.singleListeners.filter((s) => !oldSingleListenersToTeardown.includes(s));
907
+ newBatches.forEach((b) => {
908
+ if (b.ids.length === 30) {
909
+ this.batchedListeners.push(b);
910
+ }
911
+ else {
912
+ this.singleListeners.push(b);
913
+ }
914
+ });
915
+ }
916
+ /**
917
+ * Utility to split an array of IDs into smaller chunks (max 30 for Firestore 'in' queries).
918
+ */
919
+ chunkArray(array, size) {
920
+ return Array.from({ length: Math.ceil(array.length / size) }, (v, i) => array.slice(i * size, i * size + size));
921
+ }
922
+ /**
923
+ * Takes the raw DocumentChange payload from Firestore and formats it into
924
+ * added/modified/removed arrays that the NgRx Signal Store can easily process.
925
+ */
926
+ patchToStore(fbPayload, queryParams) {
927
+ const entitiesToAdd = fbPayload
928
+ .filter((dc) => dc.type === 'added' && !dc.docData['_deleted'])
929
+ .map((dc) => dc.docData);
930
+ const entitiesToModify = fbPayload
931
+ .filter((dc) => dc.type === 'modified' && !dc.docData['_deleted'])
932
+ .map((dc) => dc.docData);
933
+ const entitiesToRemove = fbPayload
934
+ .filter((dc) => dc.type === 'modified' && dc.docData['_deleted'])
935
+ .map((dc) => dc.docData['__id']);
936
+ const entitiesToModify2 = fbPayload
937
+ .filter((dc) => dc.type === 'removed' && !entityInQueryResults(dc.docData, queryParams, {}))
938
+ .map((dc) => dc.docData);
939
+ const entitiesToRemove2 = fbPayload
940
+ .filter((dc) => dc.type === 'removed' && entityInQueryResults(dc.docData, queryParams, {}))
941
+ .map((dc) => dc.docData['__id']);
942
+ this.store.handleStreamChanges(entitiesToAdd, [...entitiesToModify, ...entitiesToModify2], [...entitiesToRemove, ...entitiesToRemove2]);
943
+ }
944
+ }
945
+
946
+ const selectId$1 = (entity) => entity.__id;
947
+ /** Equal timestamps are not a record revision: multiple local writes can share a clock tick. */
948
+ function entityChanged(previous, current) {
949
+ if (previous === current)
950
+ return false;
951
+ const keys = Object.keys(current);
952
+ if (keys.length !== Object.keys(previous).length)
953
+ return true;
954
+ return keys.some(key => {
955
+ const before = previous[key];
956
+ const after = current[key];
957
+ return isDataTimestamp(before) && isDataTimestamp(after)
958
+ ? !dataTimestampEquals(before, after)
959
+ : !Object.prototype.hasOwnProperty.call(previous, key) || !Object.is(before, after);
960
+ });
961
+ }
962
+ /**
963
+ * CachedListenersService manages database connections and their lifecycles to
964
+ * ensure optimal performance, prevent memory leaks, and solve the N+1 query problem.
965
+ *
966
+ * Responsibilities:
967
+ * 1. **Listener Pooling**: Deduplicates active database snapshot listeners. If
968
+ * multiple components request the exact same query, only one actual database
969
+ * listener is opened. Components share one root store per collection, so the
970
+ * shared listener updates the same records for all those components.
971
+ * 2. **Reference Counting & Lifecycle Management**: Tracks which components are using
972
+ * which stream via their Angular `DestroyRef`. When a component is destroyed, its
973
+ * reference is removed.
974
+ * 3. **Graceful Teardown**: Implements a 5-second grace period before fully closing a
975
+ * database connection after its last reference drops. This prevents UI flicker and
976
+ * unnecessary DB reads if the user navigates away and immediately back.
977
+ * 4. **Load Time Tracking (One-shot Loads)**: Tracks `lastLoadTime` for general queries
978
+ * and precise `entityLoadTime` for optimized batch equality queries. This enables
979
+ * incremental (delta-only) fetching, drastically reducing bandwidth by only fetching
980
+ * entities modified since the last load.
981
+ */
982
+ class CachedListenersService {
983
+ db;
984
+ /** Prevent nested stream callbacks from restarting listeners after global teardown. */
985
+ streamGeneration = 0;
986
+ queryLogger = injectLogger('data');
987
+ streamErrors = new Subject();
988
+ nestedObservers = new Set();
989
+ reportStreamError(error) {
990
+ this.queryLogger.error('Nested data stream failed', error);
991
+ this.streamErrors.next(error);
992
+ }
993
+ /** Dispose nested signal observers on component destruction or global listener teardown. */
994
+ observeNested(source, injector) {
995
+ return new Observable(subscriber => {
996
+ const destroyRef = injector.get(DestroyRef);
997
+ if (destroyRef.destroyed) {
998
+ subscriber.complete();
999
+ return;
1000
+ }
1001
+ const watcher = effect(() => {
1002
+ try {
1003
+ const value = source();
1004
+ untracked(() => subscriber.next(value));
1005
+ }
1006
+ catch (error) {
1007
+ subscriber.error(error);
1008
+ }
1009
+ }, { ...(ngDevMode ? { debugName: "watcher" } : /* istanbul ignore next */ {}), injector, manualCleanup: true });
1010
+ const complete = () => subscriber.complete();
1011
+ const unregister = destroyRef.onDestroy(complete);
1012
+ this.nestedObservers.add(complete);
1013
+ return () => {
1014
+ watcher.destroy();
1015
+ unregister();
1016
+ this.nestedObservers.delete(complete);
1017
+ };
1018
+ });
1019
+ }
1020
+ /** Nested asynchronous failures, which cannot be returned from the initial stream call. */
1021
+ errors$ = this.streamErrors.asObservable();
1022
+ /** Listener claims keyed by collection and canonical query. */
1023
+ connectionByQueryKey = {};
1024
+ /** Active equality multiplexers keyed by collection and field. */
1025
+ streamMultiplexers = new Map();
1026
+ /** Close connection events. */
1027
+ closeConnection$ = new Subject();
1028
+ /** Query cutoffs grouped by collection so resetting one store preserves the others. */
1029
+ lastLoadTime = new Map();
1030
+ /** Per-value equality cutoffs grouped by collection, in local-clock milliseconds. */
1031
+ entityLoadTime = new Map();
1032
+ getEntityLoadTime(collection, field, value) {
1033
+ return this.entityLoadTime.get(collection)?.get(this.getQueryKey(collection, [[field, '==', value]], {})) ?? -1;
1034
+ }
1035
+ setEntityLoadTime(collection, field, value, time) {
1036
+ let history = this.entityLoadTime.get(collection);
1037
+ if (!history)
1038
+ this.entityLoadTime.set(collection, history = new Map());
1039
+ history.set(this.getQueryKey(collection, [[field, '==', value]], {}), time);
1040
+ }
1041
+ /** Define a unique key for each connection. */
1042
+ getQueryKey(collection, queryParams, queryOptions) {
1043
+ return stableQueryKey(collection, queryParams, queryOptions);
1044
+ }
1045
+ /**
1046
+ * Tears down active adapter listeners before authentication is removed.
1047
+ * Retains records and load history so cached stores can keep loading deltas.
1048
+ * Ordinary reads/writes already in flight still finish normally.
1049
+ */
1050
+ teardownAllStreams() {
1051
+ this.streamGeneration++;
1052
+ for (const complete of [...this.nestedObservers])
1053
+ complete();
1054
+ for (const key of Object.keys(this.connectionByQueryKey)) {
1055
+ const connection = this.connectionByQueryKey[key];
1056
+ if (connection) {
1057
+ this.closeConnection$.next(key);
1058
+ connection.registeredSet.clear();
1059
+ }
1060
+ }
1061
+ this.connectionByQueryKey = {};
1062
+ for (const multiplexer of this.streamMultiplexers.values()) {
1063
+ multiplexer.teardownAll();
1064
+ }
1065
+ this.streamMultiplexers.clear();
1066
+ }
1067
+ /** Forget all query/value cutoffs for one collection when its store is reset. */
1068
+ clearLoadHistory(collection) {
1069
+ this.lastLoadTime.delete(collection);
1070
+ this.entityLoadTime.delete(collection);
1071
+ }
1072
+ /**
1073
+ * Explicitly close all listeners and clear every collection's load history, e.g. in tests.
1074
+ * Does not clear entity records or cancel pending reads/writes.
1075
+ */
1076
+ clearCache() {
1077
+ this.teardownAllStreams();
1078
+ this.lastLoadTime.clear();
1079
+ this.entityLoadTime.clear();
1080
+ }
1081
+ /** Return whether a stream exists for this query. */
1082
+ isStreamForQuery(collection, queryParams, queryOptions) {
1083
+ const queryKey = this.getQueryKey(collection, queryParams, queryOptions);
1084
+ return !!this.connectionByQueryKey[queryKey];
1085
+ }
1086
+ /** Return whether a specific ID is currently being streamed by a multiplexer. */
1087
+ isIdStreamed(collection, field, id) {
1088
+ const multiplexerKey = stableQueryKey(collection, [[field, '==', null]], {});
1089
+ const multiplexer = this.streamMultiplexers.get(multiplexerKey);
1090
+ return multiplexer ? multiplexer.isIdActive(id) : false;
1091
+ }
1092
+ /** Get the last load time for a particular query. */
1093
+ getLastLoadTime(collection, queryParams, queryOptions) {
1094
+ // If there are queryOptions, we don't support saving load times
1095
+ if (queryOptions && Object.keys(queryOptions).length > 0)
1096
+ return -1;
1097
+ const queryKey = this.getQueryKey(collection, queryParams, queryOptions);
1098
+ return this.lastLoadTime.get(collection)?.get(queryKey) ?? -1;
1099
+ }
1100
+ /** Set the last load time for a particular query. */
1101
+ setLastLoadTime(collection, queryParams, queryOptions, time) {
1102
+ // If there are queryOptions, we don't support saving load times
1103
+ if (queryOptions && Object.keys(queryOptions).length > 0)
1104
+ return;
1105
+ const queryKey = this.getQueryKey(collection, queryParams, queryOptions);
1106
+ let history = this.lastLoadTime.get(collection);
1107
+ if (!history)
1108
+ this.lastLoadTime.set(collection, history = new Map());
1109
+ history.set(queryKey, time);
1110
+ }
1111
+ /** Gets a cached connection if one exists. */
1112
+ getConnection(collection, queryParams, queryOptions) {
1113
+ const queryKey = this.getQueryKey(collection, queryParams, queryOptions);
1114
+ return this.connectionByQueryKey[queryKey];
1115
+ }
1116
+ /**
1117
+ * Attach/reuse a general query listener for this store and calling component.
1118
+ * DestroyRef releases the component's claim after the navigation grace period;
1119
+ * session resets bypass that delay. Optional descriptors add nested streams.
1120
+ */
1121
+ async processStreamQuery(collection, store, queryParams, queryOptions, injector, streamQueries, options) {
1122
+ this.queryLogger.log(`[CachedListenersService] processStreamQuery called for collection: '${collection}', query:`, JSON.stringify(queryParams));
1123
+ // console.log("PROCESS QUERY: " + this.getQueryKey(collection, queryParams, queryOptions));
1124
+ // Get destroyRef for the component that called processStreamQuery
1125
+ // (which will be used to determine when to trigger unsubscribe)
1126
+ const destroyRef = injector.get(DestroyRef);
1127
+ const epoch = this.streamGeneration;
1128
+ // get connection and process the immediate query
1129
+ let connection = this.getConnection(collection, queryParams, queryOptions);
1130
+ if (connection) {
1131
+ // if the connection already exists, don't need to create a new connection,
1132
+ // but may need to add the DestroyRef if it doesn't already exist
1133
+ if (!connection.registeredSet.has(destroyRef)) {
1134
+ connection.registeredSet.add(destroyRef);
1135
+ }
1136
+ }
1137
+ else {
1138
+ // if the connection does not exist, create it and initialize the
1139
+ // registeredSet to include destroyRef
1140
+ // this function also will subscribe and link to the store
1141
+ connection = this.createConnection(collection, store, queryParams, queryOptions, destroyRef);
1142
+ if (!connection.closed)
1143
+ this.connectionByQueryKey[connection.queryKey] = connection;
1144
+ }
1145
+ // Unregister from the connection when the component is destroyed
1146
+ // Disconnects the "virtual" connection. If this was the only DestroyRef,
1147
+ // then actually unsubscribe
1148
+ destroyRef.onDestroy(() => {
1149
+ // Add a 5-second delay so we don't have to reconnect multiple times
1150
+ // if the next view happens to use the same stream
1151
+ setTimeout(() => {
1152
+ // If the destroyRef is not in the set, it means this connection was already
1153
+ // cleared/cleaned up (e.g., via clearCache() in tests), so we bail out.
1154
+ if (!connection.registeredSet.has(destroyRef)) {
1155
+ return;
1156
+ }
1157
+ connection.registeredSet.delete(destroyRef);
1158
+ if (connection.registeredSet.size === 0) {
1159
+ // Verify that this connection is still the active connection in the cache map.
1160
+ // This is essential to prevent stale callbacks (e.g. from a previous test case
1161
+ // that was cleared via clearCache()) from overwriting a new active connection
1162
+ // in the cache or triggering premature disconnections.
1163
+ if (this.connectionByQueryKey[connection.queryKey] === connection) {
1164
+ this.closeConnection$.next(connection.queryKey);
1165
+ this.connectionByQueryKey[connection.queryKey] = undefined;
1166
+ }
1167
+ }
1168
+ }, 5000);
1169
+ });
1170
+ // For every new entity on the stream, process the nested streamQueries
1171
+ if (streamQueries) {
1172
+ // get the entities we're streaming as a signal. we do it here rather than
1173
+ // using the firestore stream so that we can always get the latest version
1174
+ // without needing to multicast the original stream to all future components
1175
+ // querying for the stream
1176
+ const streamEntities = computed(() => {
1177
+ return store.selectEntities(queryParams, queryOptions);
1178
+ }, ...(ngDevMode ? [{ debugName: "streamEntities" }] : /* istanbul ignore next */ []));
1179
+ // convert to an observable, convert to the changes, then subscribe
1180
+ // Global teardown and component destruction both dispose the underlying effect.
1181
+ this.observeNested(streamEntities, injector).pipe(
1182
+ // convert to entityMap to more easily compare
1183
+ map((entities) => {
1184
+ const entityMap = {};
1185
+ for (const entity of entities) {
1186
+ entityMap[entity.__id] = entity;
1187
+ }
1188
+ return entityMap;
1189
+ }),
1190
+ // compare current with prior including the first
1191
+ startWith({}), pairwise(),
1192
+ // get the changedEntities
1193
+ map(([prevEntities, currEntities]) => {
1194
+ const changedEntities = [];
1195
+ for (const key in currEntities) {
1196
+ if (!(key in prevEntities)) {
1197
+ // the entity was added
1198
+ changedEntities.push({
1199
+ type: 'added',
1200
+ doc: currEntities[key],
1201
+ });
1202
+ }
1203
+ else if (currEntities[key]['_deleted']) {
1204
+ // the entity was removed
1205
+ changedEntities.push({
1206
+ type: 'removed',
1207
+ doc: currEntities[key],
1208
+ });
1209
+ }
1210
+ else if (entityChanged(prevEntities[key], currEntities[key])) {
1211
+ // the entity was modified
1212
+ changedEntities.push({
1213
+ type: 'modified',
1214
+ doc: currEntities[key],
1215
+ });
1216
+ }
1217
+ }
1218
+ return changedEntities;
1219
+ }),
1220
+ // We don't need the removed ones for nested streamQueries (but I just
1221
+ // included it above for debugging purposes so we can see all changes)
1222
+ map((changes) => changes.filter((c) => c.type !== 'removed')), filter((changes) => changes.length > 0), mergeMap(async (changes) => {
1223
+ if (epoch !== this.streamGeneration || destroyRef.destroyed)
1224
+ return;
1225
+ // create a matrix of queries, each row corresponding to a given entity
1226
+ const queriesByEntity = changes.map((change) => streamQueries(change.doc));
1227
+ // transpose the matrix so each row corresponds to all queries for the same query type
1228
+ const queriesByQueryType = Array.from({ length: Math.max(0, ...queriesByEntity.map(row => row.length)) }, (_, colIndex) => queriesByEntity.map(row => row[colIndex]).filter(Boolean));
1229
+ // Process all query types concurrently
1230
+ await Promise.all(queriesByQueryType.map(async (queriesForOneType) => {
1231
+ // Seeing if we can optimize by collapsing equality queries into 'in' queries
1232
+ const optimizedQueries = EntityStreamQuery.optimize(queriesForOneType);
1233
+ // Process queries concurrently using Promise.all
1234
+ await Promise.all(optimizedQueries.filter((q) => !!q).map(async (query) => {
1235
+ const isSimpleChild = (!query.queryOptions || Object.keys(query.queryOptions).length === 0) &&
1236
+ query.queryParams.length === 1 &&
1237
+ (query.queryParams[0][1] === '==' || query.queryParams[0][1] === 'in');
1238
+ if (isSimpleChild) {
1239
+ const childField = query.queryParams[0][0];
1240
+ const childOp = query.queryParams[0][1];
1241
+ const childVal = query.queryParams[0][2];
1242
+ const childIds = childOp === 'in' ? childVal : [childVal];
1243
+ this.queryLogger.log(`[CachedListenersService] Nested query optimized to simple stream query: ${childField} in [${childIds}]`);
1244
+ await this.processSimpleStreamQuery(query.collection, childField, childIds, query.store, injector, query.streamQueries, { loading: options?.loading });
1245
+ }
1246
+ else {
1247
+ this.queryLogger.log(`[CachedListenersService] Nested query falling back to standard stream query:`, JSON.stringify(query.queryParams));
1248
+ await this.processStreamQuery(query.collection, query.store, query.queryParams, query.queryOptions, injector, query.streamQueries, { loading: options?.loading });
1249
+ }
1250
+ }));
1251
+ }));
1252
+ })).subscribe({ error: error => this.reportStreamError(error) });
1253
+ }
1254
+ else {
1255
+ // We'll turn off the loading indicator the first time there is a query that doesn't have nested queries
1256
+ // (ideally we'd want to turn if off after each of the streams have gotten their first entities, but I
1257
+ // don't think we can do that easily and this won't be too off)
1258
+ options?.loading?.set(false);
1259
+ }
1260
+ return connection;
1261
+ }
1262
+ /**
1263
+ * Optimized fast-path for simple streaming queries (e.g., `id in [1, 2, 3]`).
1264
+ * Instead of managing distinct complex RxJS subscription chains for every component, this delegates
1265
+ * ID registration to a centralized `StreamMultiplexer` (per collection/field).
1266
+ *
1267
+ * It also handles nested `streamQueries` (e.g. streaming a post's author) by listening to changes
1268
+ * to the parent entities, diffing them (`pairwise`), and setting up streams for the new children.
1269
+ */
1270
+ async processSimpleStreamQuery(collection, field, ids, store, injector, streamQueries, options) {
1271
+ this.queryLogger.log(`[CachedListenersService] processSimpleStreamQuery called for collection: '${collection}', field: '${field}', ids: [${ids}]`);
1272
+ if (!ids || ids.length === 0) {
1273
+ options?.loading?.set(false);
1274
+ return;
1275
+ }
1276
+ const destroyRef = injector.get(DestroyRef);
1277
+ const epoch = this.streamGeneration;
1278
+ const multiplexerKey = stableQueryKey(collection, [[field, '==', null]], {});
1279
+ let multiplexer = this.streamMultiplexers.get(multiplexerKey);
1280
+ if (!multiplexer) {
1281
+ multiplexer = new StreamMultiplexer(collection, field, this.db, store, this.queryLogger, error => this.streamErrors.next(error));
1282
+ this.streamMultiplexers.set(multiplexerKey, multiplexer);
1283
+ }
1284
+ multiplexer.registerIds(ids, destroyRef);
1285
+ if (streamQueries) {
1286
+ // 1. We select the entities from the store.
1287
+ // Because the selectors in `entity-store.ts` cache identical array references, `filteredSignal` will NOT trigger
1288
+ // spurious emissions if the underlying data has not actually changed.
1289
+ const filteredSignal = computed(() => {
1290
+ return store.selectEntities([[field, 'in', ids]], {});
1291
+ }, ...(ngDevMode ? [{ debugName: "filteredSignal" }] : /* istanbul ignore next */ []));
1292
+ // 2. We convert the signal to an observable to perform pairwise diffing.
1293
+ // This is necessary because if a parent entity is added or modified, we need to re-evaluate
1294
+ // its nested `streamQueries` (e.g., if a post's authorId changes, we must query the new author).
1295
+ this.observeNested(filteredSignal, injector).pipe(map((entities) => {
1296
+ const entityMap = {};
1297
+ for (const entity of entities) {
1298
+ entityMap[entity.__id] = entity;
1299
+ }
1300
+ return entityMap;
1301
+ }), startWith({}), pairwise(), map(([prevEntities, currEntities]) => {
1302
+ // 3. Diff the current entities against the previous entities to determine exactly
1303
+ // what was added, removed, or modified. The _deleted flag identifies
1304
+ // deletion. Compare _updatedAt by its timestamp value, and also check
1305
+ // other fields: two writes in the same clock tick can change a post's
1306
+ // authorId without producing different _updatedAt values. Comparing
1307
+ // only timestamps would miss the new author and its nested query.
1308
+ const changedEntities = [];
1309
+ for (const key in currEntities) {
1310
+ if (!(key in prevEntities)) {
1311
+ changedEntities.push({ type: 'added', doc: currEntities[key] });
1312
+ }
1313
+ else if (currEntities[key]['_deleted']) {
1314
+ changedEntities.push({ type: 'removed', doc: currEntities[key] });
1315
+ }
1316
+ else if (entityChanged(prevEntities[key], currEntities[key])) {
1317
+ changedEntities.push({ type: 'modified', doc: currEntities[key] });
1318
+ }
1319
+ }
1320
+ return changedEntities;
1321
+ }), map((changes) => changes.filter((c) => c.type !== 'removed')), filter((changes) => changes.length > 0), mergeMap(async (changes) => {
1322
+ if (epoch !== this.streamGeneration || destroyRef.destroyed)
1323
+ return;
1324
+ // 4. For every changed entity, evaluate its nested stream queries.
1325
+ const queriesByEntity = changes.map((change) => streamQueries(change.doc));
1326
+ if (queriesByEntity.length === 0)
1327
+ return;
1328
+ // 5. Transpose the matrix so each row corresponds to all queries of the same query type.
1329
+ // This allows us to group and optimize queries (e.g., combining 5 single equality queries into 1 'in' query).
1330
+ const queriesByQueryType = Array.from({ length: Math.max(0, ...queriesByEntity.map(row => row.length)) }, (_, colIndex) => queriesByEntity.map(row => row[colIndex]).filter(Boolean));
1331
+ await Promise.all(queriesByQueryType.map(async (queriesForOneType) => {
1332
+ const optimizedQueries = EntityStreamQuery.optimize(queriesForOneType);
1333
+ await Promise.all(optimizedQueries.filter((q) => !!q).map(async (query) => {
1334
+ const isSimpleChild = (!query.queryOptions || Object.keys(query.queryOptions).length === 0) &&
1335
+ query.queryParams.length === 1 &&
1336
+ (query.queryParams[0][1] === '==' || query.queryParams[0][1] === 'in');
1337
+ if (isSimpleChild) {
1338
+ const childField = query.queryParams[0][0];
1339
+ const childOp = query.queryParams[0][1];
1340
+ const childVal = query.queryParams[0][2];
1341
+ const childIds = childOp === 'in' ? childVal : [childVal];
1342
+ this.queryLogger.log(`[CachedListenersService] Nested query optimized to simple stream query: ${childField} in [${childIds}]`);
1343
+ await this.processSimpleStreamQuery(query.collection, childField, childIds, query.store, injector, query.streamQueries, { loading: options?.loading });
1344
+ }
1345
+ else {
1346
+ this.queryLogger.log(`[CachedListenersService] Nested query falling back to standard stream query:`, JSON.stringify(query.queryParams));
1347
+ await this.processStreamQuery(query.collection, query.store, query.queryParams, query.queryOptions, injector, query.streamQueries, { loading: options?.loading });
1348
+ }
1349
+ }));
1350
+ }));
1351
+ })).subscribe({ error: error => this.reportStreamError(error) });
1352
+ }
1353
+ // We'll turn off the loading indicator right away since we don't have a good way
1354
+ // to know when all individual streams are initialized yet.
1355
+ options?.loading?.set(false);
1356
+ }
1357
+ createConnection(collection, store, queryParams, queryOptions, destroyRef) {
1358
+ // console.log("CONNECT " + this.getQueryKey(collection, queryParams, queryOptions));
1359
+ // ------------ DEFINE OBSERVABLES FOR DISCONNECTING ------------------------------
1360
+ const queryKey = this.getQueryKey(collection, queryParams, queryOptions);
1361
+ const disconnectObs$ = this.closeConnection$.pipe(filter((qk) => qk === queryKey), take(1),
1362
+ // tap(a => { console.log("DISCONNECT: " + queryKey) }),
1363
+ share());
1364
+ const connection = { queryKey, registeredSet: new Set([destroyRef]) };
1365
+ // ------------ HANDLE PATCHING TO STORE ------------------------------------------
1366
+ // Handle patching to the store
1367
+ this.db.streamEntitiesChanges(collection, queryParams, queryOptions).pipe(takeUntil(disconnectObs$)).subscribe({ next: (fbPayload) => {
1368
+ // Handle all the added entities
1369
+ const entitiesToAdd = fbPayload
1370
+ .filter((dc) => dc.type === 'added' && !dc.docData['_deleted'])
1371
+ .map((dc) => dc.docData);
1372
+ // Handle all the modified entities
1373
+ const entitiesToModify = fbPayload
1374
+ .filter((dc) => dc.type === 'modified' && !dc.docData['_deleted'])
1375
+ .map((dc) => dc.docData);
1376
+ // Handle all the removed entities
1377
+ const entitiesToRemove = fbPayload
1378
+ .filter((dc) => dc.type === 'modified' && dc.docData['_deleted'])
1379
+ .map((dc) => dc.docData['__id']);
1380
+ // Handle changes of the 'removed' type. In general, firebase 'removed'
1381
+ // could be due to no longer matching the stream query rather than being
1382
+ // deleted from the DB. this is why we use soft deletes (set _deleted to true).
1383
+ // We could still get 'removed' entries if there are manual deletions in the
1384
+ // database or when firestore is syncing updates after temporarily using
1385
+ // entities cached to IndexedDB.
1386
+ const entitiesToModify2 = fbPayload
1387
+ .filter((dc) => dc.type === 'removed' && !entityInQueryResults(dc.docData, queryParams, queryOptions))
1388
+ .map((dc) => dc.docData);
1389
+ const entitiesToRemove2 = fbPayload
1390
+ .filter((dc) => dc.type === 'removed' && entityInQueryResults(dc.docData, queryParams, queryOptions))
1391
+ .map((dc) => dc.docData['__id']);
1392
+ // Patch all the changes to the store
1393
+ store.handleStreamChanges(entitiesToAdd, [...entitiesToModify, ...entitiesToModify2], [...entitiesToRemove, ...entitiesToRemove2]);
1394
+ }, error: error => {
1395
+ connection.closed = true;
1396
+ connection.registeredSet.clear();
1397
+ this.streamErrors.next(error);
1398
+ this.queryLogger.error('Data stream failed; a subsequent stream request can retry.', error);
1399
+ this.closeConnection$.next(queryKey);
1400
+ delete this.connectionByQueryKey[queryKey];
1401
+ } });
1402
+ return connection;
1403
+ }
1404
+ constructor(db) {
1405
+ this.db = db;
1406
+ }
1407
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.23", ngImport: i0, type: CachedListenersService, deps: [{ token: DATA_ACCESS }], target: i0.ɵɵFactoryTarget.Injectable });
1408
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.23", ngImport: i0, type: CachedListenersService, providedIn: 'root' });
1409
+ }
1410
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.23", ngImport: i0, type: CachedListenersService, decorators: [{
1411
+ type: Injectable,
1412
+ args: [{
1413
+ providedIn: 'root',
1414
+ }]
1415
+ }], ctorParameters: () => [{ type: undefined, decorators: [{
1416
+ type: Inject,
1417
+ args: [DATA_ACCESS]
1418
+ }] }] });
1419
+
1420
+ /**
1421
+ * Present successful-write feedback with an optional compensating undo.
1422
+ * Backend restoration must succeed before local state is reverted. Inverse
1423
+ * operations run in reverse order so dependent writes unwind correctly.
1424
+ * Undo is a new write attempt, not cancellation of the original commit.
1425
+ */
1426
+ function openSnackBarWithUndoOption(snackBar, snackBarConfig, revertFns, dbRevertFns, revertBatch) {
1427
+ const snackBarRef = snackBar.open(snackBarConfig.successMessage, snackBarConfig.undoOnAction ? 'Undo' : '', snackBarConfig.config);
1428
+ // if there is an undo option for the snackbar, then we should
1429
+ // revert both local and database changes if the undo was clicked
1430
+ if (snackBarConfig.undoOnAction) {
1431
+ snackBarRef.onAction().subscribe(async () => {
1432
+ try {
1433
+ // first try to undo changes on the database
1434
+ // dbRevertFns will directly remove from DB if not in the batch setting.
1435
+ // if it is a batch setting, it will do revertBatch.set to prepare
1436
+ // revertBatch for a commit
1437
+ for (const dbRevertFn of [...dbRevertFns].reverse())
1438
+ await dbRevertFn();
1439
+ if (revertBatch) {
1440
+ await revertBatch.commit();
1441
+ }
1442
+ // if successful, then undo changes locally too
1443
+ [...revertFns].reverse().forEach((revertFn) => revertFn());
1444
+ }
1445
+ catch (e) {
1446
+ console.error(e);
1447
+ snackBar.open('Failed to undo', '', {
1448
+ duration: 3000,
1449
+ });
1450
+ }
1451
+ });
1452
+ }
1453
+ }
1454
+
1455
+ const selectId = (entity) => entity.__id;
1456
+ /**
1457
+ * Add in-memory entity state, stream-change application and synchronous selectors.
1458
+ * Selectors hide soft-deleted records and only inspect already-loaded state;
1459
+ * they do not query the backend. Used by frontend and mock backend stores.
1460
+ */
1461
+ function withEntitiesAndSelectMethods() {
1462
+ return signalStoreFeature(withEntities(), withMethods((store) => {
1463
+ const queryCache = new Map();
1464
+ return {
1465
+ handleStreamChanges(entitiesToAdd, entitiesToModify, entitiesToRemove) {
1466
+ patchState(store, setEntities(entitiesToAdd, { selectId }));
1467
+ patchState(store, setEntities(entitiesToModify, { selectId }));
1468
+ patchState(store, removeEntities(entitiesToRemove));
1469
+ },
1470
+ selectEntity(id) {
1471
+ const result = store.entityMap()[id];
1472
+ if (result && !result['_deleted']) {
1473
+ return result;
1474
+ }
1475
+ else {
1476
+ return null;
1477
+ }
1478
+ },
1479
+ selectFirst(queryParams, queryOptions) {
1480
+ // Note: selectEntities already filters out _deleted
1481
+ const entities = selectEntities(store.entityMap(), queryParams, queryOptions);
1482
+ if (entities && entities.length > 0) {
1483
+ return entities[0];
1484
+ }
1485
+ else {
1486
+ return null;
1487
+ }
1488
+ },
1489
+ selectEntities(queryParams, queryOptions) {
1490
+ // Note: The global standalone selectEntities function already filters out entities with _deleted: true
1491
+ const result = selectEntities(store.entityMap(), queryParams, queryOptions);
1492
+ const key = JSON.stringify({ queryParams, queryOptions });
1493
+ // CRITICAL: Angular's computed() signals rely on strict referential equality (===).
1494
+ // Because Object.values().filter() creates a brand new array reference every time it is called,
1495
+ // any computed signal that calls selectEntities() would trigger an update even if the contents
1496
+ // of the array are identical. This led to infinite loops and massive memory leaks in nested streams.
1497
+ // By memoizing the array reference here, we ensure that if the query results are strictly identical
1498
+ // (same length, same entity references in the exact same order), we return the exact same array reference.
1499
+ const lastResult = queryCache.get(key);
1500
+ if (lastResult && lastResult.length === result.length && lastResult.every((v, i) => v === result[i])) {
1501
+ return lastResult;
1502
+ }
1503
+ queryCache.set(key, result);
1504
+ // Bound retained query results to 50 keys, evicting in insertion order.
1505
+ if (queryCache.size > 50) {
1506
+ const firstKey = queryCache.keys().next().value;
1507
+ if (firstKey)
1508
+ queryCache.delete(firstKey);
1509
+ }
1510
+ return result;
1511
+ },
1512
+ };
1513
+ }));
1514
+ }
1515
+ /**
1516
+ * Add collection-specific load/stream/write methods to an NgRx signal store.
1517
+ * Provide one root store per collection so components share records and listeners.
1518
+ * DATA_ACCESS selects the backend. The app ends listeners through the cache service
1519
+ * and explicitly chooses which local stores to reset during logout.
1520
+ *
1521
+ * @example
1522
+ * export const ProblemStore = signalStore(
1523
+ * { providedIn: 'root' },
1524
+ * withEntitiesAndDBMethods<Problem>(problemEntity.collection),
1525
+ * );
1526
+ */
1527
+ function withEntitiesAndDBMethods(collectionName) {
1528
+ return signalStoreFeature(withEntitiesAndSelectMethods(), withMethods((store, cachedLoads = inject(CachedListenersService), db = inject(DATA_ACCESS), snackBar = inject(DATA_FEEDBACK), logger = injectLogger('data')) => ({
1529
+ /** Replace local state only; no records are written to the backend. */
1530
+ init(entities) {
1531
+ patchState(store, setAllEntities(entities, { selectId }));
1532
+ },
1533
+ /** Empty this collection’s records and load history; listener teardown is separate. */
1534
+ reset() {
1535
+ cachedLoads.clearLoadHistory(collectionName);
1536
+ patchState(store, setAllEntities([], { selectId }));
1537
+ },
1538
+ /**
1539
+ * Keep query results current for the lifetime of the caller's injector.
1540
+ * Pass a component/route injector, not the root injector, for scoped cleanup.
1541
+ * To reduce redundant database reads, matching queries reuse cached listeners.
1542
+ * After navigating away from a container, its listener claim has a 5-second
1543
+ * grace period before release, allowing a quick return to reuse the listener.
1544
+ * The injector's DestroyRef handles this; containers do not manually disconnect IDs.
1545
+ *
1546
+ * Nested streamQueries establish child streams, with simple equality filters
1547
+ * combined by the multiplexer to avoid one listener per parent. The older
1548
+ * comment about nested queries being load-only does not describe this method:
1549
+ * use load() and loadQueries for nested one-shot reads instead.
1550
+ */
1551
+ async stream(queryParams, queryOptions, injector, streamQueries, options) {
1552
+ try {
1553
+ // start loading icon if available
1554
+ options?.loading?.set(true);
1555
+ const isSimpleEqualityQuery = (!queryOptions || Object.keys(queryOptions).length === 0) &&
1556
+ queryParams.length === 1 &&
1557
+ (queryParams[0][1] === '==' || queryParams[0][1] === 'in');
1558
+ if (isSimpleEqualityQuery) {
1559
+ const field = queryParams[0][0];
1560
+ const ids = queryParams[0][1] === 'in' ? queryParams[0][2] : [queryParams[0][2]];
1561
+ await cachedLoads.processSimpleStreamQuery(collectionName, field, ids, store, injector, streamQueries, options);
1562
+ }
1563
+ else {
1564
+ await cachedLoads.processStreamQuery(collectionName, store, queryParams, queryOptions, injector, streamQueries, options);
1565
+ }
1566
+ }
1567
+ catch (e) {
1568
+ logger.error(e);
1569
+ // stop loading icon. when no error, loading icon is stopped
1570
+ // upon the initial payload coming through the stream and the
1571
+ // loadQueries being processed
1572
+ options?.loading?.set(false);
1573
+ throw e;
1574
+ }
1575
+ },
1576
+ /**
1577
+ * Fetch once, then evaluate nested loads against all matching local records.
1578
+ * Loading reduces redundant reads in the following ways when there are no
1579
+ * queryOptions:
1580
+ * - If a matching listener already covers the data, let it keep the store current.
1581
+ * - Otherwise, load active records updated since the last load (_deleted == false).
1582
+ * - Also query for records deleted since that load (_deleted == true), so their
1583
+ * IDs can be removed from the frontend store. The active query cannot report them.
1584
+ * - Calculate loadQueries from the matching entities in the store, including
1585
+ * both the newly fetched changes and records loaded earlier. A delta response
1586
+ * alone would miss unchanged parents whose related data still needs loading.
1587
+ *
1588
+ * Ordering/limits/cursors disable delta caching because adding a time filter
1589
+ * would change the requested result window. A first load has no previous cutoff.
1590
+ */
1591
+ async load(queryParams, queryOptions, loadQueries, options) {
1592
+ try {
1593
+ // start loading icon if available
1594
+ options?.loading?.set(true);
1595
+ const isBatchableEqualityOrIn = (!queryOptions || Object.keys(queryOptions).length === 0) &&
1596
+ queryParams.length === 1 &&
1597
+ (queryParams[0][1] === '==' || queryParams[0][1] === 'in');
1598
+ if (!isBatchableEqualityOrIn) {
1599
+ // ---------------------------------------------------------
1600
+ // LEGACY PATH: Non-equality queries use full query-string tracking
1601
+ // ---------------------------------------------------------
1602
+ // only load if there is not already a listener for the same query
1603
+ if (!cachedLoads.isStreamForQuery(collectionName, queryParams, queryOptions)) {
1604
+ // get the last load time and next load time
1605
+ const lastLoadTime = cachedLoads.getLastLoadTime(collectionName, queryParams, queryOptions);
1606
+ const newLoadTime = Date.now();
1607
+ // load entities since last load that are not deleted
1608
+ // note that we always load all entities if there exist queryOptions since adding
1609
+ // the _updatedAt filter will change queries with limit
1610
+ let queryParamsWithTime;
1611
+ if (lastLoadTime === -1 || (queryOptions && Object.keys(queryOptions).length > 0)) {
1612
+ queryParamsWithTime = [...queryParams, ['_deleted', '==', false]];
1613
+ }
1614
+ else {
1615
+ queryParamsWithTime = [
1616
+ ...queryParams,
1617
+ ['_updatedAt', '>', dataTimestampFromMillis(lastLoadTime)],
1618
+ ['_deleted', '==', false],
1619
+ ];
1620
+ }
1621
+ // get entities that have been added or updated since last load
1622
+ const entitiesDelta = await db.getEntities(collectionName, queryParamsWithTime, queryOptions);
1623
+ patchState(store, setEntities(entitiesDelta, { selectId }));
1624
+ // delete any new deleted entities
1625
+ if (lastLoadTime === -1 || (queryOptions && Object.keys(queryOptions).length > 0)) {
1626
+ const entitiesDeletedDelta = await db.getEntities(collectionName, [...queryParams, ['_deleted', '==', true]], queryOptions);
1627
+ patchState(store, removeEntities(entitiesDeletedDelta.map((e) => e.__id)));
1628
+ }
1629
+ else {
1630
+ const entitiesDeletedDelta = await db.getEntities(collectionName, [...queryParams,
1631
+ ['_updatedAt', '>', dataTimestampFromMillis(lastLoadTime)],
1632
+ ['_deleted', '==', true]], queryOptions);
1633
+ patchState(store, removeEntities(entitiesDeletedDelta.map((e) => e.__id)));
1634
+ }
1635
+ // save a new lastLoadTime for this query
1636
+ cachedLoads.setLastLoadTime(collectionName, queryParams, queryOptions, newLoadTime);
1637
+ }
1638
+ }
1639
+ else {
1640
+ // ---------------------------------------------------------
1641
+ // OPTIMIZED PATH: Per-entity tracking for == and in queries
1642
+ // ---------------------------------------------------------
1643
+ const field = queryParams[0][0];
1644
+ const operator = queryParams[0][1];
1645
+ const rawValues = operator === '==' ? [queryParams[0][2]] : queryParams[0][2];
1646
+ // 1. Remove IDs already covered by active streams
1647
+ const valuesToLoad = rawValues.filter((v) => {
1648
+ // Check if it's covered by a multiplexer stream
1649
+ if (cachedLoads.isIdStreamed(collectionName, field, v))
1650
+ return false;
1651
+ return true;
1652
+ });
1653
+ if (valuesToLoad.length > 0) {
1654
+ const newLoadTime = Date.now();
1655
+ if (field === '__id' && valuesToLoad.length === 1) {
1656
+ const idToFetch = valuesToLoad[0];
1657
+ logger.log(`[Store] Optimized Load Triggered for collection '${collectionName}', fetching single ID using getDoc.`);
1658
+ const entity = await db.getEntity(collectionName, idToFetch);
1659
+ if (entity) {
1660
+ if (entity._deleted) {
1661
+ patchState(store, removeEntities([idToFetch]));
1662
+ }
1663
+ else {
1664
+ patchState(store, setEntities([entity], { selectId }));
1665
+ }
1666
+ }
1667
+ else {
1668
+ patchState(store, removeEntities([idToFetch]));
1669
+ }
1670
+ cachedLoads.setEntityLoadTime(collectionName, field, idToFetch, newLoadTime);
1671
+ }
1672
+ else {
1673
+ // 2. Group values by their entityLoadTime (Time Bucketing Strategy)
1674
+ // To prevent the N+1 problem of issuing dozens of queries for items with slightly
1675
+ // different load times, we group loaded items into 5-minute buckets.
1676
+ // Unloaded items (-1) are strictly kept in their own bucket to prevent over-fetching.
1677
+ const BUCKET_MS = 5 * 60 * 1000;
1678
+ // Map bucket index to the exact minimum time in that bucket and its values
1679
+ const groupsByBucket = new Map();
1680
+ logger.log(`[Store] Optimized Load Triggered for collection '${collectionName}', tracking ${valuesToLoad.length} IDs.`);
1681
+ valuesToLoad.forEach((val) => {
1682
+ const time = cachedLoads.getEntityLoadTime(collectionName, field, val);
1683
+ const bucketIndex = time === -1 ? -1 : Math.floor(time / BUCKET_MS);
1684
+ if (!groupsByBucket.has(bucketIndex)) {
1685
+ groupsByBucket.set(bucketIndex, { minTime: time, values: [] });
1686
+ }
1687
+ const group = groupsByBucket.get(bucketIndex);
1688
+ // Track the earliest load time in this bucket
1689
+ if (time !== -1 && time < group.minTime) {
1690
+ group.minTime = time;
1691
+ }
1692
+ group.values.push(val);
1693
+ });
1694
+ // 3. For each group, execute DB fetches
1695
+ logger.log(`[Store] Grouped ${valuesToLoad.length} IDs into ${groupsByBucket.size} time bucket(s).`);
1696
+ await Promise.all(Array.from(groupsByBucket.entries()).map(async ([bucketIndex, group]) => {
1697
+ const lastTime = group.minTime;
1698
+ const groupValues = group.values;
1699
+ logger.log(`[Store] Bucket ${bucketIndex === -1 ? '(-1: Never Loaded)' : bucketIndex} (minTime: ${lastTime === -1 ? 'Never' : new Date(lastTime).toISOString()}) fetching ${groupValues.length} IDs.`);
1700
+ // Chunk into 30s
1701
+ for (let i = 0; i < groupValues.length; i += 30) {
1702
+ const chunk = groupValues.slice(i, i + 30);
1703
+ const batchedParams = [[field, 'in', chunk]];
1704
+ logger.log(`[Store] -> Fetching chunk of ${chunk.length} IDs...`);
1705
+ // Fetch changed entities
1706
+ let queryParamsWithTime;
1707
+ if (lastTime === -1) {
1708
+ queryParamsWithTime = [...batchedParams, ['_deleted', '==', false]];
1709
+ }
1710
+ else {
1711
+ queryParamsWithTime = [
1712
+ ...batchedParams,
1713
+ ['_updatedAt', '>', dataTimestampFromMillis(lastTime)],
1714
+ ['_deleted', '==', false],
1715
+ ];
1716
+ }
1717
+ const entitiesDelta = await db.getEntities(collectionName, queryParamsWithTime, {});
1718
+ if (entitiesDelta.length > 0) {
1719
+ logger.log(`[Store] -> Loaded ${entitiesDelta.length} updated/new entities from chunk.`);
1720
+ }
1721
+ patchState(store, setEntities(entitiesDelta, { selectId }));
1722
+ // Fetch soft-deleted entities
1723
+ let deletedParamsWithTime;
1724
+ if (lastTime === -1) {
1725
+ deletedParamsWithTime = [...batchedParams, ['_deleted', '==', true]];
1726
+ }
1727
+ else {
1728
+ deletedParamsWithTime = [
1729
+ ...batchedParams,
1730
+ ['_updatedAt', '>', dataTimestampFromMillis(lastTime)],
1731
+ ['_deleted', '==', true],
1732
+ ];
1733
+ }
1734
+ const entitiesDeletedDelta = await db.getEntities(collectionName, deletedParamsWithTime, {});
1735
+ if (entitiesDeletedDelta.length > 0) {
1736
+ logger.log(`[Store] -> Removed ${entitiesDeletedDelta.length} soft-deleted entities from chunk.`);
1737
+ }
1738
+ patchState(store, removeEntities(entitiesDeletedDelta.map(selectId)));
1739
+ }
1740
+ }));
1741
+ // 4. Update entityLoadTime for all fetched values to the unified newLoadTime
1742
+ valuesToLoad.forEach((val) => cachedLoads.setEntityLoadTime(collectionName, field, val, newLoadTime));
1743
+ }
1744
+ }
1745
+ }
1746
+ if (loadQueries) {
1747
+ // retrieve entities from store for loading queries
1748
+ // note we cannot simply use entities from load since it may not be all entities (only those for which updatedAt > lastLoadTime)
1749
+ const allQueriedEntities = store.selectEntities(queryParams, queryOptions);
1750
+ await processLoadQueries(allQueriedEntities, loadQueries);
1751
+ }
1752
+ }
1753
+ catch (e) {
1754
+ logger.error(e);
1755
+ throw e;
1756
+ }
1757
+ finally {
1758
+ // stop loading icon
1759
+ options?.loading?.set(false);
1760
+ }
1761
+ },
1762
+ /** Count active backend records; does not populate the local entity store. */
1763
+ async count(queryParams, queryOptions, options) {
1764
+ try {
1765
+ // start loading icon if available
1766
+ options?.loading?.set(true);
1767
+ const queryParamsNotDeleted = [...queryParams, ['_deleted', '==', false]];
1768
+ return await db.count(collectionName, queryParamsNotDeleted, queryOptions);
1769
+ }
1770
+ catch (e) {
1771
+ logger.error(e);
1772
+ throw e;
1773
+ }
1774
+ finally {
1775
+ // stop loading icon
1776
+ options?.loading?.set(false);
1777
+ }
1778
+ },
1779
+ /** Compute backend aggregates over active records without loading them locally. */
1780
+ async aggregate(queryParams, queryOptions, aggregateParams, options) {
1781
+ try {
1782
+ // start loading icon if available
1783
+ options?.loading?.set(true);
1784
+ const queryParamsNotDeleted = [...queryParams, ['_deleted', '==', false]];
1785
+ return await db.aggregate(collectionName, queryParamsNotDeleted, queryOptions, aggregateParams);
1786
+ }
1787
+ catch (e) {
1788
+ logger.error(e);
1789
+ throw e;
1790
+ }
1791
+ finally {
1792
+ // stop loading icon
1793
+ options?.loading?.set(false);
1794
+ }
1795
+ },
1796
+ async increment(id, field, delta, options) {
1797
+ // get current value
1798
+ const currEntityValue = store.entityMap()[id];
1799
+ const changes = {};
1800
+ changes[field] = (typeof currEntityValue?.[field] === 'number' ? currEntityValue[field] : 0) + delta;
1801
+ changes['_updatedAt'] = dataTimestampNow();
1802
+ if (options?.optimistic) {
1803
+ try {
1804
+ // optimistically set then query backend
1805
+ patchState(store, updateEntity({
1806
+ id,
1807
+ changes: Object.assign({}, changes, {
1808
+ _updatedAt: dataTimestampNow(),
1809
+ }),
1810
+ }, { selectId }));
1811
+ await db.incrementEntityField(collectionName, id, field, delta);
1812
+ }
1813
+ catch (e) {
1814
+ // undo ngrx store value
1815
+ if (currEntityValue) {
1816
+ patchState(store, setEntity(currEntityValue, { selectId }));
1817
+ }
1818
+ else {
1819
+ patchState(store, removeEntity(id));
1820
+ }
1821
+ logger.error(e);
1822
+ throw e;
1823
+ }
1824
+ }
1825
+ else {
1826
+ try {
1827
+ // start loading icon
1828
+ options?.loading?.set(true);
1829
+ // update entity
1830
+ await db.incrementEntityField(collectionName, id, field, delta);
1831
+ patchState(store, updateEntity({
1832
+ id,
1833
+ changes: Object.assign({}, changes, {
1834
+ _updatedAt: dataTimestampNow(),
1835
+ }),
1836
+ }, { selectId }));
1837
+ }
1838
+ catch (e) {
1839
+ logger.error(e);
1840
+ throw e;
1841
+ }
1842
+ finally {
1843
+ // stop loading icon
1844
+ options?.loading?.set(false);
1845
+ }
1846
+ }
1847
+ },
1848
+ /**
1849
+ * Create a record from domain fields, supplying ID/metadata when absent.
1850
+ * Local patches may run optimistically or after success; batchConfig queues
1851
+ * them under the batch coordinator instead of committing immediately.
1852
+ */
1853
+ async add(entityOpId, options) {
1854
+ // Create an __id if one was not provided
1855
+ const entity = Object.assign({}, entityOpId, {
1856
+ __id: entityOpId['__id'] || db.createId(),
1857
+ });
1858
+ // Function for setting the entity locally
1859
+ const patchFn = () => {
1860
+ patchState(store, setEntity(Object.assign({}, entity, {
1861
+ _updatedAt: dataTimestampNow(),
1862
+ _createdAt: entity._createdAt ?? dataTimestampNow(),
1863
+ _deleted: false,
1864
+ }), { selectId }));
1865
+ };
1866
+ // Function for reverting changes for optimistic adds
1867
+ const currEntityValue = store.entityMap()[entity.__id];
1868
+ const revertFn = () => {
1869
+ if (currEntityValue) {
1870
+ patchState(store, setEntity(currEntityValue, { selectId }));
1871
+ }
1872
+ else {
1873
+ patchState(store, removeEntity(entity.__id));
1874
+ }
1875
+ };
1876
+ // Function for reverting changes to the DB when 'Undo' is clicked in the snackbar
1877
+ const dbRevertFn = async () => {
1878
+ try {
1879
+ if (currEntityValue) {
1880
+ await db.addEntity(collectionName, currEntityValue, options?.batchConfig?.revertBatch);
1881
+ }
1882
+ else {
1883
+ await db.removeEntity(collectionName, entity.__id, options?.batchConfig?.revertBatch);
1884
+ }
1885
+ }
1886
+ catch (e) {
1887
+ logger.error(e);
1888
+ throw e;
1889
+ }
1890
+ };
1891
+ // Add the patchFn, revertFn, dbRevertFn if this is a batch write
1892
+ options?.batchConfig?.patchFns?.push(patchFn);
1893
+ options?.batchConfig?.revertFns?.push(revertFn);
1894
+ options?.batchConfig?.dbRevertFns?.push(dbRevertFn);
1895
+ // optimistically set locally, then in backend and revert if needed
1896
+ if (options?.optimistic || options?.batchConfig?.optimistic) {
1897
+ patchFn();
1898
+ try {
1899
+ await db.addEntity(collectionName, entity, options?.batchConfig?.batch);
1900
+ // it will only go into here when not in a batch setting
1901
+ // since there is no snackBarConfig in the a batch seting
1902
+ if (options?.snackBarConfig) {
1903
+ openSnackBarWithUndoOption(snackBar, options.snackBarConfig, [revertFn], [dbRevertFn]);
1904
+ }
1905
+ }
1906
+ catch (e) {
1907
+ // will only get here when it's not a batch
1908
+ revertFn();
1909
+ logger.error(e);
1910
+ if (options?.snackBarConfig) {
1911
+ snackBar.open(options.snackBarConfig.failureMessage, '', options.snackBarConfig.config);
1912
+ }
1913
+ throw e;
1914
+ }
1915
+ // set in backend and then locally if successful
1916
+ }
1917
+ else {
1918
+ // start loading icon
1919
+ options?.loading?.set(true);
1920
+ try {
1921
+ await db.addEntity(collectionName, entity, options?.batchConfig?.batch);
1922
+ // only patch if not using batch writes since if we're using
1923
+ // batch writes, we should be patching after the batch write
1924
+ // is successful
1925
+ if (!options?.batchConfig?.batch) {
1926
+ patchFn();
1927
+ if (options?.snackBarConfig) {
1928
+ openSnackBarWithUndoOption(snackBar, options.snackBarConfig, [revertFn], [dbRevertFn]);
1929
+ }
1930
+ }
1931
+ }
1932
+ catch (e) {
1933
+ logger.error(e);
1934
+ // will only get here when it's not a batch
1935
+ if (options?.snackBarConfig) {
1936
+ snackBar.open(options.snackBarConfig.failureMessage, '', options.snackBarConfig.config);
1937
+ }
1938
+ throw e;
1939
+ }
1940
+ finally {
1941
+ // stop loading icon
1942
+ options?.loading?.set(false);
1943
+ }
1944
+ }
1945
+ },
1946
+ /** Update a record with rollback/undo support and an advanced _updatedAt value. */
1947
+ async update(id, changes, options) {
1948
+ // Function for updating the entity locally
1949
+ const patchFn = () => {
1950
+ patchState(store, updateEntity({
1951
+ id,
1952
+ changes: Object.assign({}, changes, {
1953
+ _updatedAt: dataTimestampNow(),
1954
+ }),
1955
+ }, { selectId }));
1956
+ };
1957
+ // Function for reverting changes for optimistic updates
1958
+ const currEntityValue = store.entityMap()[id];
1959
+ const revertFn = () => {
1960
+ if (currEntityValue) {
1961
+ patchState(store, setEntity(currEntityValue, { selectId }));
1962
+ }
1963
+ else {
1964
+ patchState(store, removeEntity(id));
1965
+ }
1966
+ };
1967
+ // Function for reverting changes to the DB when 'Undo' is clicked in the snackbar
1968
+ const dbRevertFn = async () => {
1969
+ try {
1970
+ if (currEntityValue) {
1971
+ await db.addEntity(collectionName, currEntityValue, options?.batchConfig?.revertBatch);
1972
+ }
1973
+ else {
1974
+ await db.removeEntity(collectionName, id, options?.batchConfig?.revertBatch);
1975
+ }
1976
+ }
1977
+ catch (e) {
1978
+ logger.error(e);
1979
+ throw e;
1980
+ }
1981
+ };
1982
+ // Add the patchFn, revertFn, dbRevertFn if this is a batch write
1983
+ options?.batchConfig?.patchFns?.push(patchFn);
1984
+ options?.batchConfig?.revertFns?.push(revertFn);
1985
+ options?.batchConfig?.dbRevertFns?.push(dbRevertFn);
1986
+ // optimistically update locally, then in backend and revert if needed
1987
+ if (options?.optimistic || options?.batchConfig?.optimistic) {
1988
+ patchFn();
1989
+ try {
1990
+ await db.updateEntity(collectionName, id, changes, options?.batchConfig?.batch);
1991
+ // it will only go into here when not in a batch setting
1992
+ // since there is no snackBarConfig in the a batch seting
1993
+ if (options?.snackBarConfig) {
1994
+ openSnackBarWithUndoOption(snackBar, options.snackBarConfig, [revertFn], [dbRevertFn]);
1995
+ }
1996
+ }
1997
+ catch (e) {
1998
+ // will only get here when it's not a batch
1999
+ revertFn();
2000
+ logger.error(e);
2001
+ if (options?.snackBarConfig) {
2002
+ snackBar.open(options.snackBarConfig.failureMessage, '', options.snackBarConfig.config);
2003
+ }
2004
+ throw e;
2005
+ }
2006
+ // update in backend and then locally if successful
2007
+ }
2008
+ else {
2009
+ // start loading icon
2010
+ options?.loading?.set(true);
2011
+ try {
2012
+ await db.updateEntity(collectionName, id, changes, options?.batchConfig?.batch);
2013
+ // only patch if not using batch writes since if we're using
2014
+ // batch writes, we should be patching after the batch write
2015
+ // is successful
2016
+ if (!options?.batchConfig?.batch) {
2017
+ patchFn();
2018
+ if (options?.snackBarConfig) {
2019
+ openSnackBarWithUndoOption(snackBar, options.snackBarConfig, [revertFn], [dbRevertFn]);
2020
+ }
2021
+ }
2022
+ }
2023
+ catch (e) {
2024
+ logger.error(e);
2025
+ // will only get here when it's not a batch
2026
+ if (options?.snackBarConfig) {
2027
+ snackBar.open(options.snackBarConfig.failureMessage, '', options.snackBarConfig.config);
2028
+ }
2029
+ throw e;
2030
+ }
2031
+ finally {
2032
+ // stop loading icon
2033
+ options?.loading?.set(false);
2034
+ }
2035
+ }
2036
+ },
2037
+ /** Remove locally and soft-delete remotely so other clients can observe the change. */
2038
+ async remove(id, options) {
2039
+ // Function for updating the entity locally
2040
+ const patchFn = () => {
2041
+ patchState(store, removeEntity(id));
2042
+ };
2043
+ // Function for reverting changes for optimistic deletes
2044
+ const currEntityValue = store.entityMap()[id];
2045
+ const revertFn = () => {
2046
+ if (currEntityValue) {
2047
+ patchState(store, setEntity(currEntityValue, { selectId }));
2048
+ }
2049
+ };
2050
+ // Function for reverting changes to the DB when 'Undo' is clicked in the snackbar
2051
+ const dbRevertFn = async () => {
2052
+ try {
2053
+ if (currEntityValue) {
2054
+ await db.addEntity(collectionName, currEntityValue, options?.batchConfig?.revertBatch);
2055
+ }
2056
+ }
2057
+ catch (e) {
2058
+ logger.error(e);
2059
+ throw e;
2060
+ }
2061
+ };
2062
+ // Add the patchFn, revertFn, dbRevertFn if this is a batch write
2063
+ options?.batchConfig?.patchFns?.push(patchFn);
2064
+ options?.batchConfig?.revertFns?.push(revertFn);
2065
+ options?.batchConfig?.dbRevertFns?.push(dbRevertFn);
2066
+ // optimistically remove locally, then in backend and revert if needed
2067
+ if (options?.optimistic || options?.batchConfig?.optimistic) {
2068
+ patchFn();
2069
+ try {
2070
+ await db.removeEntity(collectionName, id, options?.batchConfig?.batch);
2071
+ // it will only go into here when not in a batch setting
2072
+ // since there is no snackBarConfig in the a batch seting
2073
+ if (options?.snackBarConfig) {
2074
+ openSnackBarWithUndoOption(snackBar, options.snackBarConfig, [revertFn], [dbRevertFn]);
2075
+ }
2076
+ }
2077
+ catch (e) {
2078
+ // will only get here when it's not a batch
2079
+ revertFn();
2080
+ logger.error(e);
2081
+ if (options?.snackBarConfig) {
2082
+ snackBar.open(options.snackBarConfig.failureMessage, '', options.snackBarConfig.config);
2083
+ }
2084
+ throw e;
2085
+ }
2086
+ // update in backend and then locally if successful
2087
+ }
2088
+ else {
2089
+ // start loading icon
2090
+ options?.loading?.set(true);
2091
+ try {
2092
+ await db.removeEntity(collectionName, id, options?.batchConfig?.batch);
2093
+ // only patch if not using batch writes since if we're using
2094
+ // batch writes, we should be patching after the batch write
2095
+ // is successful
2096
+ if (!options?.batchConfig?.batch) {
2097
+ patchFn();
2098
+ if (options?.snackBarConfig) {
2099
+ openSnackBarWithUndoOption(snackBar, options.snackBarConfig, [revertFn], [dbRevertFn]);
2100
+ }
2101
+ }
2102
+ }
2103
+ catch (e) {
2104
+ logger.error(e);
2105
+ // will only get here when it's not a batch
2106
+ if (options?.snackBarConfig) {
2107
+ snackBar.open(options.snackBarConfig.failureMessage, '', options.snackBarConfig.config);
2108
+ }
2109
+ throw e;
2110
+ }
2111
+ finally {
2112
+ // stop loading icon
2113
+ options?.loading?.set(false);
2114
+ }
2115
+ }
2116
+ },
2117
+ })));
2118
+ }
2119
+
2120
+ const BATCH_WRITE_SERVICE = new InjectionToken('PlatformBatchWriteService');
2121
+ /**
2122
+ * Shared coordinator for real and mock batches. The callback queues backend
2123
+ * writes and records local patches/compensations; this function commits once.
2124
+ * Keep the original optimistic/non-optimistic branches visible: one patches
2125
+ * during preparation, the other patches after commit. Preparation is inside
2126
+ * the try block so a preparation failure also rolls back optimistic changes.
2127
+ */
2128
+ async function processBatchWrite(batchFn, options, batch, revertBatch, feedback) {
2129
+ const config = {
2130
+ batch, revertBatch, patchFns: [], revertFns: [], dbRevertFns: [], optimistic: options?.optimistic,
2131
+ };
2132
+ options?.loading?.set(true);
2133
+ if (options?.optimistic) {
2134
+ // This includes optimistically patching locally when batchFn uses add, update,
2135
+ // or remove from the NgRx entity stores with this batchConfig. Those methods
2136
+ // also record revertFns so a failed preparation or commit can restore state.
2137
+ let committed = false;
2138
+ try {
2139
+ await batchFn(config);
2140
+ await batch.commit();
2141
+ committed = true;
2142
+ if (options?.snackBarConfig) {
2143
+ openSnackBarWithUndoOption(feedback, options.snackBarConfig, config.revertFns, config.dbRevertFns, revertBatch);
2144
+ }
2145
+ }
2146
+ catch (error) {
2147
+ // A notification failure after commit must not undo an already-saved write.
2148
+ if (!committed)
2149
+ [...config.revertFns].reverse().forEach(revert => revert());
2150
+ if (options?.snackBarConfig)
2151
+ feedback.open(options.snackBarConfig.failureMessage, '', options.snackBarConfig.config);
2152
+ throw error;
2153
+ }
2154
+ finally {
2155
+ options?.loading?.set(false);
2156
+ }
2157
+ }
2158
+ else {
2159
+ // Store methods queue local patches; apply them only after the backend succeeds.
2160
+ try {
2161
+ await batchFn(config);
2162
+ await batch.commit();
2163
+ config.patchFns.forEach(patch => patch());
2164
+ if (options?.snackBarConfig) {
2165
+ openSnackBarWithUndoOption(feedback, options.snackBarConfig, config.revertFns, config.dbRevertFns, revertBatch);
2166
+ }
2167
+ }
2168
+ catch (error) {
2169
+ if (options?.snackBarConfig)
2170
+ feedback.open(options.snackBarConfig.failureMessage, '', options.snackBarConfig.config);
2171
+ throw error;
2172
+ }
2173
+ finally {
2174
+ options?.loading?.set(false);
2175
+ }
2176
+ }
2177
+ }
2178
+
2179
+ /**
2180
+ * Core entry point: shared values, entity stores and adapter contracts.
2181
+ * Keep Firebase, mock fixtures and Material dependencies in their secondary
2182
+ * entry points so importing core does not require those integrations.
2183
+ */
2184
+
2185
+ /**
2186
+ * Generated bundle index. Do not edit.
2187
+ */
2188
+
2189
+ export { BATCH_WRITE_SERVICE, CachedListenersService, DATABASE_SERVICE, DATA_ACCESS, DATA_FEEDBACK, EntityLoadQuery, EntityStreamQuery, NOOP_DATA_FEEDBACK, StreamMultiplexer, compareDataTimestamps, dataTimestamp, dataTimestampEquals, dataTimestampFromDate, dataTimestampFromMillis, dataTimestampNow, dataTimestampToDate, dataTimestampToMillis, defineEntity, entityInQueryResults, fieldValue, isDataTimestamp, openSnackBarWithUndoOption, processBatchWrite, processLoadQueries, providePlatformData, queryEntities, queryOrderings, selectEntities, stableQueryKey, withEntitiesAndDBMethods, withEntitiesAndSelectMethods };
2190
+ //# sourceMappingURL=tech4good-platform-data.mjs.map