@kosdev-code/kos-ui-sdk 0.1.0-next.911 → 0.1.0-next.937

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 (55) hide show
  1. package/.kos.json +1 -1
  2. package/core/core/decorators/kos-logger-aware.d.ts.map +1 -1
  3. package/core/core/decorators/kos-multiple-future-aware.d.ts +10 -46
  4. package/core/core/decorators/kos-multiple-future-aware.d.ts.map +1 -1
  5. package/core/core/decorators/kos-reload-aware.d.ts +6 -4
  6. package/core/core/decorators/kos-reload-aware.d.ts.map +1 -1
  7. package/core/core/decorators/kos-service-request-helpers.d.ts +3 -1
  8. package/core/core/decorators/kos-service-request-helpers.d.ts.map +1 -1
  9. package/core/core/decorators/kos-service-request.d.ts +13 -35
  10. package/core/core/decorators/kos-service-request.d.ts.map +1 -1
  11. package/core/core/decorators/kos-state-machine.d.ts +21 -10
  12. package/core/core/decorators/kos-state-machine.d.ts.map +1 -1
  13. package/core/core/decorators/kos-topic-handler-flow-control.d.ts +28 -28
  14. package/core/core/decorators/kos-topic-handler-flow-control.d.ts.map +1 -1
  15. package/core/core/decorators/kos-view-model.d.ts.map +1 -1
  16. package/core/core/decorators/kosDependency.d.ts +4 -2
  17. package/core/core/decorators/kosDependency.d.ts.map +1 -1
  18. package/core/core/decorators/kosModel.d.ts.map +1 -1
  19. package/core/core/decorators/kosTopicHandler.d.ts +3 -12
  20. package/core/core/decorators/kosTopicHandler.d.ts.map +1 -1
  21. package/core/core/extension/extension-manager.d.ts.map +1 -1
  22. package/core/core/kosCore.d.ts +15 -0
  23. package/core/core/kosCore.d.ts.map +1 -1
  24. package/core/core/kosModel.d.ts +5 -0
  25. package/core/core/kosModel.d.ts.map +1 -1
  26. package/core/core/model/kos-model-component-factory.d.ts +1 -1
  27. package/core/core/model/kos-model-component-factory.d.ts.map +1 -1
  28. package/core/core/model/kos-service-request-manager.d.ts +7 -2
  29. package/core/core/model/kos-service-request-manager.d.ts.map +1 -1
  30. package/core/core/model/kos-subscription-manager.d.ts +2 -2
  31. package/core/core/model/kos-subscription-manager.d.ts.map +1 -1
  32. package/core/core/model/service-response-store.d.ts +2 -1
  33. package/core/core/model/service-response-store.d.ts.map +1 -1
  34. package/core/types/kos-dependency.d.ts +13 -4
  35. package/core/types/kos-dependency.d.ts.map +1 -1
  36. package/core/types/service-response-store.d.ts +0 -4
  37. package/core/types/service-response-store.d.ts.map +1 -1
  38. package/core/util/model-utils.d.ts.map +1 -1
  39. package/{index-YzHb2lnB.js → index-Csq0zQtb.js} +358 -647
  40. package/index-Csq0zQtb.js.map +1 -0
  41. package/{index-CRb8ucfF.cjs → index-D52vEGXT.cjs} +287 -576
  42. package/index-D52vEGXT.cjs.map +1 -0
  43. package/index.cjs +310 -36
  44. package/index.cjs.map +1 -1
  45. package/index.js +375 -101
  46. package/index.js.map +1 -1
  47. package/models/utils/services/kos/daily/service.d.ts +1 -1
  48. package/models/utils/services/kos/daily/service.d.ts.map +1 -1
  49. package/models/utils/services/vfs/daily/service.d.ts +1 -1
  50. package/models/utils/services/vfs/daily/service.d.ts.map +1 -1
  51. package/package.json +3 -3
  52. package/testing.cjs +1 -1
  53. package/testing.js +1 -1
  54. package/index-CRb8ucfF.cjs.map +0 -1
  55. package/index-YzHb2lnB.js.map +0 -1
@@ -94,17 +94,17 @@ function reset() {
94
94
  log$q.warn("Resetting event bus");
95
95
  Object.keys(subscriptions).forEach((key) => delete subscriptions[key]);
96
96
  }
