@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
@@ -95,17 +95,17 @@ function reset() {
95
95
  log$q.warn("Resetting event bus");
96
96
  Object.keys(subscriptions).forEach((key) => delete subscriptions[key]);
97
97
  }
98
- function once$1(eventType, callback) {
98
+ function once(eventType, callback) {
99
99
  const subscription = subscribe(eventType, (msg) => {
100
100
  subscription.unsubscribe();
101
101
  callback(msg);
102
102
  });
103
103
  return subscription.unsubscribe;
104
104
  }
105
- function waitFor$1(eventType, timeout) {
105
+ function waitFor(eventType, timeout) {
106
106
  return new Promise((resolve, reject) => {
107
107
  let timeoutId = null;
108
- const unsubscribe = once$1(eventType, (msg) => {
108
+ const unsubscribe = once(eventType, (msg) => {
109
109
  if (timeoutId) {
110
110
  clearTimeout(timeoutId);
111
111
  }
@@ -122,288 +122,15 @@ function waitFor$1(eventType, timeout) {
122
122
  const eventBus = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
123
123
  __proto__: null,
124
124
  hasEventSubscriptions,
125
- once: once$1,
125
+ once,
126
126
  publish,
127
127
  reset,
128
128
  subscribe,
129
- waitFor: waitFor$1
130
- }, Symbol.toStringTag, { value: "Module" }));
131
- function once(eventType, callback) {
132
- const subscription = subscribe(eventType, (msg) => {
133
- subscription.unsubscribe();
134
- callback(msg);
135
- });
136
- return subscription.unsubscribe;
137
- }
138
- function waitFor(eventType, timeout) {
139
- return new Promise((resolve, reject) => {
140
- let timeoutId = null;
141
- const unsubscribe = once(eventType, (msg) => {
142
- if (timeoutId) {
143
- clearTimeout(timeoutId);
144
- }
145
- resolve(msg);
146
- });
147
- if (timeout) {
148
- timeoutId = setTimeout(() => {
149
- unsubscribe();
150
- reject(new Error(`Timeout waiting for event: ${eventType}`));
151
- }, timeout);
152
- }
153
- });
154
- }
155
- function waitForAll(eventTypes, timeout) {
156
- const promises = eventTypes.map(
157
- (eventType) => waitFor(eventType, timeout)
158
- );
159
- return Promise.all(promises);
160
- }
161
- function race(eventTypes, timeout) {
162
- return new Promise((resolve, reject) => {
163
- const unsubscribers = [];
164
- let timeoutId = null;
165
- let resolved = false;
166
- const cleanup = () => {
167
- unsubscribers.forEach((unsub) => unsub());
168
- if (timeoutId) {
169
- clearTimeout(timeoutId);
170
- }
171
- };
172
- eventTypes.forEach((eventType) => {
173
- const unsubscribe = once(eventType, (msg) => {
174
- if (!resolved) {
175
- resolved = true;
176
- cleanup();
177
- resolve({ eventType, data: msg });
178
- }
179
- });
180
- unsubscribers.push(unsubscribe);
181
- });
182
- if (timeout) {
183
- timeoutId = setTimeout(() => {
184
- if (!resolved) {
185
- resolved = true;
186
- cleanup();
187
- reject(
188
- new Error(`Timeout waiting for any event: ${eventTypes.join(", ")}`)
189
- );
190
- }
191
- }, timeout);
192
- }
193
- });
194
- }
195
- function filter(eventType, predicate, callback) {
196
- const subscription = subscribe(eventType, (msg) => {
197
- if (msg && predicate(msg)) {
198
- callback(msg);
199
- }
200
- });
201
- return subscription.unsubscribe;
202
- }
203
- function map(eventType, transform, callback) {
204
- const subscription = subscribe(eventType, (msg) => {
205
- if (msg) {
206
- const transformed = transform(msg);
207
- callback(transformed);
208
- }
209
- });
210
- return subscription.unsubscribe;
211
- }
212
- function debounce(eventType, delay2, callback) {
213
- let timeoutId = null;
214
- const subscription = subscribe(eventType, (msg) => {
215
- if (timeoutId) {
216
- clearTimeout(timeoutId);
217
- }
218
- timeoutId = setTimeout(() => {
219
- callback(msg);
220
- }, delay2);
221
- });
222
- return () => {
223
- if (timeoutId) {
224
- clearTimeout(timeoutId);
225
- }
226
- subscription.unsubscribe();
227
- };
228
- }
229
- function throttle(eventType, interval, callback) {
230
- let lastEmit = 0;
231
- let pendingTimeout = null;
232
- const subscription = subscribe(eventType, (msg) => {
233
- const now = Date.now();
234
- const timeSinceLastEmit = now - lastEmit;
235
- if (timeSinceLastEmit >= interval) {
236
- lastEmit = now;
237
- callback(msg);
238
- } else if (!pendingTimeout) {
239
- pendingTimeout = setTimeout(() => {
240
- lastEmit = Date.now();
241
- callback(msg);
242
- pendingTimeout = null;
243
- }, interval - timeSinceLastEmit);
244
- }
245
- });
246
- return () => {
247
- if (pendingTimeout) {
248
- clearTimeout(pendingTimeout);
249
- }
250
- subscription.unsubscribe();
251
- };
252
- }
253
- function buffer(eventType, bufferTime, callback) {
254
- let buffer2 = [];
255
- let timeoutId = null;
256
- const flush = () => {
257
- if (buffer2.length > 0) {
258
- callback([...buffer2]);
259
- buffer2 = [];
260
- }
261
- };
262
- const subscription = subscribe(eventType, (msg) => {
263
- if (msg) {
264
- buffer2.push(msg);
265
- if (!timeoutId) {
266
- timeoutId = setTimeout(() => {
267
- flush();
268
- timeoutId = null;
269
- }, bufferTime);
270
- }
271
- }
272
- });
273
- return () => {
274
- if (timeoutId) {
275
- clearTimeout(timeoutId);
276
- flush();
277
- }
278
- subscription.unsubscribe();
279
- };
280
- }
281
- function replay(eventType, bufferSize = 1) {
282
- const buffer2 = [];
283
- subscribe(eventType, (msg) => {
284
- if (msg) {
285
- buffer2.push(msg);
286
- if (buffer2.length > bufferSize) {
287
- buffer2.shift();
288
- }
289
- }
290
- });
291
- return {
292
- subscribe: (callback) => {
293
- buffer2.forEach((event) => callback(event));
294
- return subscribe(eventType, callback);
295
- }
296
- };
297
- }
298
- function merge(eventTypes, callback) {
299
- const subscriptions2 = eventTypes.map(
300
- (eventType) => subscribe(eventType, (msg) => {
301
- if (msg) {
302
- callback(eventType, msg);
303
- }
304
- })
305
- );
306
- return () => {
307
- subscriptions2.forEach((sub) => sub.unsubscribe());
308
- };
309
- }
310
- function stateMachine(initialState, transitions) {
311
- let currentState = initialState;
312
- const subscriptions2 = [];
313
- const allEvents = /* @__PURE__ */ new Set();
314
- Object.values(transitions).forEach((stateTransitions) => {
315
- Object.keys(stateTransitions).forEach((event) => {
316
- allEvents.add(event);
317
- });
318
- });
319
- allEvents.forEach((eventType) => {
320
- const { unsubscribe } = subscribe(eventType, (msg) => {
321
- const stateTransitions = transitions[currentState];
322
- if (stateTransitions && stateTransitions[eventType]) {
323
- const nextState = stateTransitions[eventType](msg);
324
- currentState = nextState;
325
- }
326
- });
327
- subscriptions2.push(unsubscribe);
328
- });
329
- return {
330
- get state() {
331
- return currentState;
332
- },
333
- unsubscribe: () => {
334
- subscriptions2.forEach((unsub) => unsub());
335
- }
336
- };
337
- }
338
- function request(requestEvent, responseEvent, request2, timeout) {
339
- const responsePromise = waitFor(responseEvent, timeout);
340
- publish(requestEvent, request2);
341
- return responsePromise;
342
- }
343
- async function* eventIterator(eventType) {
344
- const queue = [];
345
- const waiters = [];
346
- const subscription = subscribe(eventType, (msg) => {
347
- if (msg) {
348
- if (waiters.length > 0) {
349
- const waiter = waiters.shift();
350
- waiter(msg);
351
- } else {
352
- queue.push(msg);
353
- }
354
- }
355
- });
356
- try {
357
- while (true) {
358
- if (queue.length > 0) {
359
- yield queue.shift();
360
- } else {
361
- yield await new Promise((resolve) => {
362
- waiters.push(resolve);
363
- });
364
- }
365
- }
366
- } finally {
367
- subscription.unsubscribe();
368
- }
369
- }
370
- const EventBusFunctional = {
371
- once,
372
- waitFor,
373
- waitForAll,
374
- race,
375
- filter,
376
- map,
377
- debounce,
378
- throttle,
379
- buffer,
380
- replay,
381
- merge,
382
- stateMachine,
383
- request,
384
- eventIterator
385
- };
386
- const eventBus_functional = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
387
- __proto__: null,
388
- EventBusFunctional,
389
- buffer,
390
- debounce,
391
- eventIterator,
392
- filter,
393
- map,
394
- merge,
395
- once,
396
- race,
397
- replay,
398
- request,
399
- stateMachine,
400
- throttle,
401
- waitFor,
402
- waitForAll
129
+ waitFor
403
130
  }, Symbol.toStringTag, { value: "Module" }));
404
131
  async function waitForOrGetState(eventType, options) {
405
132
  const { getCurrentState, transformState, shouldUseFetchedState, timeout } = options;
406
- const eventPromise = waitFor$1(eventType, timeout);
133
+ const eventPromise = waitFor(eventType, timeout);
407
134
  const currentState = await getCurrentState();
408
135
  const normalizedState = transformState ? transformState(currentState) : currentState;
409
136
  if (shouldUseFetchedState) {
@@ -522,7 +249,7 @@ async function waitForAllWithState(eventTypesOrType, options) {
522
249
  return normalizedState;
523
250
  }
524
251
  const eventPromises = eventTypes.map(
525
- (eventType) => waitFor$1(eventType, timeout)
252
+ (eventType) => waitFor(eventType, timeout)
526
253
  );
527
254
  const results = await Promise.all(eventPromises);
528
255
  return results[results.length - 1];
@@ -1257,7 +984,7 @@ function resolveServiceRequestParameters(metadata, modelInstance, args, runtimeO
1257
984
  modelId: modelInstance.id,
1258
985
  modelData: modelInstance,
1259
986
  value: {
1260
- ...typeof metadata.pathParams === "function" ? metadata.pathParams(modelInstance) : metadata.pathParams || {},
987
+ ...typeof metadata.pathParams === "function" ? metadata.pathParams(modelInstance, ...args) : metadata.pathParams || {},
1261
988
  ...runtimeOptions?.pathParams || {}
1262
989
  }
1263
990
  });
@@ -1265,11 +992,11 @@ function resolveServiceRequestParameters(metadata, modelInstance, args, runtimeO
1265
992
  modelId: modelInstance.id,
1266
993
  modelData: modelInstance,
1267
994
  value: {
1268
- ...typeof metadata.queryParams === "function" ? metadata.queryParams(modelInstance) : metadata.queryParams || {},
995
+ ...typeof metadata.queryParams === "function" ? metadata.queryParams(modelInstance, ...args) : metadata.queryParams || {},
1269
996
  ...runtimeOptions?.queryParams || {}
1270
997
  }
1271
998
  });
1272
- const finalBody = runtimeOptions?.body || (typeof metadata.body === "function" ? metadata.body(modelInstance) : metadata.body);
999
+ const finalBody = runtimeOptions?.body || (typeof metadata.body === "function" ? metadata.body(modelInstance, ...args) : metadata.body);
1273
1000
  const decoratorRequestOptions = typeof metadata.requestOptions === "function" ? metadata.requestOptions(modelInstance, ...args) : metadata.requestOptions;
1274
1001
  const finalRequestOptions = {
1275
1002
  ...decoratorRequestOptions || {},
@@ -1437,6 +1164,7 @@ function kosStateMachine(config2, options) {
1437
1164
  // Default to READY if not specified
1438
1165
  initializeAt: config2.initializeAt || DependencyLifecycle.READY
1439
1166
  },
1167
+ initializeAtExplicit: config2.initializeAt !== void 0,
1440
1168
  options: {
1441
1169
  stateProperty: options?.stateProperty || "currentState",
1442
1170
  trackHistory: options?.trackHistory || false,
@@ -1471,7 +1199,8 @@ function kosStateGuard(options) {
1471
1199
  if (!isFsmInitialized) {
1472
1200
  return originalMethod.apply(this, args);
1473
1201
  }
1474
- const currentState = this.currentState;
1202
+ const stateProperty = this[StateMachineSetup]?.options?.stateProperty || "currentState";
1203
+ const currentState = this[stateProperty];
1475
1204
  const isAllowed = options.allowedStates.includes(currentState);
1476
1205
  if (!isAllowed) {
1477
1206
  const message = `Method ${String(
@@ -1735,10 +1464,9 @@ const registerExtensionPoint = (id, extensionPoint) => {
1735
1464
  };
1736
1465
  const _ExtensionManager = {
1737
1466
  indexExtension: {
1467
+ // Registrations under one id accumulate; a repeated index key takes the latest mapper.
1738
1468
  registerIndexExtension: (id, extension) => {
1739
- const extensions = indexExtensions.get(id) || {};
1740
- Object.assign(extensions, extension);
1741
- indexExtensions.set(id, extension);
1469
+ indexExtensions.set(id, { ...indexExtensions.get(id), ...extension });
1742
1470
  },
1743
1471
  loadIndexExtensions: (id) => indexExtensions.get(id) || {}
1744
1472
  },
@@ -1878,13 +1606,13 @@ class KosContainerIndex {
1878
1606
  refresh() {
1879
1607
  this.generateIndex();
1880
1608
  }
1881
- addItemToIndex(key, model, map2 = this._map, data = this.data) {
1882
- const currentValue = map2.get(key) || /* @__PURE__ */ new Set();
1609
+ addItemToIndex(key, model, map = this._map, data = this.data) {
1610
+ const currentValue = map.get(key) || /* @__PURE__ */ new Set();
1883
1611
  currentValue.add(model);
1884
- map2.set(key, currentValue);
1612
+ map.set(key, currentValue);
1885
1613
  data[key] = Array.from(currentValue);
1886
1614
  }
1887
- resolveIndex(map2, data) {
1615
+ resolveIndex(map, data) {
1888
1616
  const toRemove = this.data.keys.filter(
1889
1617
  (key) => !Object.keys(data).includes(key)
1890
1618
  );
@@ -1897,7 +1625,7 @@ class KosContainerIndex {
1897
1625
  const existing = this.data[key] || [];
1898
1626
  if (!arraysAreEqual(values, existing)) {
1899
1627
  this.data[key] = values;
1900
- const set = map2.get(key) || /* @__PURE__ */ new Set();
1628
+ const set = map.get(key) || /* @__PURE__ */ new Set();
1901
1629
  this._map.set(key, set);
1902
1630
  } else {
1903
1631
  KosLog.debug(`KosContainerIndex - Index ${key} is the same`);
@@ -2974,6 +2702,7 @@ class SingletonKosModelRegistrationFactory extends KosBaseModelRegistration {
2974
2702
  }
2975
2703
  }
2976
2704
  const log$j = KosLog.createLogger({ group: "decorators", name: "kos-model" });
2705
+ const FUTURE_CANCEL_END_STATE = "CANCEL";
2977
2706
  function resolveParentContext(TargetClass, modelId, modelData) {
2978
2707
  const parentIdRaw = TargetClass[ParentModel]?.parentId;
2979
2708
  if (!parentIdRaw) return;
@@ -2993,6 +2722,19 @@ function injectFutureServices(modelInstance) {
2993
2722
  modelInstance[key] = handler;
2994
2723
  });
2995
2724
  }
2725
+ function resolveDependencyAtConstruction(dependency, resolvedId, options) {
2726
+ const modelManager = KosCore.getInstance().modelManager;
2727
+ const resolutionPolicy = dependency.resolutionPolicy || DependencyResolutionPolicy.CREATE;
2728
+ if (resolutionPolicy === DependencyResolutionPolicy.CREATE) {
2729
+ return modelManager.createModelInstance(
2730
+ dependency.modelType,
2731
+ resolvedId,
2732
+ options
2733
+ ).data;
2734
+ }
2735
+ const existing = modelManager.getModelById(resolvedId);
2736
+ return existing?.modelTypeName === dependency.modelType ? existing.modelData : void 0;
2737
+ }
2996
2738
  function injectDependencies(modelInstance, modelId) {
2997
2739
  const dependencies = modelInstance[DependencyModels] || {};
2998
2740
  Object.entries(dependencies).forEach(([key, dependency]) => {
@@ -3014,12 +2756,11 @@ function injectDependencies(modelInstance, modelId) {
3014
2756
  );
3015
2757
  if (typeof resolvedId === "string") {
3016
2758
  if (!dependency.lazy) {
3017
- const model = KosCore.getInstance().modelManager.createModelInstance(
3018
- dependency.modelType,
2759
+ modelInstance[key] = resolveDependencyAtConstruction(
2760
+ dependency,
3019
2761
  resolvedId,
3020
2762
  options
3021
2763
  );
3022
- modelInstance[key] = model.data;
3023
2764
  }
3024
2765
  KosCore.getInstance().modelManager.addDependency(modelId, resolvedId);
3025
2766
  }
@@ -3063,7 +2804,7 @@ function injectFutureContainerSupport(modelInstance) {
3063
2804
  });
3064
2805
  Object.defineProperty(modelInstance, "isCancelled", {
3065
2806
  get() {
3066
- return futureHandler.future?.status === "CANCELLED" || false;
2807
+ return futureHandler.future?.status === FUTURE_CANCEL_END_STATE;
3067
2808
  },
3068
2809
  enumerable: true,
3069
2810
  configurable: true
@@ -3081,14 +2822,6 @@ function injectMultipleFutureContainerSupport(modelInstance) {
3081
2822
  const { mode, handlerProperty } = setup;
3082
2823
  const futureHandler = new MultipleFutureHandler(modelInstance);
3083
2824
  modelInstance[handlerProperty] = futureHandler;
3084
- Object.defineProperty(modelInstance, "future", {
3085
- get() {
3086
- return futureHandler.future;
3087
- },
3088
- enumerable: true,
3089
- configurable: true
3090
- // Allow MobX to make this observable
3091
- });
3092
2825
  const aliases = modelInstance[FutureAliases];
3093
2826
  if (aliases instanceof Map) {
3094
2827
  aliases.forEach((alias) => {
@@ -3128,7 +2861,7 @@ function injectMultipleFutureContainerSupport(modelInstance) {
3128
2861
  Object.defineProperty(modelInstance, `${alias}IsCancelled`, {
3129
2862
  get() {
3130
2863
  const future = futureHandler.futureMap.get(alias);
3131
- return future?.status === "CANCELLED" || false;
2864
+ return future?.status === FUTURE_CANCEL_END_STATE;
3132
2865
  },
3133
2866
  enumerable: true,
3134
2867
  configurable: true
@@ -3142,41 +2875,6 @@ function injectMultipleFutureContainerSupport(modelInstance) {
3142
2875
  }
3143
2876
  });
3144
2877
  }
3145
- if (mode === "full") {
3146
- Object.defineProperty(modelInstance, "progress", {
3147
- get() {
3148
- return futureHandler.future?.progress || 0;
3149
- },
3150
- enumerable: true,
3151
- configurable: true
3152
- });
3153
- Object.defineProperty(modelInstance, "status", {
3154
- get() {
3155
- return futureHandler.future?.status || "IDLE";
3156
- },
3157
- enumerable: true,
3158
- configurable: true
3159
- });
3160
- Object.defineProperty(modelInstance, "isRunning", {
3161
- get() {
3162
- return futureHandler.future ? !futureHandler.future.endState : false;
3163
- },
3164
- enumerable: true,
3165
- configurable: true
3166
- });
3167
- Object.defineProperty(modelInstance, "isCancelled", {
3168
- get() {
3169
- return futureHandler.future?.status === "CANCELLED" || false;
3170
- },
3171
- enumerable: true,
3172
- configurable: true
3173
- });
3174
- modelInstance.cancelFuture = async () => {
3175
- if (futureHandler.future) {
3176
- await futureHandler.future.cancelFuture();
3177
- }
3178
- };
3179
- }
3180
2878
  }
3181
2879
  function injectTroubleAwareSupport(modelInstance) {
3182
2880
  const troubleSetup = modelInstance[TroubleAwareSetup];
@@ -3470,9 +3168,6 @@ function kosTopicHandler(params2) {
3470
3168
  return (target, _propertyKey, descriptor) => {
3471
3169
  const configuration = prepareHandlerConfiguration(params2, descriptor);
3472
3170
  registerTopicHandlers(target, params2.topic, configuration);
3473
- if (params2.replay) {
3474
- configureReplayBehavior(params2.topic, params2.replay.bufferSize);
3475
- }
3476
3171
  };
3477
3172
  }
3478
3173
  function prepareHandlerConfiguration(params2, descriptor) {
@@ -3486,10 +3181,10 @@ function prepareHandlerConfiguration(params2, descriptor) {
3486
3181
  lifecycle,
3487
3182
  destinationAddress,
3488
3183
  explicitDestination = false,
3489
- debounce: debounce2,
3490
- throttle: throttle2,
3491
- buffer: buffer2,
3492
- filter: filter2,
3184
+ debounce,
3185
+ throttle,
3186
+ buffer,
3187
+ filter,
3493
3188
  once: once2,
3494
3189
  wildcardName,
3495
3190
  flow,
@@ -3497,12 +3192,12 @@ function prepareHandlerConfiguration(params2, descriptor) {
3497
3192
  } = params2;
3498
3193
  const originalHandler = descriptor.value;
3499
3194
  const enhancedHandler = applyFunctionalEnhancements(originalHandler, {
3500
- debounce: debounce2,
3501
- throttle: throttle2,
3502
- buffer: buffer2,
3195
+ debounce,
3196
+ throttle,
3197
+ buffer,
3503
3198
  once: once2
3504
3199
  });
3505
- const enhancedCondition = combineFilterWithCondition(filter2, condition);
3200
+ const enhancedCondition = combineFilterWithCondition(filter, condition);
3506
3201
  return {
3507
3202
  websocket,
3508
3203
  fos,
@@ -3550,12 +3245,12 @@ function applyFunctionalEnhancements(handler, enhancements) {
3550
3245
  }
3551
3246
  return enhancedHandler;
3552
3247
  }
3553
- function combineFilterWithCondition(filter2, condition) {
3554
- if (!filter2) {
3248
+ function combineFilterWithCondition(filter, condition) {
3249
+ if (!filter) {
3555
3250
  return condition;
3556
3251
  }
3557
3252
  return (payload, model, raw) => {
3558
- if (!filter2(raw)) {
3253
+ if (!filter(raw)) {
3559
3254
  return false;
3560
3255
  }
3561
3256
  return condition(payload, model, raw);
@@ -3571,9 +3266,6 @@ function registerTopicHandlers(target, topic, handlerConfig) {
3571
3266
  target[SubscriptionHandlers][topic] = handlerConfig;
3572
3267
  }
3573
3268
  }
3574
- function configureReplayBehavior(topic, bufferSize) {
3575
- setupReplayHandler(topic, bufferSize);
3576
- }
3577
3269
  function createDebouncedHandler(originalHandler, config2) {
3578
3270
  const delay2 = typeof config2 === "number" ? config2 : config2.delay;
3579
3271
  const strategy = determineDebounceStrategy(config2);
@@ -3657,18 +3349,18 @@ function createThrottledHandler(originalHandler, config2) {
3657
3349
  };
3658
3350
  }
3659
3351
  function createBufferedHandler(originalHandler, bufferConfig) {
3660
- const buffer2 = [];
3352
+ const buffer = [];
3661
3353
  let timeoutId = null;
3662
3354
  const maxSize = bufferConfig.maxSize || 1e3;
3663
3355
  const flush = (context) => {
3664
- if (buffer2.length > 0) {
3665
- originalHandler.call(context, [...buffer2]);
3666
- buffer2.length = 0;
3356
+ if (buffer.length > 0) {
3357
+ originalHandler.call(context, [...buffer]);
3358
+ buffer.length = 0;
3667
3359
  }
3668
3360
  };
3669
3361
  return function(payload) {
3670
- buffer2.push(payload);
3671
- if (buffer2.length >= maxSize) {
3362
+ buffer.push(payload);
3363
+ if (buffer.length >= maxSize) {
3672
3364
  if (timeoutId) {
3673
3365
  clearTimeout(timeoutId);
3674
3366
  timeoutId = null;
@@ -3693,12 +3385,6 @@ function createOnceHandler(originalHandler) {
3693
3385
  }
3694
3386
  };
3695
3387
  }
3696
- function setupReplayHandler(topic, bufferSize) {
3697
- const topics = Array.isArray(topic) ? topic : [topic];
3698
- topics.forEach((t) => {
3699
- replay(t, bufferSize);
3700
- });
3701
- }
3702
3388
  const isPrintable = (model) => typeof model.toJSON === "function";
3703
3389
  const isKosDataModel = (model) => model[DependencyModels] !== void 0;
3704
3390
  const isKosModelContainer = (model) => model.revision !== void 0 && model.index !== void 0;
@@ -4289,6 +3975,21 @@ const createModelDependency = (model, dependency) => {
4289
3975
  );
4290
3976
  return { dependentModel: null, dataModelId, success: false };
4291
3977
  }
3978
+ if (resolutionPolicy === DependencyResolutionPolicy.FAIL) {
3979
+ const errorMessage = `No ${dependency.modelType} model with id ${dataModelId} exists`;
3980
+ KosLog.error(
3981
+ `Failed to resolve dependency for model ${model.modelId}:
3982
+ - Dependency Type: ${dependency.modelType}
3983
+ - Dependency ID: ${dataModelId}
3984
+ - Resolution Policy: ${resolutionPolicy}
3985
+ - Parent Model: ${model.modelTypeName}
3986
+ - Parent Model ID: ${model.modelId}
3987
+ - Error: ${errorMessage}`
3988
+ );
3989
+ throw new Error(
3990
+ `Dependency resolution failed (policy: FAIL) - Model ${model.modelId} cannot resolve dependency ${dependency.modelType} [${dataModelId}]: ${errorMessage}`
3991
+ );
3992
+ }
4292
3993
  const hasOptions = Object.keys(options).length > 0;
4293
3994
  const modelClass = modelRegistry.class || modelRegistry.create;
4294
3995
  const requiresOptions = modelClass?.prototype?.[OptionsRequired] === true;
@@ -4331,11 +4032,6 @@ const createModelDependency = (model, dependency) => {
4331
4032
  - Provided Options: ${JSON.stringify(options, null, 2)}
4332
4033
  - Error: ${errorMessage}`
4333
4034
  );
4334
- if (resolutionPolicy === DependencyResolutionPolicy.FAIL) {
4335
- throw new Error(
4336
- `Dependency resolution failed (policy: FAIL) - Model ${model.modelId} cannot resolve dependency ${dependency.modelType} [${dataModelId}]: ${errorMessage}`
4337
- );
4338
- }
4339
4035
  throw error;
4340
4036
  }
4341
4037
  };
@@ -5500,8 +5196,8 @@ function uuid() {
5500
5196
  return v.toString(16);
5501
5197
  });
5502
5198
  }
5503
- function arrayBufferToBase64(buffer2) {
5504
- const bytes = new Uint8Array(buffer2);
5199
+ function arrayBufferToBase64(buffer) {
5200
+ const bytes = new Uint8Array(buffer);
5505
5201
  let binary = "";
5506
5202
  for (let i = 0; i < bytes.byteLength; i++) {
5507
5203
  binary += String.fromCharCode(bytes[i]);
@@ -5519,8 +5215,8 @@ function base64ToArrayBuffer(base64) {
5519
5215
  async function blobToArrayBuffer(blob) {
5520
5216
  return await blob.arrayBuffer();
5521
5217
  }
5522
- function arrayBufferToBlob(buffer2, type) {
5523
- return new Blob([buffer2], { type });
5218
+ function arrayBufferToBlob(buffer, type) {
5219
+ return new Blob([buffer], { type });
5524
5220
  }
5525
5221
  async function serializeFormData(formData) {
5526
5222
  const fields = {};
@@ -5531,12 +5227,12 @@ async function serializeFormData(formData) {
5531
5227
  });
5532
5228
  for (const [key, value] of entries) {
5533
5229
  if (value instanceof File) {
5534
- const buffer2 = await value.arrayBuffer();
5230
+ const buffer = await value.arrayBuffer();
5535
5231
  files.push({
5536
5232
  name: key,
5537
5233
  filename: value.name,
5538
5234
  type: value.type,
5539
- data: arrayBufferToBase64(buffer2)
5235
+ data: arrayBufferToBase64(buffer)
5540
5236
  });
5541
5237
  } else {
5542
5238
  fields[key] = value.toString();
@@ -5563,23 +5259,23 @@ async function processRequestBody(body) {
5563
5259
  return { data: body, contentType: "text/plain" };
5564
5260
  }
5565
5261
  if (body instanceof ArrayBuffer || body instanceof Uint8Array) {
5566
- let buffer2;
5262
+ let buffer;
5567
5263
  if (body instanceof Uint8Array) {
5568
- buffer2 = new ArrayBuffer(body.byteLength);
5569
- new Uint8Array(buffer2).set(body);
5264
+ buffer = new ArrayBuffer(body.byteLength);
5265
+ new Uint8Array(buffer).set(body);
5570
5266
  } else {
5571
- buffer2 = body;
5267
+ buffer = body;
5572
5268
  }
5573
5269
  return {
5574
- data: arrayBufferToBase64(buffer2),
5270
+ data: arrayBufferToBase64(buffer),
5575
5271
  contentType: "application/octet-stream",
5576
5272
  encoding: "base64"
5577
5273
  };
5578
5274
  }
5579
5275
  if (body instanceof Blob) {
5580
- const buffer2 = await blobToArrayBuffer(body);
5276
+ const buffer = await blobToArrayBuffer(body);
5581
5277
  return {
5582
- data: arrayBufferToBase64(buffer2),
5278
+ data: arrayBufferToBase64(buffer),
5583
5279
  contentType: body.type || "application/octet-stream",
5584
5280
  encoding: "base64"
5585
5281
  };
@@ -6471,8 +6167,11 @@ class ServiceRequestManager {
6471
6167
  model;
6472
6168
  responseStore;
6473
6169
  handlers;
6474
- constructor(model, responseStore) {
6170
+ /** Topic handlers waiting on a baseline live on the KosModel, not the data model. */
6171
+ baselineListener;
6172
+ constructor(model, responseStore, baselineListener) {
6475
6173
  this.model = model;
6174
+ this.baselineListener = baselineListener;
6476
6175
  this.responseStore = responseStore;
6477
6176
  this.handlers = /* @__PURE__ */ new Map();
6478
6177
  this.discoverHandlers();
@@ -6515,15 +6214,25 @@ class ServiceRequestManager {
6515
6214
  * Zone 1: Orchestrates the entire service request flow
6516
6215
  */
6517
6216
  async executeHandler(metadata) {
6217
+ let failure;
6518
6218
  try {
6519
6219
  if (!this.shouldProcessRequest(metadata)) {
6520
6220
  return;
6521
6221
  }
6522
6222
  const requestContext = await this.prepareAndExecuteRequest(metadata);
6523
- await this.processAndStoreResponse(requestContext, metadata);
6223
+ if (requestContext.error) {
6224
+ failure = {
6225
+ error: new Error(requestContext.error),
6226
+ errorContext: requestContext.errorContext
6227
+ };
6228
+ } else {
6229
+ await this.processAndStoreResponse(requestContext, metadata);
6230
+ }
6524
6231
  } catch (err) {
6525
- const error = err instanceof Error ? err : new Error(String(err));
6526
- await this.handleError(error, metadata);
6232
+ failure = { error: err instanceof Error ? err : new Error(String(err)) };
6233
+ }
6234
+ if (failure) {
6235
+ await this.handleError(failure.error, metadata, failure.errorContext);
6527
6236
  }
6528
6237
  }
6529
6238
  /**
@@ -6571,14 +6280,6 @@ class ServiceRequestManager {
6571
6280
  * Zone 2: Coordinates response processing and storage
6572
6281
  */
6573
6282
  async processAndStoreResponse(context, metadata) {
6574
- if (context.error) {
6575
- await this.handleError(
6576
- new Error(context.error),
6577
- metadata,
6578
- context.errorContext
6579
- );
6580
- return;
6581
- }
6582
6283
  const transformedData = await this.processResponse(
6583
6284
  context.response,
6584
6285
  metadata
@@ -6671,11 +6372,7 @@ class ServiceRequestManager {
6671
6372
  * @private
6672
6373
  */
6673
6374
  triggerBaselineQueueFlush(baselinePath) {
6674
- const subscriptionManager = this.model.subscriptionManager;
6675
- if (!subscriptionManager || !subscriptionManager.flushQueueForBaseline) {
6676
- return;
6677
- }
6678
- subscriptionManager.flushQueueForBaseline(baselinePath);
6375
+ this.baselineListener?.flushQueueForBaseline(baselinePath);
6679
6376
  }
6680
6377
  /**
6681
6378
  * Make HTTP request using existing KOS API client
@@ -6808,7 +6505,7 @@ class ServiceRequestManager {
6808
6505
  );
6809
6506
  if (errorHandler.defaultValue !== void 0) {
6810
6507
  const storageKey = createStorageKey(
6811
- metadata.path,
6508
+ resolvePathFromMetadata(metadata, this.model),
6812
6509
  metadata.method || "get"
6813
6510
  );
6814
6511
  this.responseStore.set(
@@ -6826,7 +6523,7 @@ class ServiceRequestManager {
6826
6523
  case "ignore":
6827
6524
  if (errorHandler.defaultValue !== void 0) {
6828
6525
  const storageKey = createStorageKey(
6829
- metadata.path,
6526
+ resolvePathFromMetadata(metadata, this.model),
6830
6527
  metadata.method || "get"
6831
6528
  );
6832
6529
  this.responseStore.set(
@@ -6844,7 +6541,7 @@ class ServiceRequestManager {
6844
6541
  case "default":
6845
6542
  if (errorHandler.defaultValue !== void 0) {
6846
6543
  const storageKey = createStorageKey(
6847
- metadata.path,
6544
+ resolvePathFromMetadata(metadata, this.model),
6848
6545
  metadata.method || "get"
6849
6546
  );
6850
6547
  this.responseStore.set(
@@ -6931,8 +6628,6 @@ class FlowControlManager {
6931
6628
  config;
6932
6629
  stats;
6933
6630
  filterHistory = [];
6934
- activePromises = /* @__PURE__ */ new Set();
6935
- eventQueue = [];
6936
6631
  rateLimitWindow = /* @__PURE__ */ new Map();
6937
6632
  constructor(config2) {
6938
6633
  this.config = config2;
@@ -6940,7 +6635,6 @@ class FlowControlManager {
6940
6635
  eventsReceived: 0,
6941
6636
  batchesProcessed: 0,
6942
6637
  eventsDropped: 0,
6943
- currentQueueSize: 0,
6944
6638
  averageBatchSize: 0,
6945
6639
  processingRate: 0,
6946
6640
  lastProcessedAt: Date.now()
@@ -6961,86 +6655,89 @@ class FlowControlManager {
6961
6655
  if (this.config.filter && !this.shouldProcessEvent(event)) {
6962
6656
  return;
6963
6657
  }
6964
- if (this.config.rateLimit && !this.checkRateLimit()) {
6965
- if (this.config.rateLimit.onExceeded === "drop") {
6966
- this.stats.eventsDropped++;
6967
- return;
6968
- } else if (this.config.rateLimit.onExceeded === "delay") {
6969
- await this.waitForRateLimit();
6970
- }
6971
- }
6972
- if (this.config.backpressure) {
6973
- this.enqueueEvent(event);
6974
- await this.waitForCapacity();
6975
- const queuedEvent = this.dequeueEvent();
6976
- if (queuedEvent) {
6977
- const transformed = this.config.transform ? this.config.transform([queuedEvent]) : [queuedEvent];
6978
- yield transformed;
6979
- this.updateProcessingStats([queuedEvent]);
6980
- }
6981
- } else {
6982
- const transformed = this.config.transform ? this.config.transform([event]) : [event];
6983
- yield transformed;
6984
- this.updateProcessingStats([event]);
6658
+ if (!await this.admitRateLimited()) {
6659
+ return;
6985
6660
  }
6661
+ const transformed = this.config.transform ? this.config.transform([event]) : [event];
6662
+ yield transformed;
6663
+ this.updateProcessingStats([event]);
6986
6664
  }
6665
+ /**
6666
+ * Collects admitted events into batches. A batch is delivered when it
6667
+ * reaches `size`, when `window` ms have passed since its first event, or
6668
+ * when the stream ends. The window timer is cleared on every flush and when
6669
+ * the generator finishes or is returned.
6670
+ */
6987
6671
  async *processBatchedEvents(eventStream, batchConfig) {
6988
6672
  const maxSize = batchConfig.size || 100;
6989
6673
  const maxWait = batchConfig.window || 1e3;
6674
+ const iterator = eventStream[Symbol.asyncIterator]();
6990
6675
  let batch = [];
6991
- let lastFlush = Date.now();
6992
- const flushBatch = async () => {
6993
- if (batch.length === 0) return void 0;
6994
- const currentBatch = [...batch];
6676
+ let windowTimer;
6677
+ let windowElapsed;
6678
+ let elapsed = false;
6679
+ let pending;
6680
+ let sourceDone = false;
6681
+ const openWindow = () => {
6682
+ windowElapsed = new Promise((resolve) => {
6683
+ windowTimer = setTimeout(() => {
6684
+ elapsed = true;
6685
+ resolve("window");
6686
+ }, maxWait);
6687
+ });
6688
+ };
6689
+ const closeWindow = () => {
6690
+ clearTimeout(windowTimer);
6691
+ windowTimer = void 0;
6692
+ windowElapsed = void 0;
6693
+ elapsed = false;
6694
+ };
6695
+ const flushBatch = () => {
6696
+ const currentBatch = batch;
6995
6697
  batch = [];
6996
- lastFlush = Date.now();
6997
- const filteredBatch = this.config.filter ? currentBatch.filter((event) => this.shouldProcessEvent(event)) : currentBatch;
6998
- if (filteredBatch.length === 0) return void 0;
6999
- if (this.config.backpressure) {
7000
- await this.waitForCapacity();
7001
- }
7002
- const transformed = this.config.transform ? this.config.transform(filteredBatch) : filteredBatch;
6698
+ closeWindow();
6699
+ const transformed = this.config.transform ? this.config.transform(currentBatch) : currentBatch;
7003
6700
  this.stats.batchesProcessed++;
7004
- this.updateProcessingStats(filteredBatch);
6701
+ this.updateProcessingStats(currentBatch);
7005
6702
  return transformed;
7006
6703
  };
7007
6704
  try {
7008
- for await (const event of eventStream) {
6705
+ while (true) {
6706
+ pending ??= iterator.next();
6707
+ const next = windowElapsed ? await Promise.race([pending, windowElapsed]) : await pending;
6708
+ if (next === "window") {
6709
+ yield flushBatch();
6710
+ continue;
6711
+ }
6712
+ pending = void 0;
6713
+ if (next.done) {
6714
+ sourceDone = true;
6715
+ break;
6716
+ }
6717
+ const event = next.value;
7009
6718
  this.stats.eventsReceived++;
7010
- if (this.config.backpressure) {
7011
- this.enqueueEvent(event);
7012
- while (this.eventQueue.length > 0) {
7013
- const queuedEvent = this.dequeueEvent();
7014
- if (queuedEvent) {
7015
- batch.push(queuedEvent);
7016
- }
7017
- const now = Date.now();
7018
- const timeSinceLastFlush = now - lastFlush;
7019
- if (batch.length >= maxSize || timeSinceLastFlush >= maxWait) {
7020
- const flushed2 = await flushBatch();
7021
- if (flushed2 !== void 0) {
7022
- yield flushed2;
7023
- }
7024
- break;
7025
- }
7026
- }
7027
- } else {
7028
- batch.push(event);
7029
- const now = Date.now();
7030
- const timeSinceLastFlush = now - lastFlush;
7031
- if (batch.length >= maxSize || timeSinceLastFlush >= maxWait) {
7032
- const flushed2 = await flushBatch();
7033
- if (flushed2 !== void 0) {
7034
- yield flushed2;
7035
- }
7036
- }
6719
+ if (this.config.filter && !this.shouldProcessEvent(event)) {
6720
+ continue;
6721
+ }
6722
+ if (!await this.admitRateLimited()) {
6723
+ continue;
6724
+ }
6725
+ batch.push(event);
6726
+ if (batch.length === 1) {
6727
+ openWindow();
6728
+ }
6729
+ if (batch.length >= maxSize || elapsed) {
6730
+ yield flushBatch();
7037
6731
  }
7038
6732
  }
7039
- const flushed = await flushBatch();
7040
- if (flushed !== void 0) {
7041
- yield flushed;
6733
+ if (batch.length > 0) {
6734
+ yield flushBatch();
7042
6735
  }
7043
6736
  } finally {
6737
+ closeWindow();
6738
+ if (!sourceDone) {
6739
+ void iterator.return?.();
6740
+ }
7044
6741
  }
7045
6742
  }
7046
6743
  shouldProcessEvent(event) {
@@ -7059,6 +6756,23 @@ class FlowControlManager {
7059
6756
  }
7060
6757
  return shouldProcess;
7061
6758
  }
6759
+ /**
6760
+ * Counts an event against the rate limit. Resolves false when the event is
6761
+ * dropped; with `onExceeded: "delay"` it waits for a window with room and
6762
+ * counts the event there.
6763
+ */
6764
+ async admitRateLimited() {
6765
+ const rateLimit = this.config.rateLimit;
6766
+ if (!rateLimit) return true;
6767
+ while (!this.checkRateLimit()) {
6768
+ if (rateLimit.onExceeded !== "delay") {
6769
+ this.stats.eventsDropped++;
6770
+ return false;
6771
+ }
6772
+ await this.waitForRateLimit();
6773
+ }
6774
+ return true;
6775
+ }
7062
6776
  checkRateLimit() {
7063
6777
  if (!this.config.rateLimit) return true;
7064
6778
  const now = Date.now();
@@ -7085,70 +6799,12 @@ class FlowControlManager {
7085
6799
  await new Promise((resolve) => setTimeout(resolve, waitTime));
7086
6800
  }
7087
6801
  }
7088
- async waitForCapacity() {
7089
- if (!this.config.backpressure) return;
7090
- const maxConcurrent = this.config.backpressure.maxConcurrent || 5;
7091
- const maxQueue = this.config.backpressure.maxQueue || 1e3;
7092
- while (this.activePromises.size >= maxConcurrent) {
7093
- await Promise.race(this.activePromises);
7094
- }
7095
- if (this.eventQueue.length >= maxQueue) {
7096
- this.handleQueueOverflow();
7097
- }
7098
- }
7099
- handleQueueOverflow() {
7100
- if (!this.config.backpressure) return;
7101
- const maxQueue = this.config.backpressure.maxQueue || 1e3;
7102
- const dropPolicy = this.config.backpressure.dropPolicy || "oldest";
7103
- const onQueueFull = this.config.backpressure.onQueueFull;
7104
- if (dropPolicy === "none") {
7105
- return;
7106
- }
7107
- const overflow = this.eventQueue.length - maxQueue;
7108
- if (overflow <= 0) return;
7109
- let droppedEvents = [];
7110
- if (dropPolicy === "oldest") {
7111
- droppedEvents = this.eventQueue.splice(0, overflow);
7112
- } else if (dropPolicy === "newest") {
7113
- droppedEvents = this.eventQueue.splice(-overflow);
7114
- }
7115
- this.stats.eventsDropped += droppedEvents.length;
7116
- this.stats.currentQueueSize = this.eventQueue.length;
7117
- if (onQueueFull && droppedEvents.length > 0) {
7118
- try {
7119
- onQueueFull(droppedEvents);
7120
- } catch (error) {
7121
- console.warn("Error in onQueueFull callback:", error);
7122
- }
7123
- }
7124
- }
7125
- enqueueEvent(event) {
7126
- this.eventQueue.push(event);
7127
- this.stats.currentQueueSize = this.eventQueue.length;
7128
- if (this.config.backpressure) {
7129
- const maxQueue = this.config.backpressure.maxQueue || 1e3;
7130
- if (this.eventQueue.length > maxQueue) {
7131
- this.handleQueueOverflow();
7132
- }
7133
- }
7134
- }
7135
- dequeueEvent() {
7136
- const event = this.eventQueue.shift();
7137
- this.stats.currentQueueSize = this.eventQueue.length;
7138
- return event;
7139
- }
7140
6802
  updateProcessingStats(batch) {
7141
6803
  const now = Date.now();
7142
6804
  const timeSinceLastProcessed = now - this.stats.lastProcessedAt;
7143
6805
  this.stats.averageBatchSize = (this.stats.averageBatchSize * this.stats.batchesProcessed + batch.length) / (this.stats.batchesProcessed + 1);
7144
6806
  this.stats.processingRate = timeSinceLastProcessed > 0 ? batch.length / (timeSinceLastProcessed / 1e3) : this.stats.processingRate;
7145
6807
  this.stats.lastProcessedAt = now;
7146
- this.stats.currentQueueSize = this.eventQueue.length;
7147
- }
7148
- trackPromise(promise) {
7149
- this.activePromises.add(promise);
7150
- promise.finally(() => this.activePromises.delete(promise));
7151
- return promise;
7152
6808
  }
7153
6809
  getStats() {
7154
6810
  return { ...this.stats };
@@ -7470,24 +7126,24 @@ const summarize = (name, fixture) => {
7470
7126
  };
7471
7127
  };
7472
7128
  const openDb = () => new Promise((resolve, reject) => {
7473
- const request2 = indexedDB.open(DB_NAME, 1);
7474
- request2.onupgradeneeded = () => {
7475
- if (!request2.result.objectStoreNames.contains(STORE_NAME)) {
7476
- request2.result.createObjectStore(STORE_NAME);
7129
+ const request = indexedDB.open(DB_NAME, 1);
7130
+ request.onupgradeneeded = () => {
7131
+ if (!request.result.objectStoreNames.contains(STORE_NAME)) {
7132
+ request.result.createObjectStore(STORE_NAME);
7477
7133
  }
7478
7134
  };
7479
- request2.onsuccess = () => resolve(request2.result);
7480
- request2.onerror = () => reject(request2.error);
7135
+ request.onsuccess = () => resolve(request.result);
7136
+ request.onerror = () => reject(request.error);
7481
7137
  });
7482
7138
  const withStore = async (mode, operation) => {
7483
7139
  const db = await openDb();
7484
7140
  try {
7485
7141
  return await new Promise((resolve, reject) => {
7486
- const request2 = operation(
7142
+ const request = operation(
7487
7143
  db.transaction(STORE_NAME, mode).objectStore(STORE_NAME)
7488
7144
  );
7489
- request2.onsuccess = () => resolve(request2.result);
7490
- request2.onerror = () => reject(request2.error);
7145
+ request.onsuccess = () => resolve(request.result);
7146
+ request.onerror = () => reject(request.error);
7491
7147
  });
7492
7148
  } finally {
7493
7149
  db.close();
@@ -8042,17 +7698,17 @@ class KosMockRecorder {
8042
7698
  }
8043
7699
  const responseId = headers["response-id"];
8044
7700
  if (responseId) {
8045
- const request2 = this.pending.get(responseId);
8046
- if (!request2) {
7701
+ const request = this.pending.get(responseId);
7702
+ if (!request) {
8047
7703
  return;
8048
7704
  }
8049
7705
  this.pending.delete(responseId);
8050
7706
  this.exchanges.push({
8051
- ...request2,
7707
+ ...request,
8052
7708
  status: parseInt(headers["status"] ?? "200", 10) || 200,
8053
7709
  responseBody: body ?? "",
8054
7710
  responseHeaders: headers,
8055
- latencyMs: Math.max(0, this.elapsed() - request2.tMs),
7711
+ latencyMs: Math.max(0, this.elapsed() - request.tMs),
8056
7712
  ...headers[KOS_MOCKED_HEADER] === "true" ? { mocked: true } : {}
8057
7713
  });
8058
7714
  return;
@@ -8340,13 +7996,13 @@ class KosMockRegistry {
8340
7996
  if (!responseId) {
8341
7997
  return frame;
8342
7998
  }
8343
- const request2 = this.pendingRequests.get(responseId);
7999
+ const request = this.pendingRequests.get(responseId);
8344
8000
  this.pendingRequests.delete(responseId);
8345
- if (!request2) {
8001
+ if (!request) {
8346
8002
  return frame;
8347
8003
  }
8348
8004
  const matching = this.transformers.filter(
8349
- (transformer) => methodMatches(transformer.method, request2.method) && matchRoutePattern(transformer.compiled, request2.path) !== void 0
8005
+ (transformer) => methodMatches(transformer.method, request.method) && matchRoutePattern(transformer.compiled, request.path) !== void 0
8350
8006
  );
8351
8007
  if (matching.length === 0) {
8352
8008
  return frame;
@@ -8358,7 +8014,7 @@ class KosMockRegistry {
8358
8014
  return frame;
8359
8015
  }
8360
8016
  const info = {
8361
- request: request2,
8017
+ request,
8362
8018
  headers,
8363
8019
  status: parseInt(headers["status"] ?? "200", 10) || 200,
8364
8020
  mocked: headers[KOS_MOCKED_HEADER] === "true"
@@ -8745,7 +8401,7 @@ class KosMockRegistry {
8745
8401
  }
8746
8402
  return false;
8747
8403
  }
8748
- const request2 = {
8404
+ const request = {
8749
8405
  method: frame.method,
8750
8406
  url: frame.url,
8751
8407
  path,
@@ -8766,12 +8422,12 @@ class KosMockRegistry {
8766
8422
  }
8767
8423
  }
8768
8424
  };
8769
- void this.resolve(request2, candidates, io, policy);
8425
+ void this.resolve(request, candidates, io, policy);
8770
8426
  return true;
8771
8427
  }
8772
- async resolve(request2, candidates, io, policy) {
8428
+ async resolve(request, candidates, io, policy) {
8773
8429
  for (const { route, params: params2 } of candidates) {
8774
- const scopedRequest = { ...request2, params: params2 };
8430
+ const scopedRequest = { ...request, params: params2 };
8775
8431
  if (route.when) {
8776
8432
  let accepted = false;
8777
8433
  try {
@@ -8810,21 +8466,21 @@ class KosMockRegistry {
8810
8466
  if (route.once) {
8811
8467
  this.removeRoute(route.id);
8812
8468
  }
8813
- this.deliverResponse(io, request2.requestId, response, route);
8469
+ this.deliverResponse(io, request.requestId, response, route);
8814
8470
  return;
8815
8471
  }
8816
8472
  if (policy === "respond404") {
8817
- this.deliverResponse(io, request2.requestId, {
8473
+ this.deliverResponse(io, request.requestId, {
8818
8474
  status: 404,
8819
8475
  data: {
8820
- message: `KosMock: all routes declined ${request2.method} ${request2.path}`
8476
+ message: `KosMock: all routes declined ${request.method} ${request.path}`
8821
8477
  }
8822
8478
  });
8823
8479
  return;
8824
8480
  }
8825
8481
  if (policy === "warn") {
8826
8482
  KosLog.warn(
8827
- `KosMock: all routes declined ${request2.method} ${request2.path}`
8483
+ `KosMock: all routes declined ${request.method} ${request.path}`
8828
8484
  );
8829
8485
  }
8830
8486
  io.forward();
@@ -10051,10 +9707,10 @@ class KosSubscriptionManager {
10051
9707
  async startFlowProcessing(config2, resolvedTopic, handler, flowManager) {
10052
9708
  const controller = new AbortController();
10053
9709
  try {
10054
- let eventSource;
9710
+ let unsubscribeTopic;
10055
9711
  if (config2.websocket) {
10056
9712
  const { destinationAddress, explicitDestination } = this.resolveDestination(config2);
10057
- WebSocketTransport.getInstance().subscribeTopic({
9713
+ unsubscribeTopic = WebSocketTransport.getInstance().subscribeTopic({
10058
9714
  topic: resolvedTopic,
10059
9715
  callback: () => {
10060
9716
  },
@@ -10064,10 +9720,12 @@ class KosSubscriptionManager {
10064
9720
  destinationAddress,
10065
9721
  explicitDestination
10066
9722
  });
10067
- eventSource = iterate(resolvedTopic);
10068
- } else {
10069
- eventSource = iterate(resolvedTopic);
10070
9723
  }
9724
+ const eventSource = iterate(resolvedTopic);
9725
+ controller.signal.addEventListener("abort", () => {
9726
+ void eventSource.return();
9727
+ unsubscribeTopic?.();
9728
+ });
10071
9729
  (async () => {
10072
9730
  try {
10073
9731
  for await (const processedData of flowManager.processEvents(
@@ -10076,7 +9734,7 @@ class KosSubscriptionManager {
10076
9734
  if (controller.signal.aborted) break;
10077
9735
  const handlerPromise = handler(processedData);
10078
9736
  if (handlerPromise instanceof Promise) {
10079
- await flowManager.trackPromise(handlerPromise);
9737
+ await handlerPromise;
10080
9738
  }
10081
9739
  }
10082
9740
  } catch (error) {
@@ -10198,12 +9856,12 @@ class KosSubscriptionManager {
10198
9856
  * Trigger smart queue flush with baseline temporal filtering
10199
9857
  * Called after baseline loads to replay queued events
10200
9858
  *
10201
- * @param topic - Topic that had baseline dependency
9859
+ * @param path - Path of the baseline request that completed
10202
9860
  */
10203
- flushQueueForBaseline(topic) {
10204
- const baseline = this.baselineDependencies.get(topic);
9861
+ flushQueueForBaseline(path) {
9862
+ const [topic, baseline] = [...this.baselineDependencies].find(([, b]) => b.path === path) ?? [];
10205
9863
  if (!baseline) {
10206
- this.log.debug(`No baseline dependency for topic: ${topic}`);
9864
+ this.log.debug(`No baseline dependency on path: ${path}`);
10207
9865
  return;
10208
9866
  }
10209
9867
  const store = this.getResponseStore();
@@ -10445,9 +10103,11 @@ class ServiceResponseStore {
10445
10103
  return config2.retention === ResponseRetention.TTL && config2.ttl ? Date.now() + config2.ttl : void 0;
10446
10104
  }
10447
10105
  /**
10448
- * Store response with retention policy
10106
+ * Store response with retention policy, cancelling the cleanup timer of the
10107
+ * response it replaces
10449
10108
  */
10450
10109
  storeResponse(key, cached, config2) {
10110
+ this.clearTimerIfExists(key);
10451
10111
  this.responses.set(key, cached);
10452
10112
  this.retentionPolicies.set(key, config2);
10453
10113
  this.applyRetentionPolicy(key, config2);
@@ -10543,9 +10203,14 @@ class KosModelComponentFactory {
10543
10203
  const childResolver = new KosChildResolver(model);
10544
10204
  const serviceResponseStore = new ServiceResponseStore();
10545
10205
  modelData.serviceResponses = serviceResponseStore;
10206
+ const onlineLifecycleManager = new KosOnlineLifecycleManager(
10207
+ model,
10208
+ createTaggedLogger(log2, "online")
10209
+ );
10546
10210
  const components = {
10547
10211
  fsm: fsm2,
10548
10212
  offlineQueue,
10213
+ onlineLifecycleManager,
10549
10214
  serviceResponseStore,
10550
10215
  companionManager,
10551
10216
  childResolver
@@ -10567,10 +10232,6 @@ class KosModelComponentFactory {
10567
10232
  offlineQueue,
10568
10233
  subLogger
10569
10234
  );
10570
- components.onlineLifecycleManager = new KosOnlineLifecycleManager(
10571
- model,
10572
- createTaggedLogger(log2, "online")
10573
- );
10574
10235
  }
10575
10236
  if (hasHttpRouteHandlers(modelData)) {
10576
10237
  components.httpRouteManager = new KosHttpRouteManager(
@@ -10581,7 +10242,8 @@ class KosModelComponentFactory {
10581
10242
  if (hasServiceRequestHandlers(modelData)) {
10582
10243
  components.serviceRequestManager = new ServiceRequestManager(
10583
10244
  modelData,
10584
- serviceResponseStore
10245
+ serviceResponseStore,
10246
+ components.subscriptionManager
10585
10247
  );
10586
10248
  }
10587
10249
  return components;
@@ -10967,11 +10629,21 @@ class KosModel {
10967
10629
  createLifecycleCompanions(lifecycle) {
10968
10630
  this.modelManager.createLifecycleCompanions(this, {}, lifecycle);
10969
10631
  }
10632
+ /**
10633
+ * Runs on every transition to online, including each reconnect, so the
10634
+ * ONLINE dependencies and service requests are resolved and sent again
10635
+ * each time. A state machine with `initializeAt: ONLINE` starts once.
10636
+ */
10970
10637
  async online() {
10971
10638
  log$8.debug(`online model ${this.modelTypeName} with id ${this.modelId}`);
10972
10639
  this.registerSubscribers();
10640
+ await executeDependentModelLifecycle(this, DependencyLifecycle.ONLINE);
10641
+ await this.serviceRequestManager?.executeForLifecycle(
10642
+ DependencyLifecycle.ONLINE
10643
+ );
10973
10644
  const context = KosContextManager.getContext(this.modelId);
10974
10645
  await this.modelData?.online?.(context);
10646
+ this.initializeStateMachineForLifecycle(DependencyLifecycle.ONLINE);
10975
10647
  this.createLifecycleCompanions(DependencyLifecycle.ONLINE);
10976
10648
  }
10977
10649
  async offline() {
@@ -11733,6 +11405,7 @@ const getConnectionAlias = () => {
11733
11405
  const envAlias = process.env.KOS_CONNECTION_ALIAS;
11734
11406
  return alias || envAlias || void 0;
11735
11407
  };
11408
+ const resolveAliasTemplate = (alias) => alias.replace("{{TIMESTAMP}}", Date.now().toString());
11736
11409
  const getDefaultProtocol = () => {
11737
11410
  const defaultProtocol = window.location.protocol;
11738
11411
  const params2 = getQueryParams();
@@ -11873,11 +11546,40 @@ class KosCore {
11873
11546
  }
11874
11547
  const alias = getConnectionAlias() ?? connectionAlias;
11875
11548
  if (alias) {
11876
- ws.alias = alias.replace("{{TIMESTAMP}}", Date.now().toString());
11549
+ ws.alias = resolveAliasTemplate(alias);
11877
11550
  }
11878
11551
  this._transport = ws.init();
11879
11552
  this.fsmService = coreFsm(this);
11880
11553
  }
11554
+ /**
11555
+ * Registers `connectionAlias` on a core whose transport has no alias yet:
11556
+ * the alias frame goes out now on an open connection, or first thing when
11557
+ * the connection opens, and every reconnect carries it. A transport that
11558
+ * already has an alias keeps it.
11559
+ */
11560
+ applyConnectionAlias(connectionAlias) {
11561
+ if (this._transport.alias) {
11562
+ if (this.connectionAlias && this.connectionAlias !== connectionAlias) {
11563
+ log$5.warn(
11564
+ `Connection alias ${connectionAlias} ignored; the connection already uses ${this._transport.alias}`
11565
+ );
11566
+ }
11567
+ return;
11568
+ }
11569
+ this.connectionAlias = connectionAlias;
11570
+ const alias = resolveAliasTemplate(connectionAlias);
11571
+ this._transport.alias = alias;
11572
+ const frame = `type:kos.addr.alias
11573
+ alias:${alias}
11574
+
11575
+ `;
11576
+ const socket = this._transport.socket;
11577
+ if (socket?.connectionEstablished) {
11578
+ socket.socket.send(frame);
11579
+ } else {
11580
+ socket?.addOfflineMessage(frame);
11581
+ }
11582
+ }
11881
11583
  startLifecycle() {
11882
11584
  if (this.lifecycleStarted) {
11883
11585
  return;
@@ -12110,11 +11812,21 @@ class KosCore {
12110
11812
  instance.startLifecycle();
12111
11813
  return instance;
12112
11814
  }
11815
+ /**
11816
+ * Returns the process-wide core, constructing it on first use or when
11817
+ * `reset` is set.
11818
+ *
11819
+ * `connectionAlias` applies to an existing core too, provided its transport
11820
+ * has no alias yet: registering a model reaches this method, so a
11821
+ * registration chain can construct the core before the alias is known.
11822
+ */
12113
11823
  static getInstance(data) {
12114
11824
  this._instance = window.KosCore;
12115
11825
  if (!this._instance || data?.reset) {
12116
11826
  window.KosCore = new this(data?.connectionAlias);
12117
11827
  this._instance = window.KosCore;
11828
+ } else if (data?.connectionAlias && this._instance instanceof KosCore) {
11829
+ this._instance.applyConnectionAlias(data.connectionAlias);
12118
11830
  }
12119
11831
  return this._instance;
12120
11832
  }
@@ -13505,7 +13217,6 @@ exports.createStudioMessageResponse = createStudioMessageResponse;
13505
13217
  exports.del = del;
13506
13218
  exports.destroyKosModel = destroyKosModel;
13507
13219
  exports.eventBus = eventBus;
13508
- exports.eventBus_functional = eventBus_functional;
13509
13220
  exports.eventBus_state = eventBus_state;
13510
13221
  exports.executeApiMethod = executeApiMethod;
13511
13222
  exports.executeChildrenModelLifecycle = executeChildrenModelLifecycle;
@@ -13601,4 +13312,4 @@ exports.uuid = uuid;
13601
13312
  exports.waitForAppToStart = waitForAppToStart;
13602
13313
  exports.waitForAppsToStart = waitForAppsToStart;
13603
13314
  exports.whenReady = whenReady;
13604
- //# sourceMappingURL=index-CRb8ucfF.cjs.map
13315
+ //# sourceMappingURL=index-D52vEGXT.cjs.map