@statezero/core 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/dist/adaptors/react/composables.d.ts +1 -0
  2. package/dist/adaptors/react/composables.js +4 -0
  3. package/dist/adaptors/react/index.d.ts +1 -0
  4. package/dist/adaptors/react/index.js +1 -0
  5. package/dist/adaptors/vue/composables.d.ts +2 -0
  6. package/dist/adaptors/vue/composables.js +36 -0
  7. package/dist/adaptors/vue/index.d.ts +2 -0
  8. package/dist/adaptors/vue/index.js +2 -0
  9. package/dist/adaptors/vue/reactivity.d.ts +18 -0
  10. package/dist/adaptors/vue/reactivity.js +125 -0
  11. package/dist/cli/commands/syncModels.d.ts +132 -0
  12. package/dist/cli/commands/syncModels.js +1040 -0
  13. package/dist/cli/configFileLoader.d.ts +10 -0
  14. package/dist/cli/configFileLoader.js +85 -0
  15. package/dist/cli/index.d.ts +2 -0
  16. package/dist/cli/index.js +14 -0
  17. package/dist/config.d.ts +52 -0
  18. package/dist/config.js +242 -0
  19. package/dist/core/eventReceivers.d.ts +179 -0
  20. package/dist/core/eventReceivers.js +210 -0
  21. package/dist/core/utils.d.ts +8 -0
  22. package/dist/core/utils.js +62 -0
  23. package/dist/filtering/localFiltering.d.ts +116 -0
  24. package/dist/filtering/localFiltering.js +834 -0
  25. package/dist/flavours/django/dates.d.ts +33 -0
  26. package/dist/flavours/django/dates.js +99 -0
  27. package/dist/flavours/django/errors.d.ts +138 -0
  28. package/dist/flavours/django/errors.js +187 -0
  29. package/dist/flavours/django/f.d.ts +6 -0
  30. package/dist/flavours/django/f.js +91 -0
  31. package/dist/flavours/django/files.d.ts +76 -0
  32. package/dist/flavours/django/files.js +338 -0
  33. package/dist/flavours/django/makeApiCall.d.ts +20 -0
  34. package/dist/flavours/django/makeApiCall.js +169 -0
  35. package/dist/flavours/django/manager.d.ts +197 -0
  36. package/dist/flavours/django/manager.js +222 -0
  37. package/dist/flavours/django/model.d.ts +112 -0
  38. package/dist/flavours/django/model.js +253 -0
  39. package/dist/flavours/django/operationFactory.d.ts +65 -0
  40. package/dist/flavours/django/operationFactory.js +216 -0
  41. package/dist/flavours/django/q.d.ts +70 -0
  42. package/dist/flavours/django/q.js +43 -0
  43. package/dist/flavours/django/queryExecutor.d.ts +131 -0
  44. package/dist/flavours/django/queryExecutor.js +468 -0
  45. package/dist/flavours/django/querySet.d.ts +412 -0
  46. package/dist/flavours/django/querySet.js +601 -0
  47. package/dist/flavours/django/tempPk.d.ts +19 -0
  48. package/dist/flavours/django/tempPk.js +48 -0
  49. package/dist/flavours/django/utils.d.ts +19 -0
  50. package/dist/flavours/django/utils.js +29 -0
  51. package/dist/index.d.ts +38 -0
  52. package/dist/index.js +38 -0
  53. package/dist/react-entry.d.ts +2 -0
  54. package/dist/react-entry.js +2 -0
  55. package/dist/reactiveAdaptor.d.ts +24 -0
  56. package/dist/reactiveAdaptor.js +38 -0
  57. package/dist/setup.d.ts +15 -0
  58. package/dist/setup.js +22 -0
  59. package/dist/syncEngine/cache/cache.d.ts +75 -0
  60. package/dist/syncEngine/cache/cache.js +341 -0
  61. package/dist/syncEngine/metrics/metricOptCalcs.d.ts +79 -0
  62. package/dist/syncEngine/metrics/metricOptCalcs.js +284 -0
  63. package/dist/syncEngine/registries/metricRegistry.d.ts +53 -0
  64. package/dist/syncEngine/registries/metricRegistry.js +162 -0
  65. package/dist/syncEngine/registries/modelStoreRegistry.d.ts +11 -0
  66. package/dist/syncEngine/registries/modelStoreRegistry.js +56 -0
  67. package/dist/syncEngine/registries/querysetStoreRegistry.d.ts +55 -0
  68. package/dist/syncEngine/registries/querysetStoreRegistry.js +244 -0
  69. package/dist/syncEngine/stores/metricStore.d.ts +55 -0
  70. package/dist/syncEngine/stores/metricStore.js +222 -0
  71. package/dist/syncEngine/stores/modelStore.d.ts +40 -0
  72. package/dist/syncEngine/stores/modelStore.js +405 -0
  73. package/dist/syncEngine/stores/operation.d.ts +99 -0
  74. package/dist/syncEngine/stores/operation.js +224 -0
  75. package/dist/syncEngine/stores/operationEventHandlers.d.ts +8 -0
  76. package/dist/syncEngine/stores/operationEventHandlers.js +239 -0
  77. package/dist/syncEngine/stores/querysetStore.d.ts +32 -0
  78. package/dist/syncEngine/stores/querysetStore.js +200 -0
  79. package/dist/syncEngine/stores/reactivity.d.ts +3 -0
  80. package/dist/syncEngine/stores/reactivity.js +4 -0
  81. package/dist/syncEngine/stores/utils.d.ts +14 -0
  82. package/dist/syncEngine/stores/utils.js +32 -0
  83. package/dist/syncEngine/sync.d.ts +32 -0
  84. package/dist/syncEngine/sync.js +169 -0
  85. package/dist/vue-entry.d.ts +6 -0
  86. package/dist/vue-entry.js +2 -0
  87. package/license.md +116 -0
  88. package/package.json +123 -0
  89. package/readme.md +222 -0
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Base class for metric calculation strategies with operations
3
+ */
4
+ export class MetricCalculationStrategy {
5
+ /**
6
+ * Calculate metric based on ground truth and operations
7
+ */
8
+ calculateWithOperations(baseValue: any, operations: any, field: any, ModelClass: any): any;
9
+ /**
10
+ * Get initial value for the metric type
11
+ * Override in subclasses if needed
12
+ */
13
+ getInitialValue(): number;
14
+ /**
15
+ * Process a single operation - implement in subclasses
16
+ */
17
+ reduceOperation(currentValue: any, operation: any, field: any): void;
18
+ /**
19
+ * Safely get a numeric value from an object
20
+ */
21
+ safeGetValue(obj: any, field: any): number;
22
+ }
23
+ /**
24
+ * Count strategy implementation
25
+ */
26
+ export class CountStrategy extends MetricCalculationStrategy {
27
+ reduceOperation(currentCount: any, operation: any, field: any): any;
28
+ }
29
+ /**
30
+ * Sum strategy implementation
31
+ */
32
+ export class SumStrategy extends MetricCalculationStrategy {
33
+ reduceOperation(currentSum: any, operation: any, field: any): any;
34
+ }
35
+ /**
36
+ * Min strategy implementation
37
+ */
38
+ export class MinStrategy extends MetricCalculationStrategy {
39
+ reduceOperation(currentMin: any, operation: any, field: any): any;
40
+ }
41
+ /**
42
+ * Max strategy implementation
43
+ */
44
+ export class MaxStrategy extends MetricCalculationStrategy {
45
+ reduceOperation(currentMax: any, operation: any, field: any): any;
46
+ }
47
+ /**
48
+ * Factory class for creating the appropriate strategy
49
+ */
50
+ export class MetricStrategyFactory {
51
+ static "__#7@#customStrategies": Map<any, any>;
52
+ static "__#7@#defaultStrategies": Map<string, () => CountStrategy>;
53
+ /**
54
+ * Clear all custom strategy overrides
55
+ */
56
+ static clearCustomStrategies(): void;
57
+ /**
58
+ * Generate a unique key for the strategy map
59
+ * @private
60
+ * @param {string} metricType - The type of metric (count, sum, min, max)
61
+ * @param {Function} ModelClass - The model class
62
+ * @returns {string} A unique key
63
+ */
64
+ private static "__#7@#generateStrategyKey";
65
+ /**
66
+ * Override a strategy for a specific metric type and model class
67
+ * @param {string} metricType - The type of metric (count, sum, min, max)
68
+ * @param {Function|null} ModelClass - The model class or null for a generic override
69
+ * @param {MetricCalculationStrategy} strategy - The strategy to use
70
+ */
71
+ static overrideStrategy(metricType: string, ModelClass: Function | null, strategy: MetricCalculationStrategy): void;
72
+ /**
73
+ * Get the appropriate strategy for a model class and metric type
74
+ * @param {string} metricType - The type of metric (count, sum, min, max)
75
+ * @param {Function} ModelClass - The model class
76
+ * @returns {MetricCalculationStrategy} The appropriate strategy
77
+ */
78
+ static getStrategy(metricType: string, ModelClass: Function): MetricCalculationStrategy;
79
+ }
@@ -0,0 +1,284 @@
1
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
2
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
3
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
4
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
5
+ };
6
+ var _a, _MetricStrategyFactory_customStrategies, _MetricStrategyFactory_defaultStrategies, _MetricStrategyFactory_generateStrategyKey;
7
+ import { Status, Type } from '../stores/operation';
8
+ import { isNil } from 'lodash-es';
9
+ /**
10
+ * Base class for metric calculation strategies with operations
11
+ */
12
+ export class MetricCalculationStrategy {
13
+ /**
14
+ * Calculate metric based on ground truth and operations
15
+ */
16
+ calculateWithOperations(baseValue, operations, field, ModelClass) {
17
+ // Initialize the current value based on the metric type
18
+ let currentValue = baseValue === null ? this.getInitialValue() : baseValue;
19
+ // Process operations sequentially
20
+ for (const op of operations) {
21
+ // Skip rejected operations
22
+ if (op.status === Status.REJECTED)
23
+ continue;
24
+ // Process each instance in the operation
25
+ op.frozenInstances.forEach((originalData, index) => {
26
+ let pk = originalData[ModelClass.primaryKeyField];
27
+ // Get the updated data for this instance (for UPDATE operations)
28
+ const updatedData = op.instances[index] || null;
29
+ // Create operation data object for the reducer
30
+ const singleOp = {
31
+ originalData, // Pre-operation state
32
+ updatedData, // Post-operation state (for updates)
33
+ type: op.type,
34
+ status: op.status
35
+ };
36
+ // Apply this single operation using the strategy-specific reducer
37
+ currentValue = this.reduceOperation(currentValue, singleOp, field);
38
+ });
39
+ }
40
+ return currentValue;
41
+ }
42
+ /**
43
+ * Get initial value for the metric type
44
+ * Override in subclasses if needed
45
+ */
46
+ getInitialValue() {
47
+ return 0; // Default for count and sum
48
+ }
49
+ /**
50
+ * Process a single operation - implement in subclasses
51
+ */
52
+ reduceOperation(currentValue, operation, field) {
53
+ throw new Error('reduceOperation must be implemented by subclass');
54
+ }
55
+ /**
56
+ * Safely get a numeric value from an object
57
+ */
58
+ safeGetValue(obj, field) {
59
+ if (!obj || !field)
60
+ return 0;
61
+ const value = obj[field];
62
+ if (isNil(value))
63
+ return 0;
64
+ const numValue = parseFloat(value);
65
+ return isNaN(numValue) ? 0 : numValue;
66
+ }
67
+ }
68
+ /**
69
+ * Count strategy implementation
70
+ */
71
+ export class CountStrategy extends MetricCalculationStrategy {
72
+ reduceOperation(currentCount, operation, field) {
73
+ // Skip rejected operations
74
+ if (operation.status === Status.REJECTED) {
75
+ return currentCount;
76
+ }
77
+ const { type } = operation;
78
+ // Handle operation types
79
+ if (type === Type.CREATE) {
80
+ return currentCount + 1;
81
+ }
82
+ else if ([Type.DELETE, Type.DELETE_INSTANCE].includes(type)) {
83
+ return Math.max(0, currentCount - 1);
84
+ }
85
+ // Other operation types don't affect the count
86
+ return currentCount;
87
+ }
88
+ }
89
+ /**
90
+ * Sum strategy implementation
91
+ */
92
+ export class SumStrategy extends MetricCalculationStrategy {
93
+ reduceOperation(currentSum, operation, field) {
94
+ // Skip rejected operations
95
+ if (operation.status === Status.REJECTED) {
96
+ return currentSum;
97
+ }
98
+ if (!field) {
99
+ throw new Error('SumStrategy requires a field parameter');
100
+ }
101
+ const { type, originalData, updatedData } = operation;
102
+ switch (type) {
103
+ case Type.CREATE:
104
+ // For CREATE, add the value to the sum
105
+ return currentSum + this.safeGetValue(originalData, field);
106
+ case Type.CHECKPOINT:
107
+ case Type.UPDATE:
108
+ // For UPDATE, subtract old value and add new value
109
+ if (updatedData) {
110
+ const oldValue = this.safeGetValue(originalData, field);
111
+ const newValue = this.safeGetValue(updatedData, field);
112
+ return currentSum - oldValue + newValue;
113
+ }
114
+ return currentSum;
115
+ case Type.DELETE:
116
+ case Type.DELETE_INSTANCE:
117
+ // For DELETE, subtract the value from the sum
118
+ return currentSum - this.safeGetValue(originalData, field);
119
+ default:
120
+ return currentSum;
121
+ }
122
+ }
123
+ }
124
+ /**
125
+ * Min strategy implementation
126
+ */
127
+ export class MinStrategy extends MetricCalculationStrategy {
128
+ getInitialValue() {
129
+ return Infinity;
130
+ }
131
+ reduceOperation(currentMin, operation, field) {
132
+ // Skip rejected operations
133
+ if (operation.status === Status.REJECTED) {
134
+ return currentMin;
135
+ }
136
+ if (!field) {
137
+ throw new Error('MinStrategy requires a field parameter');
138
+ }
139
+ const { type, originalData, updatedData } = operation;
140
+ if (type === Type.CREATE) {
141
+ // For CREATE, check if the new value is smaller than current min
142
+ const value = this.safeGetValue(originalData, field);
143
+ return Math.min(currentMin, value);
144
+ }
145
+ else if ((type === Type.UPDATE || type.CHECKPOINT) && updatedData) {
146
+ // For UPDATE, first check if we're updating the minimum value
147
+ const oldValue = this.safeGetValue(originalData, field);
148
+ const newValue = this.safeGetValue(updatedData, field);
149
+ if (oldValue === currentMin) {
150
+ // We're updating the current minimum, need to find the new minimum
151
+ if (newValue <= oldValue) {
152
+ // Simple case: new value is still the minimum
153
+ return newValue;
154
+ }
155
+ else {
156
+ // Harder case: need to recalculate minimum
157
+ // For now, conservatively use the new value
158
+ return newValue;
159
+ }
160
+ }
161
+ else if (newValue < currentMin) {
162
+ // The updated value is a new minimum
163
+ return newValue;
164
+ }
165
+ }
166
+ // For other cases, maintain current min
167
+ return currentMin;
168
+ }
169
+ }
170
+ /**
171
+ * Max strategy implementation
172
+ */
173
+ export class MaxStrategy extends MetricCalculationStrategy {
174
+ getInitialValue() {
175
+ return -Infinity;
176
+ }
177
+ reduceOperation(currentMax, operation, field) {
178
+ // Skip rejected operations
179
+ if (operation.status === Status.REJECTED) {
180
+ return currentMax;
181
+ }
182
+ if (!field) {
183
+ throw new Error('MaxStrategy requires a field parameter');
184
+ }
185
+ const { type, originalData, updatedData } = operation;
186
+ if (type === Type.CREATE) {
187
+ // For CREATE, check if the new value is larger than current max
188
+ const value = this.safeGetValue(originalData, field);
189
+ return Math.max(currentMax, value);
190
+ }
191
+ else if ((type === Type.UPDATE || type === Type.CHECKPOINT) && updatedData) {
192
+ // For UPDATE, first check if we're updating the maximum value
193
+ const oldValue = this.safeGetValue(originalData, field);
194
+ const newValue = this.safeGetValue(updatedData, field);
195
+ if (oldValue === currentMax) {
196
+ // We're updating the current maximum, need to find the new maximum
197
+ if (newValue >= oldValue) {
198
+ // Simple case: new value is still the maximum
199
+ return newValue;
200
+ }
201
+ else {
202
+ // Harder case: need to recalculate maximum
203
+ // For now, conservatively use the new value
204
+ return newValue;
205
+ }
206
+ }
207
+ else if (newValue > currentMax) {
208
+ // The updated value is a new maximum
209
+ return newValue;
210
+ }
211
+ }
212
+ // For other cases, maintain current max
213
+ return currentMax;
214
+ }
215
+ }
216
+ /**
217
+ * Factory class for creating the appropriate strategy
218
+ */
219
+ export class MetricStrategyFactory {
220
+ /**
221
+ * Clear all custom strategy overrides
222
+ */
223
+ static clearCustomStrategies() {
224
+ __classPrivateFieldGet(this, _a, "f", _MetricStrategyFactory_customStrategies).clear();
225
+ }
226
+ /**
227
+ * Override a strategy for a specific metric type and model class
228
+ * @param {string} metricType - The type of metric (count, sum, min, max)
229
+ * @param {Function|null} ModelClass - The model class or null for a generic override
230
+ * @param {MetricCalculationStrategy} strategy - The strategy to use
231
+ */
232
+ static overrideStrategy(metricType, ModelClass, strategy) {
233
+ if (!metricType || !strategy) {
234
+ throw new Error('overrideStrategy requires metricType and strategy');
235
+ }
236
+ if (!(strategy instanceof MetricCalculationStrategy)) {
237
+ throw new Error('strategy must be an instance of MetricCalculationStrategy');
238
+ }
239
+ let key;
240
+ if (ModelClass) {
241
+ // Model-specific override
242
+ key = __classPrivateFieldGet(this, _a, "m", _MetricStrategyFactory_generateStrategyKey).call(this, metricType, ModelClass);
243
+ }
244
+ else {
245
+ // Generic override for all models
246
+ key = `${metricType}::*::*`;
247
+ }
248
+ __classPrivateFieldGet(this, _a, "f", _MetricStrategyFactory_customStrategies).set(key, strategy);
249
+ }
250
+ /**
251
+ * Get the appropriate strategy for a model class and metric type
252
+ * @param {string} metricType - The type of metric (count, sum, min, max)
253
+ * @param {Function} ModelClass - The model class
254
+ * @returns {MetricCalculationStrategy} The appropriate strategy
255
+ */
256
+ static getStrategy(metricType, ModelClass) {
257
+ const normalizedMetricType = metricType.toLowerCase();
258
+ // Check for model-specific override first
259
+ const specificKey = __classPrivateFieldGet(this, _a, "m", _MetricStrategyFactory_generateStrategyKey).call(this, normalizedMetricType, ModelClass);
260
+ if (__classPrivateFieldGet(this, _a, "f", _MetricStrategyFactory_customStrategies).has(specificKey)) {
261
+ return __classPrivateFieldGet(this, _a, "f", _MetricStrategyFactory_customStrategies).get(specificKey);
262
+ }
263
+ // Check for metric-only override (works across all models)
264
+ const genericKey = `${normalizedMetricType}::*::*`;
265
+ if (__classPrivateFieldGet(this, _a, "f", _MetricStrategyFactory_customStrategies).has(genericKey)) {
266
+ return __classPrivateFieldGet(this, _a, "f", _MetricStrategyFactory_customStrategies).get(genericKey);
267
+ }
268
+ // Otherwise, return the default strategy based on the metric type
269
+ const strategyCreator = __classPrivateFieldGet(this, _a, "f", _MetricStrategyFactory_defaultStrategies).get(normalizedMetricType) || __classPrivateFieldGet(this, _a, "f", _MetricStrategyFactory_defaultStrategies).get('count');
270
+ return strategyCreator();
271
+ }
272
+ }
273
+ _a = MetricStrategyFactory, _MetricStrategyFactory_generateStrategyKey = function _MetricStrategyFactory_generateStrategyKey(metricType, ModelClass) {
274
+ return `${metricType}::${ModelClass.configKey}::${ModelClass.modelName}`;
275
+ };
276
+ // Collection of custom strategy overrides
277
+ _MetricStrategyFactory_customStrategies = { value: new Map() };
278
+ // Default strategy map
279
+ _MetricStrategyFactory_defaultStrategies = { value: new Map([
280
+ ['count', () => new CountStrategy()],
281
+ ['sum', () => new SumStrategy()],
282
+ ['min', () => new MinStrategy()],
283
+ ['max', () => new MaxStrategy()]
284
+ ]) };
@@ -0,0 +1,53 @@
1
+ /**
2
+ * LiveMetric, a simple wrapper that always returns the latest metric value
3
+ * using a getter for the value property
4
+ */
5
+ export class LiveMetric {
6
+ constructor(queryset: any, metricType: any, field?: null);
7
+ queryset: any;
8
+ metricType: any;
9
+ field: any;
10
+ get lqs(): import("./querysetStoreRegistry").LiveQueryset;
11
+ /**
12
+ * Getter that always returns the current value from the store
13
+ */
14
+ get value(): any;
15
+ }
16
+ /**
17
+ * Registry to manage metric stores
18
+ */
19
+ export class MetricRegistry {
20
+ _stores: Map<any, any>;
21
+ syncManager: any;
22
+ clear(): void;
23
+ setSyncManager(syncManager: any): void;
24
+ /**
25
+ * Get all metric stores that match a specific queryset
26
+ * @param {Queryset} queryset - The queryset to match
27
+ * @returns {Array} Array of metric stores
28
+ */
29
+ getAllStoresForQueryset(queryset: Queryset): any[];
30
+ _makeKey(metricType: any, queryset: any, field?: null): string;
31
+ /**
32
+ * Get a metric store for a specific queryset and metric type
33
+ */
34
+ getStore(metricType: any, queryset: any, field?: null): any;
35
+ /**
36
+ * Get a metric value for a specific queryset
37
+ */
38
+ getEntity(metricType: any, queryset: any, field?: null): Object | null;
39
+ /**
40
+ * Set metric ground truth value
41
+ */
42
+ setEntity(metricType: any, queryset: any, field: any, value: any): any;
43
+ /**
44
+ * Sync a specific metric with the server
45
+ */
46
+ syncMetric(metricType: any, queryset: any, field?: null): any;
47
+ /**
48
+ * Get the queryset for a specific key
49
+ * Useful for debugging or auditing
50
+ */
51
+ getQuerysetForKey(key: any): any;
52
+ }
53
+ export const metricRegistry: MetricRegistry;
@@ -0,0 +1,162 @@
1
+ import { MetricStore } from '../stores/metricStore';
2
+ import { isNil, isEmpty } from 'lodash-es';
3
+ import { querysetStoreRegistry } from './querysetStoreRegistry';
4
+ import { QueryExecutor } from '../../flavours/django/queryExecutor';
5
+ import { wrapReactiveMetric } from '../../reactiveAdaptor.js';
6
+ import hash from 'object-hash';
7
+ /**
8
+ * LiveMetric, a simple wrapper that always returns the latest metric value
9
+ * using a getter for the value property
10
+ */
11
+ export class LiveMetric {
12
+ constructor(queryset, metricType, field = null) {
13
+ this.queryset = queryset;
14
+ this.metricType = metricType;
15
+ this.field = field;
16
+ }
17
+ get lqs() {
18
+ return querysetStoreRegistry.getEntity(this.queryset);
19
+ }
20
+ /**
21
+ * Getter that always returns the current value from the store
22
+ */
23
+ get value() {
24
+ // Get the latest store from the registry
25
+ const store = metricRegistry.getStore(this.metricType, this.queryset, this.field);
26
+ if (!store) {
27
+ return null;
28
+ }
29
+ // Render the current value
30
+ return store.render();
31
+ }
32
+ }
33
+ /**
34
+ * Registry to manage metric stores
35
+ */
36
+ export class MetricRegistry {
37
+ constructor() {
38
+ // Store both the store and a reference to the queryset as a tuple
39
+ this._stores = new Map();
40
+ this.syncManager = null;
41
+ }
42
+ clear() {
43
+ for (const entry of this._stores.values()) {
44
+ this.syncManager.unfollowModel(this, entry.store.modelClass);
45
+ }
46
+ this._stores = new Map();
47
+ }
48
+ setSyncManager(syncManager) {
49
+ this.syncManager = syncManager;
50
+ }
51
+ /**
52
+ * Get all metric stores that match a specific queryset
53
+ * @param {Queryset} queryset - The queryset to match
54
+ * @returns {Array} Array of metric stores
55
+ */
56
+ getAllStoresForQueryset(queryset) {
57
+ if (isNil(queryset) || isNil(queryset.ModelClass)) {
58
+ return [];
59
+ }
60
+ const stores = [];
61
+ const modelClass = queryset.ModelClass;
62
+ const operationAst = queryset.build();
63
+ for (const [key, entry] of this._stores.entries()) {
64
+ const store = entry.store;
65
+ // First check if model class matches
66
+ if (store.modelClass !== modelClass) {
67
+ continue;
68
+ }
69
+ // #TODO match queryset based on ast
70
+ stores.push(store);
71
+ }
72
+ return stores;
73
+ }
74
+ _makeKey(metricType, queryset, field = null) {
75
+ const modelClass = queryset.ModelClass;
76
+ const ast = queryset.build();
77
+ return `${metricType}::${modelClass.configKey}::${modelClass.modelName}::${field || 'null'}::${hash(ast)}`;
78
+ }
79
+ /**
80
+ * Get a metric store for a specific queryset and metric type
81
+ */
82
+ getStore(metricType, queryset, field = null) {
83
+ if (isNil(metricType) || isNil(queryset) || isNil(queryset.ModelClass)) {
84
+ return null;
85
+ }
86
+ const modelClass = queryset.ModelClass;
87
+ const ast = queryset.build();
88
+ const key = this._makeKey(metricType, queryset, field);
89
+ if (!this._stores.has(key)) {
90
+ // Create fetch function for this metric
91
+ const fetchMetricFn = async ({ metricType, modelClass, field, ast }) => {
92
+ const qs = queryset.clone();
93
+ return await QueryExecutor.executeAgg(qs, metricType, { field });
94
+ };
95
+ // Create new store
96
+ const store = new MetricStore(metricType, modelClass, queryset, field, ast, fetchMetricFn);
97
+ // Store both the store and a reference to the queryset
98
+ this._stores.set(key, {
99
+ store,
100
+ queryset // This keeps the queryset alive
101
+ });
102
+ this.syncManager.followModel(this, store.modelClass);
103
+ }
104
+ return this._stores.get(key).store;
105
+ }
106
+ /**
107
+ * Get a metric value for a specific queryset
108
+ */
109
+ getEntity(metricType, queryset, field = null) {
110
+ // defensive checks
111
+ if (isNil(metricType) || isNil(queryset) || isNil(queryset.ModelClass)) {
112
+ return null;
113
+ }
114
+ // Get the store (creates if doesn't exist)
115
+ const store = this.getStore(metricType, queryset, field);
116
+ // Create a LiveMetric that will always get the latest store and value
117
+ const liveMetric = new LiveMetric(queryset, metricType, field);
118
+ // If we're in a reactive environment, wrap the metric
119
+ return wrapReactiveMetric(liveMetric);
120
+ }
121
+ /**
122
+ * Set metric ground truth value
123
+ */
124
+ setEntity(metricType, queryset, field, value) {
125
+ // defensive checks
126
+ if (isNil(metricType) || isNil(queryset) || isNil(queryset.ModelClass)) {
127
+ return null;
128
+ }
129
+ const store = this.getStore(metricType, queryset, field);
130
+ if (!store) {
131
+ return null;
132
+ }
133
+ // check if the store already has a ground truth or operations
134
+ if (!isNil(store.groundTruthValue) || !isEmpty(store.operations)) {
135
+ store.reset();
136
+ }
137
+ store.setGroundTruth(value);
138
+ return value;
139
+ }
140
+ /**
141
+ * Sync a specific metric with the server
142
+ */
143
+ syncMetric(metricType, queryset, field = null) {
144
+ const store = this.getStore(metricType, queryset, field);
145
+ if (store) {
146
+ return store.sync();
147
+ }
148
+ return null;
149
+ }
150
+ /**
151
+ * Get the queryset for a specific key
152
+ * Useful for debugging or auditing
153
+ */
154
+ getQuerysetForKey(key) {
155
+ if (this._stores.has(key)) {
156
+ return this._stores.get(key).queryset;
157
+ }
158
+ return null;
159
+ }
160
+ }
161
+ // Export singleton instance
162
+ export const metricRegistry = new MetricRegistry();
@@ -0,0 +1,11 @@
1
+ export const modelStoreRegistry: ModelStoreRegistry;
2
+ declare class ModelStoreRegistry {
3
+ _stores: Map<any, any>;
4
+ syncManager: () => void;
5
+ clear(): void;
6
+ setSyncManager(syncManager: any): void;
7
+ getStore(modelClass: any): any;
8
+ getEntity(modelClass: any, pk: any): any;
9
+ setEntity(modelClass: any, pk: any, data: any): any;
10
+ }
11
+ export {};
@@ -0,0 +1,56 @@
1
+ import { ModelStore } from '../stores/modelStore.js';
2
+ import { isNil } from 'lodash-es';
3
+ class ModelStoreRegistry {
4
+ constructor() {
5
+ this._stores = new Map();
6
+ this.syncManager = () => { console.warn("SyncManager not set for ModelStoreRegistry"); };
7
+ }
8
+ clear() {
9
+ for (const modelClass of this._stores.keys()) {
10
+ this.syncManager.unfollowModel(this, modelClass);
11
+ }
12
+ this._stores = new Map();
13
+ }
14
+ setSyncManager(syncManager) {
15
+ this.syncManager = syncManager;
16
+ }
17
+ getStore(modelClass) {
18
+ if (!this._stores.has(modelClass)) {
19
+ // Create a new ModelStore on demand
20
+ const fetchModels = async ({ pks, modelClass }) => {
21
+ return await modelClass.objects.filter({
22
+ [`${modelClass.primaryKeyField}__in`]: pks
23
+ }).fetch();
24
+ };
25
+ this._stores.set(modelClass, new ModelStore(modelClass, fetchModels, null, null));
26
+ this.syncManager.followModel(this, modelClass);
27
+ }
28
+ return this._stores.get(modelClass);
29
+ }
30
+ // Get a single entity from the store
31
+ getEntity(modelClass, pk) {
32
+ // defensive checks for this nested func
33
+ if (isNil(modelClass) || isNil(pk))
34
+ return;
35
+ if (pk[modelClass.primaryKeyField])
36
+ throw new Error("getEntity should be called with a pk not an object");
37
+ // logic
38
+ const store = this.getStore(modelClass);
39
+ const renderedData = store.render([pk]);
40
+ return renderedData[0] || null;
41
+ }
42
+ // Add or update an entity ground truth in the store, not for operations!
43
+ setEntity(modelClass, pk, data) {
44
+ // defensive checks for this nested func
45
+ if (isNil(modelClass) || isNil(pk))
46
+ return;
47
+ if (pk[modelClass.primaryKeyField])
48
+ throw new Error("getEntity should be called with a pk not an object");
49
+ // logic
50
+ const store = this.getStore(modelClass);
51
+ store.addToGroundTruth([data]);
52
+ return data;
53
+ }
54
+ }
55
+ // Export singleton instance
56
+ export const modelStoreRegistry = new ModelStoreRegistry();