97
- function once$1(eventType, callback) {
97
+ function once(eventType, callback) {
98
98
  const subscription = subscribe(eventType, (msg) => {
99
99
  subscription.unsubscribe();
100
100
  callback(msg);
101
101
  });
102
102
  return subscription.unsubscribe;
103
103
  }
104
- function waitFor$1(eventType, timeout) {
104
+ function waitFor(eventType, timeout) {
105
105
  return new Promise((resolve, reject) => {
106
106
  let timeoutId = null;
107
- const unsubscribe = once$1(eventType, (msg) => {
107
+ const unsubscribe = once(eventType, (msg) => {
108
108
  if (timeoutId) {
109
109
  clearTimeout(timeoutId);
110
110
  }
@@ -121,288 +121,15 @@ function waitFor$1(eventType, timeout) {
121
121
  const eventBus = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
122
122
  __proto__: null,
123
123
  hasEventSubscriptions,
124
- once: once$1,
124
+ once,
125
125
  publish,
126
126
  reset,
127
127
  subscribe,
128
- waitFor: waitFor$1
129
- }, Symbol.toStringTag, { value: "Module" }));
130
- function once(eventType, callback) {
131
- const subscription = subscribe(eventType, (msg) => {
132
- subscription.unsubscribe();
133
- callback(msg);
134
- });
135
- return subscription.unsubscribe;
136
- }
137
- function waitFor(eventType, timeout) {
138
- return new Promise((resolve, reject) => {
139
- let timeoutId = null;
140
- const unsubscribe = once(eventType, (msg) => {
141
- if (timeoutId) {
142
- clearTimeout(timeoutId);
143
- }
144
- resolve(msg);
145
- });
146
- if (timeout) {
147
- timeoutId = setTimeout(() => {
148
- unsubscribe();
149
- reject(new Error(`Timeout waiting for event: ${eventType}`));
150
- }, timeout);
151
- }
152
- });
153
- }
154
- function waitForAll(eventTypes, timeout) {
155
- const promises = eventTypes.map(
156
- (eventType) => waitFor(eventType, timeout)
157
- );
158
- return Promise.all(promises);
159
- }
160
- function race(eventTypes, timeout) {
161
- return new Promise((resolve, reject) => {
162
- const unsubscribers = [];
163
- let timeoutId = null;
164
- let resolved = false;
165
- const cleanup = () => {
166
- unsubscribers.forEach((unsub) => unsub());
167
- if (timeoutId) {
168
- clearTimeout(timeoutId);
169
- }
170
- };
171
- eventTypes.forEach((eventType) => {
172
- const unsubscribe = once(eventType, (msg) => {
173
- if (!resolved) {
174
- resolved = true;
175
- cleanup();
176
- resolve({ eventType, data: msg });
177
- }
178
- });
179
- unsubscribers.push(unsubscribe);
180
- });
181
- if (timeout) {
182
- timeoutId = setTimeout(() => {
183
- if (!resolved) {
184
- resolved = true;
185
- cleanup();
186
- reject(
187
- new Error(`Timeout waiting for any event: ${eventTypes.join(", ")}`)
188
- );
189
- }
190
- }, timeout);
191
- }
192
- });
193
- }
194
- function filter(eventType, predicate, callback) {
195
- const subscription = subscribe(eventType, (msg) => {
196
- if (msg && predicate(msg)) {
197
- callback(msg);
198
- }
199
- });
200
- return subscription.unsubscribe;
201
- }
202
- function map(eventType, transform, callback) {
203
- const subscription = subscribe(eventType, (msg) => {
204
- if (msg) {
205
- const transformed = transform(msg);
206
- callback(transformed);
207
- }
208
- });
209
- return subscription.unsubscribe;
210
- }
211
- function debounce(eventType, delay2, callback) {
212
- let timeoutId = null;
213
- const subscription = subscribe(eventType, (msg) => {
214
- if (timeoutId) {
215
- clearTimeout(timeoutId);
216
- }
217
- timeoutId = setTimeout(() => {
218
- callback(msg);
219
- }, delay2);
220
- });
221
- return () => {
222
- if (timeoutId) {
223
- clearTimeout(timeoutId);
224
- }
225
- subscription.unsubscribe();
226
- };
227
- }
228
- function throttle(eventType, interval, callback) {
229
- let lastEmit = 0;
230
- let pendingTimeout = null;
231
- const subscription = subscribe(eventType, (msg) => {
232
- const now = Date.now();
233
- const timeSinceLastEmit = now - lastEmit;
234
- if (timeSinceLastEmit >= interval) {
235
- lastEmit = now;
236
- callback(msg);
237
- } else if (!pendingTimeout) {
238
- pendingTimeout = setTimeout(() => {
239
- lastEmit = Date.now();
240
- callback(msg);
241
- pendingTimeout = null;
242
- }, interval - timeSinceLastEmit);
243
- }
244
- });
245
- return () => {
246
- if (pendingTimeout) {
247
- clearTimeout(pendingTimeout);
248
- }
249
- subscription.unsubscribe();
250
- };
251
- }
252
- function buffer(eventType, bufferTime, callback) {
253
- let buffer2 = [];
254
- let timeoutId = null;
255
- const flush = () => {
256
- if (buffer2.length > 0) {
257
- callback([...buffer2]);
258
- buffer2 = [];
259
- }
260
- };
261
- const subscription = subscribe(eventType, (msg) => {
262
- if (msg) {
263
- buffer2.push(msg);
264
- if (!timeoutId) {
265
- timeoutId = setTimeout(() => {
266
- flush();
267
- timeoutId = null;
268
- }, bufferTime);
269
- }
270
- }
271
- });
272
- return () => {
273
- if (timeoutId) {
274
- clearTimeout(timeoutId);
275
- flush();
276
- }
277
- subscription.unsubscribe();
278
- };
279
- }
280
- function replay(eventType, bufferSize = 1) {
281
- const buffer2 = [];
282
- subscribe(eventType, (msg) => {
283
- if (msg) {
284
- buffer2.push(msg);
285
- if (buffer2.length > bufferSize) {
286
- buffer2.shift();
287
- }
288
- }
289
- });
290
- return {
291
- subscribe: (callback) => {
292
- buffer2.forEach((event) => callback(event));
293
- return subscribe(eventType, callback);
294
- }
295
- };
296
- }
297
- function merge(eventTypes, callback) {
298
- const subscriptions2 = eventTypes.map(
299
- (eventType) => subscribe(eventType, (msg) => {
300
- if (msg) {
301
- callback(eventType, msg);
302
- }
303
- })
304
- );
305
- return () => {
306
- subscriptions2.forEach((sub) => sub.unsubscribe());
307
- };
308
- }
309
- function stateMachine(initialState, transitions) {
310
- let currentState = initialState;
311
- const subscriptions2 = [];
312
- const allEvents = /* @__PURE__ */ new Set();
313
- Object.values(transitions).forEach((stateTransitions) => {
314
- Object.keys(stateTransitions).forEach((event) => {
315
- allEvents.add(event);
316
- });
317
- });
318
- allEvents.forEach((eventType) => {
319
- const { unsubscribe } = subscribe(eventType, (msg) => {
320
- const stateTransitions = transitions[currentState];
321
- if (stateTransitions && stateTransitions[eventType]) {
322
- const nextState = stateTransitions[eventType](msg);
323
- currentState = nextState;
324
- }
325
- });
326
- subscriptions2.push(unsubscribe);
327
- });
328
- return {
329
- get state() {
330
- return currentState;
331
- },
332
- unsubscribe: () => {
333
- subscriptions2.forEach((unsub) => unsub());
334
- }
335
- };
336
- }
337
- function request(requestEvent, responseEvent, request2, timeout) {
338
- const responsePromise = waitFor(responseEvent, timeout);
339
- publish(requestEvent, request2);
340
- return responsePromise;
341
- }
342
- async function* eventIterator(eventType) {
343
- const queue = [];
344
- const waiters = [];
345
- const subscription = subscribe(eventType, (msg) => {
346
- if (msg) {
347
- if (waiters.length > 0) {
348
- const waiter = waiters.shift();
349
- waiter(msg);
350
- } else {
351
- queue.push(msg);
352
- }
353
- }
354
- });
355
- try {
356
- while (true) {
357
- if (queue.length > 0) {
358
- yield queue.shift();
359
- } else {
360
- yield await new Promise((resolve) => {
361
- waiters.push(resolve);
362
- });
363
- }
364
- }
365
- } finally {
366
- subscription.unsubscribe();
367
- }
368
- }
369
- const EventBusFunctional = {
370
- once,
371
- waitFor,
372
- waitForAll,
373
- race,
374
- filter,
375
- map,
376
- debounce,
377
- throttle,
378
- buffer,
379
- replay,
380
- merge,
381
- stateMachine,
382
- request,
383
- eventIterator
384
- };
385
- const eventBus_functional = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
386
- __proto__: null,
387
- EventBusFunctional,
388
- buffer,
389
- debounce,
390
- eventIterator,
391
- filter,
392
- map,
393
- merge,
394
- once,
395
- race,
396
- replay,
397
- request,
398
- stateMachine,
399
- throttle,
400
- waitFor,
401
- waitForAll
128
+ waitFor
402
129
  }, Symbol.toStringTag, { value: "Module" }));
403
130
  async function waitForOrGetState(eventType, options) {
404
131
  const { getCurrentState, transformState, shouldUseFetchedState, timeout } = options;
405
- const eventPromise = waitFor$1(eventType, timeout);
132
+ const eventPromise = waitFor(eventType, timeout);
406
133
  const currentState = await getCurrentState();
407
134
  const normalizedState = transformState ? transformState(currentState) : currentState;
408
135
  if (shouldUseFetchedState) {
@@ -521,7 +248,7 @@ async function waitForAllWithState(eventTypesOrType, options) {
521
248
  return normalizedState;
522
249
  }
523
250
  const eventPromises = eventTypes.map(
524
- (eventType) => waitFor$1(eventType, timeout)
251
+ (eventType) => waitFor(eventType, timeout)
525
252
  );
526
253
  const results = await Promise.all(eventPromises);
527
254
  return results[results.length - 1];
@@ -1256,7 +983,7 @@ function resolveServiceRequestParameters(metadata, modelInstance, args, runtimeO
1256
983
  modelId: modelInstance.id,
1257
984
  modelData: modelInstance,
1258
985
  value: {
1259
- ...typeof metadata.pathParams === "function" ? metadata.pathParams(modelInstance) : metadata.pathParams || {},
986
+ ...typeof metadata.pathParams === "function" ? metadata.pathParams(modelInstance, ...args) : metadata.pathParams || {},
1260
987
  ...runtimeOptions?.pathParams || {}
1261
988
  }
1262
989
  });
@@ -1264,11 +991,11 @@ function resolveServiceRequestParameters(metadata, modelInstance, args, runtimeO
1264
991
  modelId: modelInstance.id,
1265
992
  modelData: modelInstance,
1266
993
  value: {
1267
- ...typeof metadata.queryParams === "function" ? metadata.queryParams(modelInstance) : metadata.queryParams || {},
994
+ ...typeof metadata.queryParams === "function" ? metadata.queryParams(modelInstance, ...args) : metadata.queryParams || {},
1268
995
  ...runtimeOptions?.queryParams || {}
1269
996
  }
1270
997
  });
1271
- const finalBody = runtimeOptions?.body || (typeof metadata.body === "function" ? metadata.body(modelInstance) : metadata.body);
998
+ const finalBody = runtimeOptions?.body || (typeof metadata.body === "function" ? metadata.body(modelInstance, ...args) : metadata.body);
1272
999
  const decoratorRequestOptions = typeof metadata.requestOptions === "function" ? metadata.requestOptions(modelInstance, ...args) : metadata.requestOptions;
1273
1000
  const finalRequestOptions = {
1274
1001
  ...decoratorRequestOptions || {},
@@ -1436,6 +1163,7 @@ function kosStateMachine(config2, options) {
1436
1163
  // Default to READY if not specified
1437
1164
  initializeAt: config2.initializeAt || DependencyLifecycle.READY
1438
1165
  },
1166
+ initializeAtExplicit: config2.initializeAt !== void 0,
1439
1167
  options: {
1440
1168
  stateProperty: options?.stateProperty || "currentState",
1441
1169
  trackHistory: options?.trackHistory || false,
@@ -1470,7 +1198,8 @@ function kosStateGuard(options) {
1470
1198
  if (!isFsmInitialized) {
1471
1199
  return originalMethod.apply(this, args);
1472
1200
  }
1473
- const currentState = this.currentState;
1201
+ const stateProperty = this[StateMachineSetup]?.options?.stateProperty || "currentState";
1202
+ const currentState = this[stateProperty];
1474
1203
  const isAllowed = options.allowedStates.includes(currentState);
1475
1204
  if (!isAllowed) {
1476
1205
  const message = `Method ${String(
@@ -1734,10 +1463,9 @@ const registerExtensionPoint = (id, extensionPoint) => {
1734
1463
  };
1735
1464
  const _ExtensionManager = {
1736
1465
  indexExtension: {
1466
+ // Registrations under one id accumulate; a repeated index key takes the latest mapper.
1737
1467
  registerIndexExtension: (id, extension) => {
1738
- const extensions = indexExtensions.get(id) || {};
1739
- Object.assign(extensions, extension);
1740
- indexExtensions.set(id, extension);
1468
+ indexExtensions.set(id, { ...indexExtensions.get(id), ...extension });
1741
1469
  },
1742
1470
  loadIndexExtensions: (id) => indexExtensions.get(id) || {}
1743
1471
  },
@@ -1877,13 +1605,13 @@ class KosContainerIndex {
1877
1605
  refresh() {
1878
1606
  this.generateIndex();
1879
1607
  }
1880
- addItemToIndex(key, model, map2 = this._map, data = this.data) {
1881
- const currentValue = map2.get(key) || /* @__PURE__ */ new Set();
1608
+ addItemToIndex(key, model, map = this._map, data = this.data) {
1609
+ const currentValue = map.get(key) || /* @__PURE__ */ new Set();
1882
1610
  currentValue.add(model);
1883
- map2.set(key, currentValue);
1611
+ map.set(key, currentValue);
1884
1612
  data[key] = Array.from(currentValue);
1885
1613
  }
1886
- resolveIndex(map2, data) {
1614
+ resolveIndex(map, data) {
1887
1615
  const toRemove = this.data.keys.filter(
1888
1616
  (key) => !Object.keys(data).includes(key)
1889
1617
  );
@@ -1896,7 +1624,7 @@ class KosContainerIndex {
1896
1624
  const existing = this.data[key] || [];
1897
1625
  if (!arraysAreEqual(values, existing)) {
1898
1626
  this.data[key] = values;
1899
- const set = map2.get(key) || /* @__PURE__ */ new Set();
1627
+ const set = map.get(key) || /* @__PURE__ */ new Set();
1900
1628
  this._map.set(key, set);
1901
1629
  } else {
1902
1630
  KosLog.debug(`KosContainerIndex - Index ${key} is the same`);
@@ -2973,6 +2701,7 @@ class SingletonKosModelRegistrationFactory extends KosBaseModelRegistration {
2973
2701
  }
2974
2702
  }
2975
2703
  const log$j = KosLog.createLogger({ group: "decorators", name: "kos-model" });
2704
+ const FUTURE_CANCEL_END_STATE = "CANCEL";
2976
2705
  function resolveParentContext(TargetClass, modelId, modelData) {
2977
2706
  const parentIdRaw = TargetClass[ParentModel]?.parentId;
2978
2707
  if (!parentIdRaw) return;
@@ -2992,6 +2721,19 @@ function injectFutureServices(modelInstance) {
2992
2721
  modelInstance[key] = handler;
2993
2722
  });
2994
2723
  }
2724
+ function resolveDependencyAtConstruction(dependency, resolvedId, options) {
2725
+ const modelManager = KosCore.getInstance().modelManager;
2726
+ const resolutionPolicy = dependency.resolutionPolicy || DependencyResolutionPolicy.CREATE;
2727
+ if (resolutionPolicy === DependencyResolutionPolicy.CREATE) {
2728
+ return modelManager.createModelInstance(
2729
+ dependency.modelType,
2730
+ resolvedId,
2731
+ options
2732
+ ).data;
2733
+ }
2734
+ const existing = modelManager.getModelById(resolvedId);
2735
+ return existing?.modelTypeName === dependency.modelType ? existing.modelData : void 0;
2736
+ }
2995
2737
  function injectDependencies(modelInstance, modelId) {
2996
2738
  const dependencies = modelInstance[DependencyModels] || {};
2997
2739
  Object.entries(dependencies).forEach(([key, dependency]) => {
@@ -3013,12 +2755,11 @@ function injectDependencies(modelInstance, modelId) {
3013
2755
  );
3014
2756
  if (typeof resolvedId === "string") {
3015
2757
  if (!dependency.lazy) {
3016
- const model = KosCore.getInstance().modelManager.createModelInstance(
3017
- dependency.modelType,
2758
+ modelInstance[key] = resolveDependencyAtConstruction(
2759
+ dependency,
3018
2760
  resolvedId,
3019
2761
  options
3020
2762
  );
3021
- modelInstance[key] = model.data;
3022
2763
  }
3023
2764
  KosCore.getInstance().modelManager.addDependency(modelId, resolvedId);
3024
2765
  }
@@ -3062,7 +2803,7 @@ function injectFutureContainerSupport(modelInstance) {
3062
2803
  });
3063
2804
  Object.defineProperty(modelInstance, "isCancelled", {
3064
2805
  get() {
3065
- return futureHandler.future?.status === "CANCELLED" || false;
2806
+ return futureHandler.future?.status === FUTURE_CANCEL_END_STATE;
3066
2807
  },
3067
2808
  enumerable: true,
3068
2809
  configurable: true
@@ -3080,14 +2821,6 @@ function injectMultipleFutureContainerSupport(modelInstance) {
3080
2821
  const { mode, handlerProperty } = setup;
3081
2822
  const futureHandler = new MultipleFutureHandler(modelInstance);
3082
2823
  modelInstance[handlerProperty] = futureHandler;
3083
- Object.defineProperty(modelInstance, "future", {
3084
- get() {
3085
- return futureHandler.future;
3086
- },
3087
- enumerable: true,
3088
- configurable: true
3089
- // Allow MobX to make this observable
3090
- });
3091
2824
  const aliases = modelInstance[FutureAliases];
3092
2825
  if (aliases instanceof Map) {
3093
2826
  aliases.forEach((alias) => {
@@ -3127,7 +2860,7 @@ function injectMultipleFutureContainerSupport(modelInstance) {
3127
2860
  Object.defineProperty(modelInstance, `${alias}IsCancelled`, {
3128
2861
  get() {
3129
2862
  const future = futureHandler.futureMap.get(alias);
3130
- return future?.status === "CANCELLED" || false;
2863
+ return future?.status === FUTURE_CANCEL_END_STATE;
3131
2864
  },
3132
2865
  enumerable: true,
3133
2866
  configurable: true
@@ -3141,41 +2874,6 @@ function injectMultipleFutureContainerSupport(modelInstance) {
3141
2874
  }
3142
2875
  });
3143
2876
  }
3144
- if (mode === "full") {
3145
- Object.defineProperty(modelInstance, "progress", {
3146
- get() {
3147
- return futureHandler.future?.progress || 0;
3148
- },
3149
- enumerable: true,
3150
- configurable: true
3151
- });
3152
- Object.defineProperty(modelInstance, "status", {
3153
- get() {
3154
- return futureHandler.future?.status || "IDLE";
3155
- },
3156
- enumerable: true,
3157
- configurable: true
3158
- });
3159
- Object.defineProperty(modelInstance, "isRunning", {
3160
- get() {
3161
- return futureHandler.future ? !futureHandler.future.endState : false;
3162
- },
3163
- enumerable: true,
3164
- configurable: true
3165
- });
3166
- Object.defineProperty(modelInstance, "isCancelled", {
3167
- get() {
3168
- return futureHandler.future?.status === "CANCELLED" || false;
3169
- },
3170
- enumerable: true,
3171
- configurable: true
3172
- });
3173
- modelInstance.cancelFuture = async () => {
3174
- if (futureHandler.future) {
3175
- await futureHandler.future.cancelFuture();
3176
- }
3177
- };
3178
- }
3179
2877
  }
3180
2878
  function injectTroubleAwareSupport(modelInstance) {
3181
2879
  const troubleSetup = modelInstance[TroubleAwareSetup];
@@ -3469,9 +3167,6 @@ function kosTopicHandler(params2) {
3469
3167
  return (target, _propertyKey, descriptor) => {
3470
3168
  const configuration = prepareHandlerConfiguration(params2, descriptor);
3471
3169
  registerTopicHandlers(target, params2.topic, configuration);
3472
- if (params2.replay) {
3473
- configureReplayBehavior(params2.topic, params2.replay.bufferSize);
3474
- }
3475
3170
  };
3476
3171
  }
3477
3172
  function prepareHandlerConfiguration(params2, descriptor) {
@@ -3485,10 +3180,10 @@ function prepareHandlerConfiguration(params2, descriptor) {
3485
3180
  lifecycle,
3486
3181
  destinationAddress,
3487
3182
  explicitDestination = false,
3488
- debounce: debounce2,
3489
- throttle: throttle2,
3490
- buffer: buffer2,
3491
- filter: filter2,
3183
+ debounce,
3184
+ throttle,
3185
+ buffer,
3186
+ filter,
3492
3187
  once: once2,
3493
3188
  wildcardName,
3494
3189
  flow,
@@ -3496,12 +3191,12 @@ function prepareHandlerConfiguration(params2, descriptor) {
3496
3191
  } = params2;
3497
3192
  const originalHandler = descriptor.value;
3498
3193
  const enhancedHandler = applyFunctionalEnhancements(originalHandler, {
3499
- debounce: debounce2,
3500
- throttle: throttle2,
3501
- buffer: buffer2,
3194
+ debounce,
3195
+ throttle,
3196
+ buffer,
3502
3197
  once: once2
3503
3198
  });
3504
- const enhancedCondition = combineFilterWithCondition(filter2, condition);
3199
+ const enhancedCondition = combineFilterWithCondition(filter, condition);
3505
3200
  return {
3506
3201
  websocket,
3507
3202
  fos,
@@ -3549,12 +3244,12 @@ function applyFunctionalEnhancements(handler, enhancements) {
3549
3244
  }
3550
3245
  return enhancedHandler;
3551
3246
  }
3552
- function combineFilterWithCondition(filter2, condition) {
3553
- if (!filter2) {
3247
+ function combineFilterWithCondition(filter, condition) {
3248
+ if (!filter) {
3554
3249
  return condition;
3555
3250
  }
3556
3251
  return (payload, model, raw) => {
3557
- if (!filter2(raw)) {
3252
+ if (!filter(raw)) {
3558
3253
  return false;
3559
3254
  }
3560
3255
  return condition(payload, model, raw);
@@ -3570,9 +3265,6 @@ function registerTopicHandlers(target, topic, handlerConfig) {
3570
3265
  target[SubscriptionHandlers][topic] = handlerConfig;
3571
3266
  }
3572
3267
  }
3573
- function configureReplayBehavior(topic, bufferSize) {
3574
- setupReplayHandler(topic, bufferSize);
3575
- }
3576
3268
  function createDebouncedHandler(originalHandler, config2) {
3577
3269
  const delay2 = typeof config2 === "number" ? config2 : config2.delay;
3578
3270
  const strategy = determineDebounceStrategy(config2);
@@ -3656,18 +3348,18 @@ function createThrottledHandler(originalHandler, config2) {
3656
3348
  };
3657
3349
  }
3658
3350
  function createBufferedHandler(originalHandler, bufferConfig) {
3659
- const buffer2 = [];
3351
+ const buffer = [];
3660
3352
  let timeoutId = null;
3661
3353
  const maxSize = bufferConfig.maxSize || 1e3;
3662
3354
  const flush = (context) => {
3663
- if (buffer2.length > 0) {
3664
- originalHandler.call(context, [...buffer2]);
3665
- buffer2.length = 0;
3355
+ if (buffer.length > 0) {
3356
+ originalHandler.call(context, [...buffer]);
3357
+ buffer.length = 0;
3666
3358
  }
3667
3359
  };
3668
3360
  return function(payload) {
3669
- buffer2.push(payload);
3670
- if (buffer2.length >= maxSize) {
3361
+ buffer.push(payload);
3362
+ if (buffer.length >= maxSize) {
3671
3363
  if (timeoutId) {
3672
3364
  clearTimeout(timeoutId);
3673
3365
  timeoutId = null;
@@ -3692,12 +3384,6 @@ function createOnceHandler(originalHandler) {
3692
3384
  }
3693
3385
  };
3694
3386
  }
3695
- function setupReplayHandler(topic, bufferSize) {
3696
- const topics = Array.isArray(topic) ? topic : [topic];
3697
- topics.forEach((t) => {
3698
- replay(t, bufferSize);
3699
- });
3700
- }
3701
3387
  const isPrintable = (model) => typeof model.toJSON === "function";
3702
3388
  const isKosDataModel = (model) => model[DependencyModels] !== void 0;
3703
3389
  const isKosModelContainer = (model) => model.revision !== void 0 && model.index !== void 0;
@@ -4288,6 +3974,21 @@ const createModelDependency = (model, dependency) => {
4288
3974
  );
4289
3975
  return { dependentModel: null, dataModelId, success: false };
4290
3976
  }
3977
+ if (resolutionPolicy === DependencyResolutionPolicy.FAIL) {
3978
+ const errorMessage = `No ${dependency.modelType} model with id ${dataModelId} exists`;
3979
+ KosLog.error(
3980
+ `Failed to resolve dependency for model ${model.modelId}:
3981
+ - Dependency Type: ${dependency.modelType}
3982
+ - Dependency ID: ${dataModelId}
3983
+ - Resolution Policy: ${resolutionPolicy}
3984
+ - Parent Model: ${model.modelTypeName}
3985
+ - Parent Model ID: ${model.modelId}
3986
+ - Error: ${errorMessage}`
3987
+ );
3988
+ throw new Error(
3989
+ `Dependency resolution failed (policy: FAIL) - Model ${model.modelId} cannot resolve dependency ${dependency.modelType} [${dataModelId}]: ${errorMessage}`
3990
+ );
3991
+ }
4291
3992
  const hasOptions = Object.keys(options).length > 0;
4292
3993
  const modelClass = modelRegistry.class || modelRegistry.create;
4293
3994
  const requiresOptions = modelClass?.prototype?.[OptionsRequired] === true;
@@ -4330,11 +4031,6 @@ const createModelDependency = (model, dependency) => {
4330
4031
  - Provided Options: ${JSON.stringify(options, null, 2)}
4331
4032
  - Error: ${errorMessage}`
4332
4033
  );
4333
- if (resolutionPolicy === DependencyResolutionPolicy.FAIL) {
4334
- throw new Error(
4335
- `Dependency resolution failed (policy: FAIL) - Model ${model.modelId} cannot resolve dependency ${dependency.modelType} [${dataModelId}]: ${errorMessage}`
4336
- );
4337
- }
4338
4034
  throw error;
4339
4035
  }
4340
4036
  };
@@ -5499,8 +5195,8 @@ function uuid() {
5499
5195
  return v.toString(16);
5500
5196
  });
5501
5197
  }
5502
- function arrayBufferToBase64(buffer2) {
5503
- const bytes = new Uint8Array(buffer2);
5198
+ function arrayBufferToBase64(buffer) {
5199
+ const bytes = new Uint8Array(buffer);
5504
5200
  let binary = "";
5505
5201
  for (let i = 0; i < bytes.byteLength; i++) {
5506
5202
  binary += String.fromCharCode(bytes[i]);
@@ -5518,8 +5214,8 @@ function base64ToArrayBuffer(base64) {
5518
5214
  async function blobToArrayBuffer(blob) {
5519
5215
  return await blob.arrayBuffer();
5520
5216
  }
5521
- function arrayBufferToBlob(buffer2, type) {
5522
- return new Blob([buffer2], { type });
5217
+ function arrayBufferToBlob(buffer, type) {
5218
+ return new Blob([buffer], { type });
5523
5219
  }
5524
5220
  async function serializeFormData(formData) {
5525
5221
  const fields = {};
@@ -5530,12 +5226,12 @@ async function serializeFormData(formData) {
5530
5226
  });
5531
5227
  for (const [key, value] of entries) {
5532
5228
  if (value instanceof File) {
5533
- const buffer2 = await value.arrayBuffer();
5229
+ const buffer = await value.arrayBuffer();
5534
5230
  files.push({
5535
5231
  name: key,
5536
5232
  filename: value.name,
5537
5233
  type: value.type,
5538
- data: arrayBufferToBase64(buffer2)
5234
+ data: arrayBufferToBase64(buffer)
5539
5235
  });
5540
5236
  } else {
5541
5237
  fields[key] = value.toString();
@@ -5562,23 +5258,23 @@ async function processRequestBody(body) {
5562
5258
  return { data: body, contentType: "text/plain" };
5563
5259
  }
5564
5260
  if (body instanceof ArrayBuffer || body instanceof Uint8Array) {
5565
- let buffer2;
5261
+ let buffer;
5566
5262
  if (body instanceof Uint8Array) {
5567
- buffer2 = new ArrayBuffer(body.byteLength);
5568
- new Uint8Array(buffer2).set(body);
5263
+ buffer = new ArrayBuffer(body.byteLength);
5264
+ new Uint8Array(buffer).set(body);
5569
5265
  } else {
5570
- buffer2 = body;
5266
+ buffer = body;
5571
5267
  }
5572
5268
  return {
5573
- data: arrayBufferToBase64(buffer2),
5269
+ data: arrayBufferToBase64(buffer),
5574
5270
  contentType: "application/octet-stream",
5575
5271
  encoding: "base64"
5576
5272
  };
5577
5273
  }
5578
5274
  if (body instanceof Blob) {
5579
- const buffer2 = await blobToArrayBuffer(body);
5275
+ const buffer = await blobToArrayBuffer(body);
5580
5276
  return {
5581
- data: arrayBufferToBase64(buffer2),
5277
+ data: arrayBufferToBase64(buffer),
5582
5278
  contentType: body.type || "application/octet-stream",
5583
5279
  encoding: "base64"
5584
5280
  };
@@ -6470,8 +6166,11 @@ class ServiceRequestManager {
6470
6166
  model;
6471
6167
  responseStore;
6472
6168
  handlers;
6473
- constructor(model, responseStore) {
6169
+ /** Topic handlers waiting on a baseline live on the KosModel, not the data model. */
6170
+ baselineListener;
6171
+ constructor(model, responseStore, baselineListener) {
6474
6172
  this.model = model;
6173
+ this.baselineListener = baselineListener;
6475
6174
  this.responseStore = responseStore;
6476
6175
  this.handlers = /* @__PURE__ */ new Map();
6477
6176
  this.discoverHandlers();
@@ -6514,15 +6213,25 @@ class ServiceRequestManager {
6514
6213
  * Zone 1: Orchestrates the entire service request flow
6515
6214
  */
6516
6215
  async executeHandler(metadata) {
6216
+ let failure;
6517
6217
  try {
6518
6218
  if (!this.shouldProcessRequest(metadata)) {
6519
6219
  return;
6520
6220
  }
6521
6221
  const requestContext = await this.prepareAndExecuteRequest(metadata);
6522
- await this.processAndStoreResponse(requestContext, metadata);
6222
+ if (requestContext.error) {
6223
+ failure = {
6224
+ error: new Error(requestContext.error),
6225
+ errorContext: requestContext.errorContext
6226
+ };
6227
+ } else {
6228
+ await this.processAndStoreResponse(requestContext, metadata);
6229
+ }
6523
6230
  } catch (err) {
6524
- const error = err instanceof Error ? err : new Error(String(err));
6525
- await this.handleError(error, metadata);
6231
+ failure = { error: err instanceof Error ? err : new Error(String(err)) };
6232
+ }
6233
+ if (failure) {
6234
+ await this.handleError(failure.error, metadata, failure.errorContext);
6526
6235
  }
6527
6236
  }
6528
6237
  /**
@@ -6570,14 +6279,6 @@ class ServiceRequestManager {
6570
6279
  * Zone 2: Coordinates response processing and storage
6571
6280
  */
6572
6281
  async processAndStoreResponse(context, metadata) {
6573
- if (context.error) {
6574
- await this.handleError(
6575
- new Error(context.error),
6576
- metadata,
6577
- context.errorContext
6578
- );
6579
- return;
6580
- }
6581
6282
  const transformedData = await this.processResponse(
6582
6283
  context.response,
6583
6284
  metadata
@@ -6670,11 +6371,7 @@ class ServiceRequestManager {
6670
6371
  * @private
6671
6372
  */
6672
6373
  triggerBaselineQueueFlush(baselinePath) {
6673
- const subscriptionManager = this.model.subscriptionManager;
6674
- if (!subscriptionManager || !subscriptionManager.flushQueueForBaseline) {
6675
- return;
6676
- }
6677
- subscriptionManager.flushQueueForBaseline(baselinePath);
6374
+ this.baselineListener?.flushQueueForBaseline(baselinePath);
6678
6375
  }
6679
6376
  /**
6680
6377
  * Make HTTP request using existing KOS API client
@@ -6807,7 +6504,7 @@ class ServiceRequestManager {
6807
6504
  );
6808
6505
  if (errorHandler.defaultValue !== void 0) {
6809
6506
  const storageKey = createStorageKey(
6810
- metadata.path,
6507
+ resolvePathFromMetadata(metadata, this.model),
6811
6508
  metadata.method || "get"
6812
6509
  );
6813
6510
  this.responseStore.set(
@@ -6825,7 +6522,7 @@ class ServiceRequestManager {
6825
6522
  case "ignore":
6826
6523
  if (errorHandler.defaultValue !== void 0) {
6827
6524
  const storageKey = createStorageKey(
6828
- metadata.path,
6525
+ resolvePathFromMetadata(metadata, this.model),
6829
6526
  metadata.method || "get"
6830
6527
  );
6831
6528
  this.responseStore.set(
@@ -6843,7 +6540,7 @@ class ServiceRequestManager {
6843
6540
  case "default":
6844
6541
  if (errorHandler.defaultValue !== void 0) {
6845
6542
  const storageKey = createStorageKey(
6846
- metadata.path,
6543
+ resolvePathFromMetadata(metadata, this.model),
6847
6544
  metadata.method || "get"
6848
6545
  );
6849
6546
  this.responseStore.set(
@@ -6930,8 +6627,6 @@ class FlowControlManager {
6930
6627
  config;
6931
6628
  stats;
6932
6629
  filterHistory = [];
6933
- activePromises = /* @__PURE__ */ new Set();
6934
- eventQueue = [];
6935
6630
  rateLimitWindow = /* @__PURE__ */ new Map();
6936
6631
  constructor(config2) {
6937
6632
  this.config = config2;
@@ -6939,7 +6634,6 @@ class FlowControlManager {
6939
6634
  eventsReceived: 0,
6940
6635
  batchesProcessed: 0,
6941
6636
  eventsDropped: 0,
6942
- currentQueueSize: 0,
6943
6637
  averageBatchSize: 0,
6944
6638
  processingRate: 0,
6945
6639
  lastProcessedAt: Date.now()
@@ -6960,86 +6654,89 @@ class FlowControlManager {
6960
6654
  if (this.config.filter && !this.shouldProcessEvent(event)) {
6961
6655
  return;
6962
6656
  }
6963
- if (this.config.rateLimit && !this.checkRateLimit()) {
6964
- if (this.config.rateLimit.onExceeded === "drop") {
6965
- this.stats.eventsDropped++;
6966
- return;
6967
- } else if (this.config.rateLimit.onExceeded === "delay") {
6968
- await this.waitForRateLimit();
6969
- }
6970
- }
6971
- if (this.config.backpressure) {
6972
- this.enqueueEvent(event);
6973
- await this.waitForCapacity();
6974
- const queuedEvent = this.dequeueEvent();
6975
- if (queuedEvent) {
6976
- const transformed = this.config.transform ? this.config.transform([queuedEvent]) : [queuedEvent];
6977
- yield transformed;
6978
- this.updateProcessingStats([queuedEvent]);
6979
- }
6980
- } else {
6981
- const transformed = this.config.transform ? this.config.transform([event]) : [event];
6982
- yield transformed;
6983
- this.updateProcessingStats([event]);
6657
+ if (!await this.admitRateLimited()) {
6658
+ return;
6984
6659
  }
6660
+ const transformed = this.config.transform ? this.config.transform([event]) : [event];
6661
+ yield transformed;
6662
+ this.updateProcessingStats([event]);
6985
6663
  }
6664
+ /**
6665
+ * Collects admitted events into batches. A batch is delivered when it
6666
+ * reaches `size`, when `window` ms have passed since its first event, or
6667
+ * when the stream ends. The window timer is cleared on every flush and when
6668
+ * the generator finishes or is returned.
6669
+ */
6986
6670
  async *processBatchedEvents(eventStream, batchConfig) {
6987
6671
  const maxSize = batchConfig.size || 100;
6988
6672
  const maxWait = batchConfig.window || 1e3;
6673
+ const iterator = eventStream[Symbol.asyncIterator]();
6989
6674
  let batch = [];
6990
- let lastFlush = Date.now();
6991
- const flushBatch = async () => {
6992
- if (batch.length === 0) return void 0;
6993
- const currentBatch = [...batch];
6675
+ let windowTimer;
6676
+ let windowElapsed;
6677
+ let elapsed = false;
6678
+ let pending;
6679
+ let sourceDone = false;
6680
+ const openWindow = () => {
6681
+ windowElapsed = new Promise((resolve) => {
6682
+ windowTimer = setTimeout(() => {
6683
+ elapsed = true;
6684
+ resolve("window");
6685
+ }, maxWait);
6686
+ });
6687
+ };
6688
+ const closeWindow = () => {
6689
+ clearTimeout(windowTimer);
6690
+ windowTimer = void 0;
6691
+ windowElapsed = void 0;
6692
+ elapsed = false;
6693
+ };
6694
+ const flushBatch = () => {
6695
+ const currentBatch = batch;
6994
6696
  batch = [];
6995
- lastFlush = Date.now();
6996
- const filteredBatch = this.config.filter ? currentBatch.filter((event) => this.shouldProcessEvent(event)) : currentBatch;
6997
- if (filteredBatch.length === 0) return void 0;
6998
- if (this.config.backpressure) {
6999
- await this.waitForCapacity();
7000
- }
7001
- const transformed = this.config.transform ? this.config.transform(filteredBatch) : filteredBatch;
6697
+ closeWindow();
6698
+ const transformed = this.config.transform ? this.config.transform(currentBatch) : currentBatch;
7002
6699
  this.stats.batchesProcessed++;
7003
- this.updateProcessingStats(filteredBatch);
6700
+ this.updateProcessingStats(currentBatch);
7004
6701
  return transformed;
7005
6702
  };
7006
6703
  try {
7007
- for await (const event of eventStream) {
6704
+ while (true) {
6705
+ pending ??= iterator.next();
6706
+ const next = windowElapsed ? await Promise.race([pending, windowElapsed]) : await pending;
6707
+ if (next === "window") {
6708
+ yield flushBatch();
6709
+ continue;
6710
+ }
6711
+ pending = void 0;
6712
+ if (next.done) {
6713
+ sourceDone = true;
6714
+ break;
6715
+ }
6716
+ const event = next.value;
7008
6717
  this.stats.eventsReceived++;
7009
- if (this.config.backpressure) {
7010
- this.enqueueEvent(event);
7011
- while (this.eventQueue.length > 0) {
7012
- const queuedEvent = this.dequeueEvent();
7013
- if (queuedEvent) {
7014
- batch.push(queuedEvent);
7015
- }
7016
- const now = Date.now();
7017
- const timeSinceLastFlush = now - lastFlush;
7018
- if (batch.length >= maxSize || timeSinceLastFlush >= maxWait) {
7019
- const flushed2 = await flushBatch();
7020
- if (flushed2 !== void 0) {
7021
- yield flushed2;
7022
- }
7023
- break;
7024
- }
7025
- }
7026
- } else {
7027
- batch.push(event);
7028
- const now = Date.now();
7029
- const timeSinceLastFlush = now - lastFlush;
7030
- if (batch.length >= maxSize || timeSinceLastFlush >= maxWait) {
7031
- const flushed2 = await flushBatch();
7032
- if (flushed2 !== void 0) {
7033
- yield flushed2;
7034
- }
7035
- }
6718
+ if (this.config.filter && !this.shouldProcessEvent(event)) {
6719
+ continue;
6720
+ }
6721
+ if (!await this.admitRateLimited()) {
6722
+ continue;
6723
+ }
6724
+ batch.push(event);
6725
+ if (batch.length === 1) {
6726
+ openWindow();
6727
+ }
6728
+ if (batch.length >= maxSize || elapsed) {
6729
+ yield flushBatch();
7036
6730
  }
7037
6731
  }
7038
- const flushed = await flushBatch();
7039
- if (flushed !== void 0) {
7040
- yield flushed;
6732
+ if (batch.length > 0) {
6733
+ yield flushBatch();
7041
6734
  }
7042
6735
  } finally {
6736
+ closeWindow();
6737
+ if (!sourceDone) {
6738
+ void iterator.return?.();
6739
+ }
7043
6740
  }
7044
6741
  }
7045
6742
  shouldProcessEvent(event) {
@@ -7058,6 +6755,23 @@ class FlowControlManager {
7058
6755
  }
7059
6756
  return shouldProcess;
7060
6757
  }
6758
+ /**
6759
+ * Counts an event against the rate limit. Resolves false when the event is
6760
+ * dropped; with `onExceeded: "delay"` it waits for a window with room and
6761
+ * counts the event there.
6762
+ */
6763
+ async admitRateLimited() {
6764
+ const rateLimit = this.config.rateLimit;
6765
+ if (!rateLimit) return true;
6766
+ while (!this.checkRateLimit()) {
6767
+ if (rateLimit.onExceeded !== "delay") {
6768
+ this.stats.eventsDropped++;
6769
+ return false;
6770
+ }
6771
+ await this.waitForRateLimit();
6772
+ }
6773
+ return true;
6774
+ }
7061
6775
  checkRateLimit() {
7062
6776
  if (!this.config.rateLimit) return true;
7063
6777
  const now = Date.now();
@@ -7084,70 +6798,12 @@ class FlowControlManager {
7084
6798
  await new Promise((resolve) => setTimeout(resolve, waitTime));
7085
6799
  }
7086
6800
  }
7087
- async waitForCapacity() {
7088
- if (!this.config.backpressure) return;
7089
- const maxConcurrent = this.config.backpressure.maxConcurrent || 5;
7090
- const maxQueue = this.config.backpressure.maxQueue || 1e3;
7091
- while (this.activePromises.size >= maxConcurrent) {
7092
- await Promise.race(this.activePromises);
7093
- }
7094
- if (this.eventQueue.length >= maxQueue) {
7095
- this.handleQueueOverflow();
7096
- }
7097
- }
7098
- handleQueueOverflow() {
7099
- if (!this.config.backpressure) return;
7100
- const maxQueue = this.config.backpressure.maxQueue || 1e3;
7101
- const dropPolicy = this.config.backpressure.dropPolicy || "oldest";
7102
- const onQueueFull = this.config.backpressure.onQueueFull;
7103
- if (dropPolicy === "none") {
7104
- return;
7105
- }
7106
- const overflow = this.eventQueue.length - maxQueue;
7107
- if (overflow <= 0) return;
7108
- let droppedEvents = [];
7109
- if (dropPolicy === "oldest") {
7110
- droppedEvents = this.eventQueue.splice(0, overflow);
7111
- } else if (dropPolicy === "newest") {
7112
- droppedEvents = this.eventQueue.splice(-overflow);
7113
- }
7114
- this.stats.eventsDropped += droppedEvents.length;
7115
- this.stats.currentQueueSize = this.eventQueue.length;
7116
- if (onQueueFull && droppedEvents.length > 0) {
7117
- try {
7118
- onQueueFull(droppedEvents);
7119
- } catch (error) {
7120
- console.warn("Error in onQueueFull callback:", error);
7121
- }
7122
- }
7123
- }
7124
- enqueueEvent(event) {
7125
- this.eventQueue.push(event);
7126
- this.stats.currentQueueSize = this.eventQueue.length;
7127
- if (this.config.backpressure) {
7128
- const maxQueue = this.config.backpressure.maxQueue || 1e3;
7129
- if (this.eventQueue.length > maxQueue) {
7130
- this.handleQueueOverflow();
7131
- }
7132
- }
7133
- }
7134
- dequeueEvent() {
7135
- const event = this.eventQueue.shift();
7136
- this.stats.currentQueueSize = this.eventQueue.length;
7137
- return event;
7138
- }
7139
6801
  updateProcessingStats(batch) {
7140
6802
  const now = Date.now();
7141
6803
  const timeSinceLastProcessed = now - this.stats.lastProcessedAt;
7142
6804
  this.stats.averageBatchSize = (this.stats.averageBatchSize * this.stats.batchesProcessed + batch.length) / (this.stats.batchesProcessed + 1);
7143
6805
  this.stats.processingRate = timeSinceLastProcessed > 0 ? batch.length / (timeSinceLastProcessed / 1e3) : this.stats.processingRate;
7144
6806
  this.stats.lastProcessedAt = now;
7145
- this.stats.currentQueueSize = this.eventQueue.length;
7146
- }
7147
- trackPromise(promise) {
7148
- this.activePromises.add(promise);
7149
- promise.finally(() => this.activePromises.delete(promise));
7150
- return promise;
7151
6807
  }
7152
6808
  getStats() {
7153
6809
  return { ...this.stats };
@@ -7469,24 +7125,24 @@ const summarize = (name, fixture) => {
7469
7125
  };
7470
7126
  };
7471
7127
  const openDb = () => new Promise((resolve, reject) => {
7472
- const request2 = indexedDB.open(DB_NAME, 1);
7473
- request2.onupgradeneeded = () => {
7474
- if (!request2.result.objectStoreNames.contains(STORE_NAME)) {
7475
- request2.result.createObjectStore(STORE_NAME);
7128
+ const request = indexedDB.open(DB_NAME, 1);
7129
+ request.onupgradeneeded = () => {
7130
+ if (!request.result.objectStoreNames.contains(STORE_NAME)) {
7131
+ request.result.createObjectStore(STORE_NAME);
7476
7132
  }
7477
7133
  };
7478
- request2.onsuccess = () => resolve(request2.result);
7479
- request2.onerror = () => reject(request2.error);
7134
+ request.onsuccess = () => resolve(request.result);
7135
+ request.onerror = () => reject(request.error);
7480
7136
  });
7481
7137
  const withStore = async (mode, operation) => {
7482
7138
  const db = await openDb();
7483
7139
  try {
7484
7140
  return await new Promise((resolve, reject) => {
7485
- const request2 = operation(
7141
+ const request = operation(
7486
7142
  db.transaction(STORE_NAME, mode).objectStore(STORE_NAME)
7487
7143
  );
7488
- request2.onsuccess = () => resolve(request2.result);
7489
- request2.onerror = () => reject(request2.error);
7144
+ request.onsuccess = () => resolve(request.result);
7145
+ request.onerror = () => reject(request.error);
7490
7146
  });
7491
7147
  } finally {
7492
7148
  db.close();
@@ -8041,17 +7697,17 @@ class KosMockRecorder {
8041
7697
  }
8042
7698
  const responseId = headers["response-id"];
8043
7699
  if (responseId) {
8044
- const request2 = this.pending.get(responseId);
8045
- if (!request2) {
7700
+ const request = this.pending.get(responseId);
7701
+ if (!request) {
8046
7702
  return;
8047
7703
  }
8048
7704
  this.pending.delete(responseId);
8049
7705
  this.exchanges.push({
8050
- ...request2,
7706
+ ...request,
8051
7707
  status: parseInt(headers["status"] ?? "200", 10) || 200,
8052
7708
  responseBody: body ?? "",
8053
7709
  responseHeaders: headers,
8054
- latencyMs: Math.max(0, this.elapsed() - request2.tMs),
7710
+ latencyMs: Math.max(0, this.elapsed() - request.tMs),
8055
7711
  ...headers[KOS_MOCKED_HEADER] === "true" ? { mocked: true } : {}
8056
7712
  });
8057
7713
  return;
@@ -8339,13 +7995,13 @@ class KosMockRegistry {
8339
7995
  if (!responseId) {
8340
7996
  return frame;
8341
7997
  }
8342
- const request2 = this.pendingRequests.get(responseId);
7998
+ const request = this.pendingRequests.get(responseId);
8343
7999
  this.pendingRequests.delete(responseId);
8344
- if (!request2) {
8000
+ if (!request) {
8345
8001
  return frame;
8346
8002
  }
8347
8003
  const matching = this.transformers.filter(
8348
- (transformer) => methodMatches(transformer.method, request2.method) && matchRoutePattern(transformer.compiled, request2.path) !== void 0
8004
+ (transformer) => methodMatches(transformer.method, request.method) && matchRoutePattern(transformer.compiled, request.path) !== void 0
8349
8005
  );
8350
8006
  if (matching.length === 0) {
8351
8007
  return frame;
@@ -8357,7 +8013,7 @@ class KosMockRegistry {
8357
8013
  return frame;
8358
8014
  }
8359
8015
  const info = {
8360
- request: request2,
8016
+ request,
8361
8017
  headers,
8362
8018
  status: parseInt(headers["status"] ?? "200", 10) || 200,
8363
8019
  mocked: headers[KOS_MOCKED_HEADER] === "true"
@@ -8744,7 +8400,7 @@ class KosMockRegistry {
8744
8400
  }
8745
8401
  return false;
8746
8402
  }
8747
- const request2 = {
8403
+ const request = {
8748
8404
  method: frame.method,
8749
8405
  url: frame.url,
8750
8406
  path,
@@ -8765,12 +8421,12 @@ class KosMockRegistry {
8765
8421
  }
8766
8422
  }
8767
8423
  };
8768
- void this.resolve(request2, candidates, io, policy);
8424
+ void this.resolve(request, candidates, io, policy);
8769
8425
  return true;
8770
8426
  }
8771
- async resolve(request2, candidates, io, policy) {
8427
+ async resolve(request, candidates, io, policy) {
8772
8428
  for (const { route, params: params2 } of candidates) {
8773
- const scopedRequest = { ...request2, params: params2 };
8429
+ const scopedRequest = { ...request, params: params2 };
8774
8430
  if (route.when) {
8775
8431
  let accepted = false;
8776
8432
  try {
@@ -8809,21 +8465,21 @@ class KosMockRegistry {
8809
8465
  if (route.once) {
8810
8466
  this.removeRoute(route.id);
8811
8467
  }
8812
- this.deliverResponse(io, request2.requestId, response, route);
8468
+ this.deliverResponse(io, request.requestId, response, route);
8813
8469
  return;
8814
8470
  }
8815
8471
  if (policy === "respond404") {
8816
- this.deliverResponse(io, request2.requestId, {
8472
+ this.deliverResponse(io, request.requestId, {
8817
8473
  status: 404,
8818
8474
  data: {
8819
- message: `KosMock: all routes declined ${request2.method} ${request2.path}`
8475
+ message: `KosMock: all routes declined ${request.method} ${request.path}`
8820
8476
  }
8821
8477
  });
8822
8478
  return;
8823
8479
  }
8824
8480
  if (policy === "warn") {
8825
8481
  KosLog.warn(
8826
- `KosMock: all routes declined ${request2.method} ${request2.path}`
8482
+ `KosMock: all routes declined ${request.method} ${request.path}`
8827
8483
  );
8828
8484
  }
8829
8485
  io.forward();
@@ -10050,10 +9706,10 @@ class KosSubscriptionManager {
10050
9706
  async startFlowProcessing(config2, resolvedTopic, handler, flowManager) {
10051
9707
  const controller = new AbortController();
10052
9708
  try {
10053
- let eventSource;
9709
+ let unsubscribeTopic;
10054
9710
  if (config2.websocket) {
10055
9711
  const { destinationAddress, explicitDestination } = this.resolveDestination(config2);
10056
- WebSocketTransport.getInstance().subscribeTopic({
9712
+ unsubscribeTopic = WebSocketTransport.getInstance().subscribeTopic({
10057
9713
  topic: resolvedTopic,
10058
9714
  callback: () => {
10059
9715
  },
@@ -10063,10 +9719,12 @@ class KosSubscriptionManager {
10063
9719
  destinationAddress,
10064
9720
  explicitDestination
10065
9721
  });
10066
- eventSource = iterate(resolvedTopic);
10067
- } else {
10068
- eventSource = iterate(resolvedTopic);
10069
9722
  }
9723
+ const eventSource = iterate(resolvedTopic);
9724
+ controller.signal.addEventListener("abort", () => {
9725
+ void eventSource.return();
9726
+ unsubscribeTopic?.();
9727
+ });
10070
9728
  (async () => {
10071
9729
  try {
10072
9730
  for await (const processedData of flowManager.processEvents(
@@ -10075,7 +9733,7 @@ class KosSubscriptionManager {
10075
9733
  if (controller.signal.aborted) break;
10076
9734
  const handlerPromise = handler(processedData);
10077
9735
  if (handlerPromise instanceof Promise) {
10078
- await flowManager.trackPromise(handlerPromise);
9736
+ await handlerPromise;
10079
9737
  }
10080
9738
  }
10081
9739
  } catch (error) {
@@ -10197,12 +9855,12 @@ class KosSubscriptionManager {
10197
9855
  * Trigger smart queue flush with baseline temporal filtering
10198
9856
  * Called after baseline loads to replay queued events
10199
9857
  *
10200
- * @param topic - Topic that had baseline dependency
9858
+ * @param path - Path of the baseline request that completed
10201
9859
  */
10202
- flushQueueForBaseline(topic) {
10203
- const baseline = this.baselineDependencies.get(topic);
9860
+ flushQueueForBaseline(path) {
9861
+ const [topic, baseline] = [...this.baselineDependencies].find(([, b]) => b.path === path) ?? [];
10204
9862
  if (!baseline) {
10205
- this.log.debug(`No baseline dependency for topic: ${topic}`);
9863
+ this.log.debug(`No baseline dependency on path: ${path}`);
10206
9864
  return;
10207
9865
  }
10208
9866
  const store = this.getResponseStore();
@@ -10444,9 +10102,11 @@ class ServiceResponseStore {
10444
10102
  return config2.retention === ResponseRetention.TTL && config2.ttl ? Date.now() + config2.ttl : void 0;
10445
10103
  }
10446
10104
  /**
10447
- * Store response with retention policy
10105
+ * Store response with retention policy, cancelling the cleanup timer of the
10106
+ * response it replaces
10448
10107
  */
10449
10108
  storeResponse(key, cached, config2) {
10109
+ this.clearTimerIfExists(key);
10450
10110
  this.responses.set(key, cached);
10451
10111
  this.retentionPolicies.set(key, config2);
10452
10112
  this.applyRetentionPolicy(key, config2);
@@ -10542,9 +10202,14 @@ class KosModelComponentFactory {
10542
10202
  const childResolver = new KosChildResolver(model);
10543
10203
  const serviceResponseStore = new ServiceResponseStore();
10544
10204
  modelData.serviceResponses = serviceResponseStore;
10205
+ const onlineLifecycleManager = new KosOnlineLifecycleManager(
10206
+ model,
10207
+ createTaggedLogger(log2, "online")
10208
+ );
10545
10209
  const components = {
10546
10210
  fsm: fsm2,
10547
10211
  offlineQueue,
10212
+ onlineLifecycleManager,
10548
10213
  serviceResponseStore,
10549
10214
  companionManager,
10550
10215
  childResolver
@@ -10566,10 +10231,6 @@ class KosModelComponentFactory {
10566
10231
  offlineQueue,
10567
10232
  subLogger
10568
10233
  );
10569
- components.onlineLifecycleManager = new KosOnlineLifecycleManager(
10570
- model,
10571
- createTaggedLogger(log2, "online")
10572
- );
10573
10234
  }
10574
10235
  if (hasHttpRouteHandlers(modelData)) {
10575
10236
  components.httpRouteManager = new KosHttpRouteManager(
@@ -10580,7 +10241,8 @@ class KosModelComponentFactory {
10580
10241
  if (hasServiceRequestHandlers(modelData)) {
10581
10242
  components.serviceRequestManager = new ServiceRequestManager(
10582
10243
  modelData,
10583
- serviceResponseStore
10244
+ serviceResponseStore,
10245
+ components.subscriptionManager
10584
10246
  );
10585
10247
  }
10586
10248
  return components;
@@ -10966,11 +10628,21 @@ class KosModel {
10966
10628
  createLifecycleCompanions(lifecycle) {
10967
10629
  this.modelManager.createLifecycleCompanions(this, {}, lifecycle);
10968
10630
  }
10631
+ /**
10632
+ * Runs on every transition to online, including each reconnect, so the
10633
+ * ONLINE dependencies and service requests are resolved and sent again
10634
+ * each time. A state machine with `initializeAt: ONLINE` starts once.
10635
+ */
10969
10636
  async online() {
10970
10637
  log$8.debug(`online model ${this.modelTypeName} with id ${this.modelId}`);
10971
10638
  this.registerSubscribers();
10639
+ await executeDependentModelLifecycle(this, DependencyLifecycle.ONLINE);
10640
+ await this.serviceRequestManager?.executeForLifecycle(
10641
+ DependencyLifecycle.ONLINE
10642
+ );
10972
10643
  const context = KosContextManager.getContext(this.modelId);
10973
10644
  await this.modelData?.online?.(context);
10645
+ this.initializeStateMachineForLifecycle(DependencyLifecycle.ONLINE);
10974
10646
  this.createLifecycleCompanions(DependencyLifecycle.ONLINE);
10975
10647
  }
10976
10648
  async offline() {
@@ -11732,6 +11404,7 @@ const getConnectionAlias = () => {
11732
11404
  const envAlias = process.env.KOS_CONNECTION_ALIAS;
11733
11405
  return alias || envAlias || void 0;
11734
11406
  };
11407
+ const resolveAliasTemplate = (alias) => alias.replace("{{TIMESTAMP}}", Date.now().toString());
11735
11408
  const getDefaultProtocol = () => {
11736
11409
  const defaultProtocol = window.location.protocol;
11737
11410
  const params2 = getQueryParams();
@@ -11872,11 +11545,40 @@ class KosCore {
11872
11545
  }
11873
11546
  const alias = getConnectionAlias() ?? connectionAlias;
11874
11547
  if (alias) {
11875
- ws.alias = alias.replace("{{TIMESTAMP}}", Date.now().toString());
11548
+ ws.alias = resolveAliasTemplate(alias);
11876
11549
  }
11877
11550
  this._transport = ws.init();
11878
11551
  this.fsmService = coreFsm(this);
11879
11552
  }
11553
+ /**
11554
+ * Registers `connectionAlias` on a core whose transport has no alias yet:
11555
+ * the alias frame goes out now on an open connection, or first thing when
11556
+ * the connection opens, and every reconnect carries it. A transport that
11557
+ * already has an alias keeps it.
11558
+ */
11559
+ applyConnectionAlias(connectionAlias) {
11560
+ if (this._transport.alias) {
11561
+ if (this.connectionAlias && this.connectionAlias !== connectionAlias) {
11562
+ log$5.warn(
11563
+ `Connection alias ${connectionAlias} ignored; the connection already uses ${this._transport.alias}`
11564
+ );
11565
+ }
11566
+ return;
11567
+ }
11568
+ this.connectionAlias = connectionAlias;
11569
+ const alias = resolveAliasTemplate(connectionAlias);
11570
+ this._transport.alias = alias;
11571
+ const frame = `type:kos.addr.alias
11572
+ alias:${alias}
11573
+
11574
+ `;
11575
+ const socket = this._transport.socket;
11576
+ if (socket?.connectionEstablished) {
11577
+ socket.socket.send(frame);
11578
+ } else {
11579
+ socket?.addOfflineMessage(frame);
11580
+ }
11581
+ }
11880
11582
  startLifecycle() {
11881
11583
  if (this.lifecycleStarted) {
11882
11584
  return;
@@ -12109,11 +11811,21 @@ class KosCore {
12109
11811
  instance.startLifecycle();
12110
11812
  return instance;
12111
11813
  }
11814
+ /**
11815
+ * Returns the process-wide core, constructing it on first use or when
11816
+ * `reset` is set.
11817
+ *
11818
+ * `connectionAlias` applies to an existing core too, provided its transport
11819
+ * has no alias yet: registering a model reaches this method, so a
11820
+ * registration chain can construct the core before the alias is known.
11821
+ */
12112
11822
  static getInstance(data) {
12113
11823
  this._instance = window.KosCore;
12114
11824
  if (!this._instance || data?.reset) {
12115
11825
  window.KosCore = new this(data?.connectionAlias);
12116
11826
  this._instance = window.KosCore;
11827
+ } else if (data?.connectionAlias && this._instance instanceof KosCore) {
11828
+ this._instance.applyConnectionAlias(data.connectionAlias);
12117
11829
  }
12118
11830
  return this._instance;
12119
11831
  }
@@ -13404,7 +13116,7 @@ export {
13404
13116
  kosAutoEffect as Z,
13405
13117
  isKosExecutionContext as _,
13406
13118
  CompanionParentModel as a,
13407
- KosHttpRouteManager as a$,
13119
+ KosMock as a$,
13408
13120
  EXTENSION_FUTURE_LIFECYCLE_WRAPPER as a0,
13409
13121
  kosObservable as a1,
13410
13122
  sendKosHttpMessageResponse as a2,
@@ -13419,29 +13131,29 @@ export {
13419
13131
  EVENT_KOS_MODEL_READY as aB,
13420
13132
  EXTENSION_FEATURE_FLAG_RESOLVER as aC,
13421
13133
  eventBus as aD,
13422
- eventBus_functional as aE,
13423
- eventBus_state as aF,
13424
- ExtensionException as aG,
13425
- FeatureFlagService as aH,
13426
- HEADER_CACHE_CONTROL as aI,
13427
- HEADER_CONTENT_TYPE as aJ,
13428
- HEADER_DESTINATION_ADDR as aK,
13429
- HEADER_FOS_REQUEST_ID as aL,
13430
- HEADER_METHOD as aM,
13431
- HEADER_ORDERED as aN,
13432
- HEADER_REQUEST_ID as aO,
13433
- HEADER_REQUEST_TYPE as aP,
13434
- HEADER_RESPONSE_ID as aQ,
13435
- HEADER_SOURCE_ADDR as aR,
13436
- HEADER_TOPIC as aS,
13437
- HEADER_URL as aT,
13438
- HEADER_WORK_TRACKER as aU,
13439
- HttpRouteHandlers as aV,
13440
- KosContainerIndex as aW,
13441
- KosContextBean as aX,
13442
- kosDependency as aY,
13443
- KosFeatureFlags as aZ,
13444
- KosGlobalConfig as a_,
13134
+ eventBus_state as aE,
13135
+ ExtensionException as aF,
13136
+ FeatureFlagService as aG,
13137
+ HEADER_CACHE_CONTROL as aH,
13138
+ HEADER_CONTENT_TYPE as aI,
13139
+ HEADER_DESTINATION_ADDR as aJ,
13140
+ HEADER_FOS_REQUEST_ID as aK,
13141
+ HEADER_METHOD as aL,
13142
+ HEADER_ORDERED as aM,
13143
+ HEADER_REQUEST_ID as aN,
13144
+ HEADER_REQUEST_TYPE as aO,
13145
+ HEADER_RESPONSE_ID as aP,
13146
+ HEADER_SOURCE_ADDR as aQ,
13147
+ HEADER_TOPIC as aR,
13148
+ HEADER_URL as aS,
13149
+ HEADER_WORK_TRACKER as aT,
13150
+ HttpRouteHandlers as aU,
13151
+ KosContainerIndex as aV,
13152
+ KosContextBean as aW,
13153
+ kosDependency as aX,
13154
+ KosFeatureFlags as aY,
13155
+ KosGlobalConfig as aZ,
13156
+ KosHttpRouteManager as a_,
13445
13157
  get as aa,
13446
13158
  getQueryParams as ab,
13447
13159
  kosEffect as ac,
@@ -13470,10 +13182,10 @@ export {
13470
13182
  DependencyResolutionPolicy as az,
13471
13183
  ContainerAwareSetup as b,
13472
13184
  getKosSessionKey as b$,
13473
- KosMock as b0,
13474
- KosModel as b1,
13475
- KosModelFactory as b2,
13476
- KosModelManager as b3,
13185
+ KosModel as b0,
13186
+ KosModelFactory as b1,
13187
+ KosModelManager as b2,
13188
+ KosModelSymbol as b3,
13477
13189
  KosObservableData as b4,
13478
13190
  KosWSTransportStatus as b5,
13479
13191
  LOADER_FEATURE_FLAG as b6,
@@ -13543,59 +13255,58 @@ export {
13543
13255
  hasHttpRouteHandlers$1 as c6,
13544
13256
  hasKosProfile as c7,
13545
13257
  httpDelete as c8,
13546
- initializeStateMachine as c9,
13547
- sendBroadcastMessage as cA,
13548
- sendIntent as cB,
13549
- sendKosMessage as cC,
13550
- sendStudioMessage as cD,
13551
- sendStudioMessageRequest as cE,
13552
- troubleByTypeReducer as cF,
13553
- unloadKosModel as cG,
13554
- waitForAppToStart as cH,
13555
- waitForAppsToStart as cI,
13556
- service as cJ,
13557
- isKosCompanionTypeFactory as ca,
13558
- isKosDataModel as cb,
13559
- isKosLoggingEnabled as cc,
13560
- isKosModelContainer as cd,
13561
- isLocalRefId as ce,
13562
- isPrintable as cf,
13563
- isTransportNotReadyError as cg,
13564
- kosReloadAware as ch,
13565
- kosStateEntry as ci,
13566
- kosStateExit as cj,
13567
- kosStateGuard as ck,
13568
- kosStateMachine as cl,
13569
- modelEventTopicFactory as cm,
13570
- modelTypeEventTopicFactory as cn,
13571
- parseWildcardSegment as co,
13572
- preloadKosModel as cp,
13573
- put as cq,
13574
- registerCompanionModel as cr,
13575
- registerHttpRoutes as cs,
13576
- resetKosModel as ct,
13577
- resolveBaseUrl as cu,
13578
- resolveChild as cv,
13579
- resolveKosContext as cw,
13580
- resolveKosProfiles as cx,
13581
- resolveServiceRequestParameters as cy,
13582
- sendAsyncIntent as cz,
13258
+ isKosCompanionTypeFactory as c9,
13259
+ sendIntent as cA,
13260
+ sendKosMessage as cB,
13261
+ sendStudioMessage as cC,
13262
+ sendStudioMessageRequest as cD,
13263
+ troubleByTypeReducer as cE,
13264
+ unloadKosModel as cF,
13265
+ waitForAppToStart as cG,
13266
+ waitForAppsToStart as cH,
13267
+ service as cI,
13268
+ isKosDataModel as ca,
13269
+ isKosLoggingEnabled as cb,
13270
+ isKosModelContainer as cc,
13271
+ isLocalRefId as cd,
13272
+ isPrintable as ce,
13273
+ isTransportNotReadyError as cf,
13274
+ kosReloadAware as cg,
13275
+ kosStateEntry as ch,
13276
+ kosStateExit as ci,
13277
+ kosStateGuard as cj,
13278
+ kosStateMachine as ck,
13279
+ modelEventTopicFactory as cl,
13280
+ modelTypeEventTopicFactory as cm,
13281
+ parseWildcardSegment as cn,
13282
+ preloadKosModel as co,
13283
+ put as cp,
13284
+ registerCompanionModel as cq,
13285
+ registerHttpRoutes as cr,
13286
+ resetKosModel as cs,
13287
+ resolveBaseUrl as ct,
13288
+ resolveChild as cu,
13289
+ resolveKosContext as cv,
13290
+ resolveKosProfiles as cw,
13291
+ resolveServiceRequestParameters as cx,
13292
+ sendAsyncIntent as cy,
13293
+ sendBroadcastMessage as cz,
13583
13294
  KosLoggerFactory as d,
13584
- KosModelSymbol as e,
13295
+ KosViewModelSymbol as e,
13585
13296
  ModelEffects as f,
13586
13297
  DependencyLifecycle as g,
13587
- KosViewModelSymbol as h,
13588
- StateMachineSetup as i,
13589
- injectStateMachineSupport as j,
13298
+ StateMachineSetup as h,
13299
+ injectStateMachineSupport as i,
13300
+ initializeStateMachine as j,
13590
13301
  KosModelVisitor as k,
13591
13302
  KosCore as l,
13592
- KosLog as m,
13593
- subscribe as n,
13303
+ sendKosMessageResponse as m,
13304
+ KosLog as n,
13594
13305
  INDEX_COLLECTION_KEY as o,
13595
13306
  publish as p,
13596
13307
  KosContainerIndexEvents as q,
13597
13308
  isIndexableItem as r,
13598
- sendKosMessageResponse as s,
13309
+ subscribe as s,
13599
13310
  Kos as t,
13600
13311
  uuid as u,
13601
13312
  isKosModel as v,
@@ -13604,4 +13315,4 @@ export {
13604
13315
  ObservableData as y,
13605
13316
  kosAction as z
13606
13317
  };
13607
- //# sourceMappingURL=index-YzHb2lnB.js.map
13318
+ //# sourceMappingURL=index-Csq0zQtb.js.map