@kinotic-ai/core 5.0.0-beta.2 → 5.0.0-beta.21

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.
package/dist/index.cjs CHANGED
@@ -66,9 +66,14 @@ var exports_src = {};
66
66
  __export(exports_src, {
67
67
  validateZone: () => validateZone,
68
68
  validateLabel: () => validateLabel,
69
+ scopeOptionalMethodNames: () => scopeOptionalMethodNames,
69
70
  receivesContext: () => receivesContext,
70
71
  isAdvertised: () => isAdvertised,
72
+ declaresAuthzResource: () => declaresAuthzResource,
73
+ declareServiceDefinitions: () => declareServiceDefinitions,
71
74
  createCRI: () => createCRI,
75
+ buildServerUrl: () => buildServerUrl,
76
+ buildBrokerUrl: () => buildBrokerUrl,
72
77
  Zone: () => Zone,
73
78
  Version: () => Version,
74
79
  TextEventFactory: () => TextEventFactory,
@@ -76,8 +81,11 @@ __export(exports_src, {
76
81
  SessionKeepAliveMode: () => SessionKeepAliveMode,
77
82
  SessionCredentialsResolver: () => SessionCredentialsResolver,
78
83
  ServiceRegistry: () => ServiceRegistry,
84
+ ServiceIdentifier: () => ServiceIdentifier,
79
85
  ServerInfo: () => ServerInfo,
86
+ ScopeOptional: () => ScopeOptional,
80
87
  Scope: () => Scope,
88
+ RpcError: () => RpcError,
81
89
  Publish: () => Publish,
82
90
  ParticipantConstants: () => ParticipantConstants,
83
91
  Pageable: () => Pageable,
@@ -103,6 +111,10 @@ __export(exports_src, {
103
111
  ChainedCredentialsResolver: () => ChainedCredentialsResolver,
104
112
  BearerCredentialsResolver: () => BearerCredentialsResolver,
105
113
  BasicCredentialsResolver: () => BasicCredentialsResolver,
114
+ AuthzUnchecked: () => AuthzUnchecked,
115
+ AuthzResource: () => AuthzResource,
116
+ AuthzCheck: () => AuthzCheck,
117
+ AuthorizationException: () => AuthorizationException,
106
118
  AbstractIterablePage: () => AbstractIterablePage
107
119
  });
108
120
  module.exports = __toCommonJS(exports_src);
@@ -113,6 +125,12 @@ class ServerInfo {
113
125
  port;
114
126
  useSSL;
115
127
  }
128
+ function buildServerUrl(server, scheme) {
129
+ return scheme + (server.useSSL ? "s" : "") + "://" + server.host + (server.port ? ":" + server.port : "");
130
+ }
131
+ function buildBrokerUrl(server) {
132
+ return buildServerUrl(server, "ws") + "/v1";
133
+ }
116
134
  var SessionKeepAliveMode;
117
135
  ((SessionKeepAliveMode2) => {
118
136
  SessionKeepAliveMode2["NONE"] = "NONE";
@@ -125,6 +143,7 @@ var EventConstants;
125
143
  EventConstants2["CONTENT_TYPE_HEADER"] = "content-type";
126
144
  EventConstants2["CONTENT_LENGTH_HEADER"] = "content-length";
127
145
  EventConstants2["REPLY_TO_HEADER"] = "reply-to";
146
+ EventConstants2["SENDER_HEADER"] = "sender";
128
147
  EventConstants2["CONNECTED_INFO_HEADER"] = "connected-info";
129
148
  EventConstants2["SESSION_KEEP_ALIVE_HEADER"] = "session-keep-alive";
130
149
  EventConstants2["CORRELATION_ID_HEADER"] = "__correlation-id";
@@ -149,126 +168,172 @@ var EventConstants;
149
168
  EventConstants2["TRACESTATE_HEADER"] = "tracestate";
150
169
  })(EventConstants ||= {});
151
170
 
171
+ // packages/core/src/internal/api/Logger.ts
172
+ var import_debug = __toESM(require("debug"));
173
+ function createDebugLogger(namespace) {
174
+ const debugLogger = import_debug.default(namespace);
175
+ return {
176
+ trace: (...args) => debugLogger("TRACE", ...args),
177
+ debug: (...args) => debugLogger("DEBUG", ...args),
178
+ info: (...args) => debugLogger("INFO", ...args),
179
+ warn: (...args) => debugLogger("WARN", ...args),
180
+ error: (...args) => debugLogger("ERROR", ...args)
181
+ };
182
+ }
183
+
152
184
  // packages/core/src/internal/api/StompConnectionManager.ts
153
185
  var import_rx_stomp = require("@stomp/rx-stomp");
154
186
  var import_stompjs = require("@stomp/stompjs");
155
- var import_debug = __toESM(require("debug"));
187
+ var import_debug2 = __toESM(require("debug"));
156
188
  var import_rxjs = require("rxjs");
189
+ var import_operators = require("rxjs/operators");
157
190
  var import_uuid = require("uuid");
191
+
192
+ // packages/core/src/internal/api/StompActivation.ts
193
+ class StompActivation {
194
+ _ended = false;
195
+ wake = null;
196
+ preparedSocket = null;
197
+ attempt = null;
198
+ failPending = null;
199
+ subscriptions = [];
200
+ get ended() {
201
+ return this._ended;
202
+ }
203
+ end() {
204
+ this._ended = true;
205
+ this.wake?.();
206
+ this.wake = null;
207
+ }
208
+ delay(ms) {
209
+ return new Promise((resolve) => {
210
+ const timer = setTimeout(() => {
211
+ this.wake = null;
212
+ resolve();
213
+ }, ms);
214
+ this.wake = () => {
215
+ clearTimeout(timer);
216
+ resolve();
217
+ };
218
+ });
219
+ }
220
+ own(subscription) {
221
+ this.subscriptions.push(subscription);
222
+ }
223
+ pending(fail) {
224
+ this.failPending = fail;
225
+ }
226
+ established() {
227
+ this.failPending = null;
228
+ }
229
+ failIfPending(reason) {
230
+ const fail = this.failPending;
231
+ this.failPending = null;
232
+ fail?.(reason);
233
+ }
234
+ unsubscribeAll() {
235
+ for (const subscription of this.subscriptions) {
236
+ subscription.unsubscribe();
237
+ }
238
+ this.subscriptions.length = 0;
239
+ }
240
+ }
241
+
242
+ // packages/core/src/internal/api/StompConnectionManager.ts
158
243
  var SESSION_CHECK_PATH = "/api/auth/me";
159
244
 
160
245
  class StompConnectionManager {
161
246
  lastWebsocketError = null;
162
247
  maxConnectionAttemptsReached = false;
163
- replyToCriChangedHandler = null;
164
- rxStomp = null;
248
+ connectionEndedHandler = null;
249
+ rxStomp = new import_rx_stomp.RxStomp;
250
+ activation = null;
251
+ teardown = null;
165
252
  INITIAL_RECONNECT_DELAY = 2000;
166
253
  JITTER_MAX = 5000;
167
254
  MAX_RECONNECT_DELAY = 120000;
168
255
  connectionAttempts = 0;
169
- debugLogger = import_debug.default("kinoitc:stomp");
170
- fatalErrorsSubject = new import_rxjs.Subject;
171
- _fatalErrors = this.fatalErrorsSubject.asObservable();
256
+ debugLogger = import_debug2.default("kinotic:stomp");
257
+ connectionEstablishedSubject = new import_rxjs.Subject;
172
258
  initialConnectionSuccessful = false;
173
- serverHeadersSubscription = null;
174
- stompErrorsSubscription = null;
175
- uuidv4 = import_uuid.v4();
259
+ rxStompHasConnected = false;
176
260
  _replyToCri = null;
177
261
  get replyToCri() {
178
262
  return this._replyToCri;
179
263
  }
180
264
  get active() {
181
- return !!this.rxStomp;
265
+ return this.activation !== null;
182
266
  }
183
267
  get connected() {
184
- return this.rxStomp != null && this.rxStomp.connected();
268
+ return this.activation !== null && this.rxStomp.connected();
185
269
  }
186
- get fatalErrors() {
187
- return this._fatalErrors;
270
+ get connectionEstablished() {
271
+ return this.connectionEstablishedSubject.asObservable();
188
272
  }
189
273
  async activate(options) {
190
- if (!options?.host) {
274
+ if (!options?.server?.host) {
191
275
  throw new Error("No host provided");
192
276
  }
193
- if (this.rxStomp) {
277
+ if (this.activation) {
278
+ throw new Error("Stomp connection already active");
279
+ }
280
+ await this.teardown;
281
+ if (this.activation) {
194
282
  throw new Error("Stomp connection already active");
195
283
  }
196
- const server = { host: options.host, port: options.port, useSSL: options.useSSL };
284
+ const server = options.server;
197
285
  const credentialsResolver = options.credentials;
286
+ const activation = new StompActivation;
287
+ this.activation = activation;
198
288
  let headerAuth = false;
199
- if (!options.webSocketFactory) {
200
- if (!credentialsResolver) {
201
- throw new Error("No credentials supplied and no default resolution applied");
289
+ try {
290
+ if (!options.webSocketFactory) {
291
+ if (!credentialsResolver) {
292
+ throw new Error("No credentials supplied and no default resolution applied");
293
+ }
294
+ const resolved = await credentialsResolver.resolve(server);
295
+ if (resolved === null) {
296
+ throw new Error("No Kinotic credentials found; consulted: " + credentialsResolver.name);
297
+ }
298
+ headerAuth = resolved.authHeaders != null;
202
299
  }
203
- const resolved = await credentialsResolver.resolve(server);
204
- if (resolved === null) {
205
- throw new Error("No Kinotic credentials found; consulted: " + credentialsResolver.name);
300
+ if (activation.ended) {
301
+ throw new Error("Deactivated before the connection was established");
302
+ }
303
+ } catch (e) {
304
+ if (this.activation === activation) {
305
+ this.activation = null;
206
306
  }
207
- headerAuth = resolved.authHeaders != null;
307
+ throw e;
208
308
  }
209
309
  return new Promise((resolve, reject) => {
210
310
  this.connectionAttempts = 0;
211
311
  this.initialConnectionSuccessful = false;
212
312
  this.lastWebsocketError = null;
213
313
  this.maxConnectionAttemptsReached = false;
214
- const url = Util.buildBrokerUrl(server);
215
- this.rxStomp = new import_rx_stomp.RxStomp;
216
- let preparedSocket = null;
217
- const userWebSocketFactory = options.webSocketFactory;
218
- const usesPreparedSocket = userWebSocketFactory != null || headerAuth;
314
+ const url = buildBrokerUrl(server);
315
+ const usesPreparedSocket = options.webSocketFactory != null || headerAuth;
316
+ const takePreparedSocket = () => {
317
+ const socket = activation.preparedSocket;
318
+ activation.preparedSocket = null;
319
+ return socket;
320
+ };
219
321
  const stompConfig = {
220
322
  brokerURL: url,
221
323
  connectHeaders: {
222
324
  ["session-keep-alive" /* SESSION_KEEP_ALIVE_HEADER */]: options.sessionKeepAlive ?? "ACTIVITY" /* ACTIVITY */
223
325
  },
224
- heartbeatIncoming: 120000,
326
+ heartbeatIncoming: 30000,
225
327
  heartbeatOutgoing: 30000,
226
328
  reconnectDelay: this.INITIAL_RECONNECT_DELAY,
227
329
  maxReconnectDelay: this.MAX_RECONNECT_DELAY,
228
330
  reconnectTimeMode: import_stompjs.ReconnectionTimeMode.EXPONENTIAL,
229
- webSocketFactory: usesPreparedSocket ? () => preparedSocket : undefined,
230
- beforeConnect: async () => {
231
- if (!usesPreparedSocket) {
232
- const sessionCheckUrl = "http" + (server.useSSL ? "s" : "") + "://" + server.host + (server.port ? ":" + server.port : "") + SESSION_CHECK_PATH;
233
- try {
234
- const res = await fetch(sessionCheckUrl, { credentials: "include" });
235
- if (res.status === 401) {
236
- await this.signalFatal(new Error("Authentication required"));
237
- return;
238
- }
239
- } catch {}
240
- }
241
- if (options?.maxConnectionAttempts) {
242
- this.connectionAttempts++;
243
- if (this.connectionAttempts > options.maxConnectionAttempts) {
244
- this.maxConnectionAttemptsReached = true;
245
- await this.signalFatal(new Error("Max number of reconnection attempts reached", { cause: this.lastWebsocketError ?? undefined }));
246
- return;
247
- } else {
248
- await this.connectionJitterDelay();
249
- }
250
- } else {
251
- await this.connectionJitterDelay();
252
- }
253
- if (userWebSocketFactory) {
254
- try {
255
- preparedSocket = await userWebSocketFactory();
256
- } catch (e) {
257
- await this.signalFatal(new Error("WebSocket factory failed", { cause: e }));
258
- }
259
- } else if (headerAuth) {
260
- try {
261
- const resolved = await credentialsResolver.resolve(server);
262
- if (resolved?.authHeaders == null) {
263
- await this.signalFatal(new Error("Credentials resolver no longer supplies auth headers: " + credentialsResolver.name));
264
- } else {
265
- const WS = WebSocket;
266
- preparedSocket = new WS(url, { headers: resolved.authHeaders });
267
- }
268
- } catch (e) {
269
- await this.signalFatal(new Error("Credential resolution failed", { cause: e }));
270
- }
271
- }
331
+ webSocketFactory: usesPreparedSocket ? takePreparedSocket : undefined,
332
+ beforeConnect: () => {
333
+ const attempt = this.prepareAttempt(activation, options, server, headerAuth);
334
+ const settled = () => new Promise((resolve2) => setTimeout(resolve2, 0));
335
+ activation.attempt = attempt.then(settled, settled);
336
+ return attempt;
272
337
  }
273
338
  };
274
339
  if (this.debugLogger.enabled) {
@@ -277,93 +342,195 @@ class StompConnectionManager {
277
342
  };
278
343
  }
279
344
  this.rxStomp.configure(stompConfig);
280
- this.rxStomp.webSocketErrors$.subscribe(async (value) => {
345
+ activation.own(this.rxStomp.webSocketErrors$.subscribe(async (value) => {
281
346
  this.lastWebsocketError = value;
282
- if (options?.maxConnectionAttempts && this.connectionAttempts >= options.maxConnectionAttempts) {
347
+ if (!activation.ended && options?.maxConnectionAttempts && this.connectionAttempts >= options.maxConnectionAttempts) {
283
348
  this.maxConnectionAttemptsReached = true;
284
- await this.signalFatal(new Error("Max number of reconnection attempts reached", { cause: value ?? undefined }));
349
+ await this.failConnection(activation, new Error("Max number of reconnection attempts reached", { cause: value ?? undefined }));
285
350
  }
286
- });
287
- this.stompErrorsSubscription = this.rxStomp.stompErrors$.subscribe(async (frame) => {
351
+ }));
352
+ activation.own(this.rxStomp.stompErrors$.subscribe(async (frame) => {
288
353
  const stompError = new Error(frame.headers["message"], { cause: frame });
289
- await this.signalFatal(new Error("STOMP connection error", { cause: stompError }));
290
- });
291
- const connectedSubscription = this.rxStomp.connected$.subscribe(() => {
292
- connectedSubscription.unsubscribe();
293
- initialFailureSubscription.unsubscribe();
294
- if (!this.initialConnectionSuccessful) {
295
- this.initialConnectionSuccessful = true;
296
- }
297
- });
298
- const initialFailureSubscription = this.fatalErrorsSubject.subscribe((err) => {
299
- connectedSubscription.unsubscribe();
300
- initialFailureSubscription.unsubscribe();
301
- reject(err.message);
302
- });
303
- this.serverHeadersSubscription = this.rxStomp.serverHeaders$.subscribe(async (value) => {
354
+ await this.failConnection(activation, new Error("STOMP connection error", { cause: stompError }));
355
+ }));
356
+ activation.own(this.rxStomp.connected$.subscribe(() => {
357
+ activation.established();
358
+ this.initialConnectionSuccessful = true;
359
+ this.connectionAttempts = 0;
360
+ }));
361
+ activation.pending(reject);
362
+ activation.own(this.rxStomp.serverHeaders$.pipe(import_operators.skip(this.rxStompHasConnected ? 1 : 0)).subscribe(async (value) => {
363
+ this.rxStompHasConnected = true;
304
364
  const connectedInfoJson = value["connected-info" /* CONNECTED_INFO_HEADER */];
305
365
  if (connectedInfoJson == null) {
306
366
  if (!this.initialConnectionSuccessful) {
307
- await this.deactivate();
308
- reject("Server did not return proper data for successful login");
367
+ await this.deactivate(undefined, new Error("Server did not return proper data for successful login"));
309
368
  }
310
369
  return;
311
370
  }
312
371
  const connectedInfo = JSON.parse(connectedInfoJson);
313
372
  if (connectedInfo.replyToId == null) {
314
373
  if (!this.initialConnectionSuccessful) {
315
- await this.deactivate();
316
- reject("Server did not return a replyToId for successful login");
374
+ await this.deactivate(undefined, new Error("Server did not return a replyToId for successful login"));
317
375
  }
318
376
  return;
319
377
  }
320
- const newReplyToCri = "reply://" /* REPLY_DESTINATION_PREFIX */ + connectedInfo.replyToId + ":" + this.uuidv4 + "@kinoitc.js.EventBus/replyHandler";
378
+ const newReplyToCri = "reply://" /* REPLY_DESTINATION_PREFIX */ + connectedInfo.replyToId + ":" + import_uuid.v4() + "@kinotic.js.EventBus/replyHandler";
379
+ this._replyToCri = newReplyToCri;
321
380
  if (!this.initialConnectionSuccessful) {
322
- this._replyToCri = newReplyToCri;
323
381
  resolve(connectedInfo);
324
- } else if (this._replyToCri !== newReplyToCri) {
325
- this._replyToCri = newReplyToCri;
326
- this.replyToCriChangedHandler?.(newReplyToCri);
327
382
  }
328
- });
383
+ this.connectionEstablishedSubject.next(connectedInfo);
384
+ }));
385
+ let previousState = this.rxStomp.connectionState$.getValue();
386
+ activation.own(this.rxStomp.connectionState$.subscribe((state) => {
387
+ if (state === import_rx_stomp.RxStompState.CLOSED && previousState === import_rx_stomp.RxStompState.OPEN && this.activation === activation) {
388
+ this.connectionEndedHandler?.(null);
389
+ }
390
+ previousState = state;
391
+ }));
329
392
  this.rxStomp.activate();
330
393
  });
331
394
  }
332
- async deactivate(force) {
333
- const rxStomp = this.rxStomp;
334
- if (rxStomp) {
335
- await rxStomp.deactivate({ force });
336
- if (this.rxStomp === rxStomp) {
337
- this.serverHeadersSubscription?.unsubscribe();
338
- this.serverHeadersSubscription = null;
339
- this.stompErrorsSubscription?.unsubscribe();
340
- this.stompErrorsSubscription = null;
341
- this.rxStomp = null;
342
- this._replyToCri = null;
395
+ async prepareAttempt(activation, options, server, headerAuth) {
396
+ const credentialsResolver = options.credentials;
397
+ const userWebSocketFactory = options.webSocketFactory;
398
+ const usesPreparedSocket = userWebSocketFactory != null || headerAuth;
399
+ const url = buildBrokerUrl(server);
400
+ if (!usesPreparedSocket) {
401
+ const sessionCheckUrl = buildServerUrl(server, "http") + SESSION_CHECK_PATH;
402
+ try {
403
+ const res = await fetch(sessionCheckUrl, { credentials: "include" });
404
+ if (res.status === 401) {
405
+ await this.failConnection(activation, new Error("Authentication required"));
406
+ return;
407
+ }
408
+ } catch (e) {
409
+ this.debugLogger("Session check at %s failed: %O", sessionCheckUrl, e);
410
+ }
411
+ }
412
+ if (options?.maxConnectionAttempts) {
413
+ this.connectionAttempts++;
414
+ if (this.connectionAttempts > options.maxConnectionAttempts) {
415
+ this.maxConnectionAttemptsReached = true;
416
+ await this.failConnection(activation, new Error("Max number of reconnection attempts reached", { cause: this.lastWebsocketError ?? undefined }));
417
+ return;
418
+ } else {
419
+ await this.connectionJitterDelay(activation);
420
+ }
421
+ } else {
422
+ await this.connectionJitterDelay(activation);
423
+ }
424
+ if (activation.ended) {
425
+ return;
426
+ }
427
+ if (userWebSocketFactory) {
428
+ try {
429
+ activation.preparedSocket = await userWebSocketFactory();
430
+ } catch (e) {
431
+ await this.failConnection(activation, new Error("WebSocket factory failed", { cause: e }));
432
+ }
433
+ } else if (headerAuth) {
434
+ try {
435
+ const resolved = await credentialsResolver.resolve(server);
436
+ if (resolved?.authHeaders == null) {
437
+ await this.failConnection(activation, new Error("Credentials resolver no longer supplies auth headers: " + credentialsResolver.name));
438
+ } else {
439
+ const WS = WebSocket;
440
+ activation.preparedSocket = new WS(url, { headers: resolved.authHeaders });
441
+ }
442
+ } catch (e) {
443
+ await this.failConnection(activation, new Error("Credential resolution failed", { cause: e }));
444
+ }
445
+ }
446
+ if (activation.ended && activation.preparedSocket) {
447
+ activation.preparedSocket.close();
448
+ activation.preparedSocket = null;
449
+ }
450
+ }
451
+ deactivate(force, reason = null) {
452
+ const activation = this.activation;
453
+ let ret;
454
+ if (activation) {
455
+ this.activation = null;
456
+ activation.end();
457
+ const wasOpen = this.rxStomp.connected();
458
+ this._replyToCri = null;
459
+ activation.failIfPending(reason ?? new Error("Deactivated before the connection was established"));
460
+ activation.preparedSocket?.close();
461
+ activation.preparedSocket = null;
462
+ const teardown = this.rxStomp.deactivate({ force }).then(() => activation.attempt ?? undefined).finally(() => {
463
+ activation.unsubscribeAll();
464
+ this.teardown = null;
465
+ });
466
+ this.teardown = teardown;
467
+ if (wasOpen || reason !== null) {
468
+ this.connectionEndedHandler?.(reason);
343
469
  }
470
+ ret = teardown;
471
+ } else {
472
+ ret = this.teardown ?? Promise.resolve();
344
473
  }
345
- return;
474
+ return ret;
346
475
  }
347
- async connectionJitterDelay() {
476
+ async connectionJitterDelay(activation) {
348
477
  if (this.initialConnectionSuccessful) {
349
478
  const randomJitter = Math.random() * this.JITTER_MAX;
350
479
  this.debugLogger(`Adding ${randomJitter}ms of jitter delay`);
351
- return new Promise((resolve) => setTimeout(resolve, randomJitter));
480
+ await activation.delay(randomJitter);
352
481
  }
353
482
  }
354
- async signalFatal(err) {
355
- this.debugLogger("Fatal error, deactivating connection: %O", err);
356
- await this.deactivate();
357
- this.fatalErrorsSubject.next(err);
483
+ async failConnection(activation, err) {
484
+ if (!activation.ended) {
485
+ this.debugLogger("Connection failed, ending it: %O", err);
486
+ await this.deactivate(undefined, err);
487
+ }
358
488
  }
359
489
  }
360
490
 
361
491
  // packages/core/src/api/event/EventBus.ts
362
492
  var import_api = require("@opentelemetry/api");
363
493
  var import_rxjs2 = require("rxjs");
364
- var import_operators = require("rxjs/operators");
494
+ var import_operators2 = require("rxjs/operators");
365
495
  var import_typescript_optional = require("typescript-optional");
366
496
  var import_uuid2 = require("uuid");
497
+
498
+ // packages/core/src/api/event/RpcError.ts
499
+ class RpcError extends Error {
500
+ exceptionName;
501
+ exceptionClass;
502
+ constructor(message, exceptionName, exceptionClass) {
503
+ super(message);
504
+ this.name = "RpcError";
505
+ this.exceptionName = exceptionName;
506
+ this.exceptionClass = exceptionClass;
507
+ }
508
+ static fromEvent(reply) {
509
+ const message = reply.getHeader("error" /* ERROR_HEADER */) ?? "";
510
+ let ret;
511
+ const detail = describedException(reply);
512
+ if (detail !== undefined) {
513
+ ret = new RpcError(detail.errorMessage ?? message, detail.exceptionName ?? "", detail.exceptionClass ?? "");
514
+ } else {
515
+ ret = new RpcError(message, "", "");
516
+ }
517
+ return ret;
518
+ }
519
+ }
520
+ function describedException(reply) {
521
+ let ret = undefined;
522
+ if (reply.data.isPresent() && reply.getHeader("content-type" /* CONTENT_TYPE_HEADER */)?.startsWith("application/json")) {
523
+ try {
524
+ const parsed = JSON.parse(reply.getDataString());
525
+ if (parsed !== null && typeof parsed === "object") {
526
+ ret = parsed;
527
+ }
528
+ } catch {}
529
+ }
530
+ return ret;
531
+ }
532
+
533
+ // packages/core/src/api/event/EventBus.ts
367
534
  class Event {
368
535
  cri;
369
536
  headers;
@@ -402,24 +569,31 @@ class Event {
402
569
 
403
570
  class EventBus {
404
571
  serverInfo = null;
572
+ log = createDebugLogger("kinotic:EventBus");
405
573
  stompConnectionManager = new StompConnectionManager;
406
574
  connectionLifecycle = Promise.resolve();
407
- replyToCri = null;
575
+ disconnectRequests = 0;
408
576
  requestRepliesObservable = null;
409
577
  requestRepliesSubject = null;
410
578
  requestRepliesSubscription = null;
411
579
  activeCorrelationIds = new Set;
412
580
  recentlyReaped = new Set;
581
+ connectionEndedSubject = new import_rxjs2.Subject;
413
582
  static REAP_DEBOUNCE_MS = 5000;
414
583
  constructor() {
415
- this.stompConnectionManager.fatalErrors.subscribe(() => this.cleanup());
416
- this.stompConnectionManager.replyToCriChangedHandler = (replyToCri) => {
417
- this.replyToCri = replyToCri;
418
- this.resetRequestReplies("Reply destination changed");
584
+ this.stompConnectionManager.connectionEndedHandler = (reason) => {
585
+ this.resetRequestReplies("Connection lost");
586
+ if (!this.stompConnectionManager.active) {
587
+ this.serverInfo = null;
588
+ }
589
+ this.connectionEndedSubject.next(reason);
419
590
  };
420
591
  }
421
- get fatalErrors() {
422
- return this.stompConnectionManager.fatalErrors;
592
+ get connectionEnded() {
593
+ return this.connectionEndedSubject.asObservable();
594
+ }
595
+ get connectionEstablished() {
596
+ return this.stompConnectionManager.connectionEstablished;
423
597
  }
424
598
  isConnectionActive() {
425
599
  return this.stompConnectionManager.active;
@@ -428,15 +602,14 @@ class EventBus {
428
602
  return this.stompConnectionManager.connected;
429
603
  }
430
604
  connect(options) {
605
+ const disconnectsWhenQueued = this.disconnectRequests;
431
606
  return this.serializeLifecycle(async () => {
607
+ if (this.disconnectRequests !== disconnectsWhenQueued) {
608
+ throw new Error("Disconnected before the connection was started");
609
+ }
432
610
  if (!this.stompConnectionManager.active) {
433
- this.cleanup();
434
611
  const connectedInfo = await this.stompConnectionManager.activate(options);
435
- this.serverInfo = new ServerInfo;
436
- this.serverInfo.host = options.host;
437
- this.serverInfo.port = options.port;
438
- this.serverInfo.useSSL = options.useSSL;
439
- this.replyToCri = this.stompConnectionManager.replyToCri;
612
+ this.serverInfo = { ...options.server };
440
613
  return connectedInfo;
441
614
  } else {
442
615
  throw new Error("Event Bus connection already active");
@@ -444,9 +617,12 @@ class EventBus {
444
617
  });
445
618
  }
446
619
  disconnect(force) {
620
+ this.disconnectRequests++;
621
+ const deactivated = this.stompConnectionManager.deactivate(force);
447
622
  return this.serializeLifecycle(async () => {
623
+ await deactivated;
448
624
  await this.stompConnectionManager.deactivate(force);
449
- this.cleanup();
625
+ this.serverInfo = null;
450
626
  });
451
627
  }
452
628
  serializeLifecycle(operation) {
@@ -455,7 +631,7 @@ class EventBus {
455
631
  return result;
456
632
  }
457
633
  send(event) {
458
- if (this.stompConnectionManager.rxStomp) {
634
+ if (this.stompConnectionManager.connected) {
459
635
  const headers = {};
460
636
  for (const [key, value] of event.headers.entries()) {
461
637
  headers[key] = value;
@@ -471,7 +647,8 @@ class EventBus {
471
647
  this.stompConnectionManager.rxStomp.publish({
472
648
  destination: event.cri,
473
649
  headers,
474
- binaryBody: event.data.orUndefined()
650
+ binaryBody: event.data.orUndefined(),
651
+ retryIfDisconnected: false
475
652
  });
476
653
  } else {
477
654
  throw this.createSendUnavailableError();
@@ -481,58 +658,65 @@ class EventBus {
481
658
  return import_rxjs2.firstValueFrom(this.requestStream(event, false));
482
659
  }
483
660
  requestStream(event, sendControlEvents = true) {
484
- if (this.stompConnectionManager?.rxStomp) {
485
- return new import_rxjs2.Observable((subscriber) => {
486
- if (this.requestRepliesObservable == null) {
487
- this.requestRepliesSubject = new import_rxjs2.Subject;
488
- this.requestRepliesObservable = this._observe(this.replyToCri).pipe(import_operators.tap((value) => this.cancelIfUnexpected(value)), import_operators.multicast(this.requestRepliesSubject));
489
- this.requestRepliesSubscription = this.requestRepliesObservable.connect();
490
- }
491
- let serverSignaledCompletion = false;
492
- const correlationId = import_uuid2.v4();
493
- this.activeCorrelationIds.add(correlationId);
494
- const defaultMessagesSubscription = this.requestRepliesObservable.pipe(import_operators.filter((value) => {
495
- return value.headers.get("__correlation-id" /* CORRELATION_ID_HEADER */) === correlationId;
496
- })).subscribe({
497
- next(value) {
498
- if (value.hasHeader("control" /* CONTROL_HEADER */)) {
499
- if (value.headers.get("control" /* CONTROL_HEADER */) === "complete" /* CONTROL_VALUE_COMPLETE */) {
500
- serverSignaledCompletion = true;
501
- subscriber.complete();
502
- } else {
503
- throw new Error("Control Header " + value.headers.get("control" /* CONTROL_HEADER */) + " is not supported");
504
- }
505
- } else if (value.hasHeader("error" /* ERROR_HEADER */)) {
661
+ return new import_rxjs2.Observable((subscriber) => {
662
+ const replyToCri = this.stompConnectionManager.replyToCri;
663
+ if (!this.stompConnectionManager.connected || replyToCri == null) {
664
+ subscriber.error(this.createSendUnavailableError());
665
+ return;
666
+ }
667
+ if (this.requestRepliesObservable == null) {
668
+ this.requestRepliesSubject = new import_rxjs2.Subject;
669
+ this.requestRepliesObservable = this._observe(replyToCri).pipe(import_operators2.tap((value) => this.cancelIfUnexpected(value)), import_operators2.multicast(this.requestRepliesSubject));
670
+ this.requestRepliesSubscription = this.requestRepliesObservable.connect();
671
+ }
672
+ let serverSignaledCompletion = false;
673
+ let replyDestinationReset = false;
674
+ const correlationId = import_uuid2.v4();
675
+ this.activeCorrelationIds.add(correlationId);
676
+ subscriber.add(() => this.activeCorrelationIds.delete(correlationId));
677
+ const defaultMessagesSubscription = this.requestRepliesObservable.pipe(import_operators2.filter((value) => {
678
+ return value.headers.get("__correlation-id" /* CORRELATION_ID_HEADER */) === correlationId;
679
+ })).subscribe({
680
+ next(value) {
681
+ if (value.hasHeader("control" /* CONTROL_HEADER */)) {
682
+ if (value.headers.get("control" /* CONTROL_HEADER */) === "complete" /* CONTROL_VALUE_COMPLETE */) {
506
683
  serverSignaledCompletion = true;
507
- subscriber.error(new Error(value.getHeader("error" /* ERROR_HEADER */)));
684
+ if (value.data.isPresent() || !sendControlEvents) {
685
+ subscriber.next(value);
686
+ }
687
+ subscriber.complete();
508
688
  } else {
509
- subscriber.next(value);
689
+ subscriber.error(new Error("Control Header " + value.headers.get("control" /* CONTROL_HEADER */) + " is not supported"));
510
690
  }
511
- },
512
- error(err) {
513
- subscriber.error(err);
514
- },
515
- complete() {
516
- subscriber.complete();
691
+ } else if (value.hasHeader("error" /* ERROR_HEADER */)) {
692
+ serverSignaledCompletion = true;
693
+ subscriber.error(RpcError.fromEvent(value));
694
+ } else {
695
+ subscriber.next(value);
517
696
  }
518
- });
519
- subscriber.add(defaultMessagesSubscription);
520
- event.setHeader("reply-to" /* REPLY_TO_HEADER */, this.replyToCri);
521
- event.setHeader("__correlation-id" /* CORRELATION_ID_HEADER */, correlationId);
522
- this.send(event);
523
- return () => {
524
- this.activeCorrelationIds.delete(correlationId);
525
- if (sendControlEvents && !serverSignaledCompletion) {
526
- const controlEvent = new Event(event.cri);
527
- controlEvent.setHeader("control" /* CONTROL_HEADER */, "cancel" /* CONTROL_VALUE_CANCEL */);
528
- controlEvent.setHeader("__correlation-id" /* CORRELATION_ID_HEADER */, correlationId);
529
- this.send(controlEvent);
697
+ },
698
+ error(err) {
699
+ replyDestinationReset = true;
700
+ subscriber.error(err);
701
+ },
702
+ complete() {
703
+ subscriber.complete();
704
+ }
705
+ });
706
+ subscriber.add(defaultMessagesSubscription);
707
+ event.setHeader("reply-to" /* REPLY_TO_HEADER */, replyToCri);
708
+ event.setHeader("__correlation-id" /* CORRELATION_ID_HEADER */, correlationId);
709
+ this.send(event);
710
+ subscriber.add(() => {
711
+ if (sendControlEvents && !serverSignaledCompletion && !replyDestinationReset) {
712
+ try {
713
+ this.sendCancel(event.cri, correlationId);
714
+ } catch (e) {
715
+ this.log.warn(`Could not cancel stream ${correlationId} on ${event.cri}`, e);
530
716
  }
531
- };
717
+ }
532
718
  });
533
- } else {
534
- return import_rxjs2.throwError(() => this.createSendUnavailableError());
535
- }
719
+ });
536
720
  }
537
721
  listen(_serverInfo) {
538
722
  return Promise.reject("Not implemented");
@@ -540,10 +724,6 @@ class EventBus {
540
724
  observe(cri) {
541
725
  return this._observe(cri);
542
726
  }
543
- cleanup() {
544
- this.resetRequestReplies("Connection disconnected");
545
- this.serverInfo = null;
546
- }
547
727
  cancelIfUnexpected(value) {
548
728
  const correlationId = value.getHeader("__correlation-id" /* CORRELATION_ID_HEADER */);
549
729
  if (correlationId === undefined || this.activeCorrelationIds.has(correlationId)) {
@@ -554,13 +734,19 @@ class EventBus {
554
734
  return;
555
735
  }
556
736
  try {
557
- const cancelEvent = new Event(originCri);
558
- cancelEvent.setHeader("control" /* CONTROL_HEADER */, "cancel" /* CONTROL_VALUE_CANCEL */);
559
- cancelEvent.setHeader("__correlation-id" /* CORRELATION_ID_HEADER */, correlationId);
560
- this.send(cancelEvent);
737
+ this.sendCancel(originCri, correlationId);
561
738
  this.recentlyReaped.add(correlationId);
562
739
  setTimeout(() => this.recentlyReaped.delete(correlationId), EventBus.REAP_DEBOUNCE_MS);
563
- } catch {}
740
+ } catch (e) {
741
+ this.log.warn(`Could not cancel orphaned stream ${correlationId} on ${originCri}`, e);
742
+ }
743
+ }
744
+ sendCancel(cri, correlationId) {
745
+ const cancelEvent = new Event(cri);
746
+ cancelEvent.setHeader("control" /* CONTROL_HEADER */, "cancel" /* CONTROL_VALUE_CANCEL */);
747
+ cancelEvent.setHeader("__correlation-id" /* CORRELATION_ID_HEADER */, correlationId);
748
+ cancelEvent.setHeader("reply-to" /* REPLY_TO_HEADER */, this.stompConnectionManager.replyToCri);
749
+ this.send(cancelEvent);
564
750
  }
565
751
  resetRequestReplies(reason) {
566
752
  if (this.requestRepliesSubject != null) {
@@ -575,29 +761,29 @@ class EventBus {
575
761
  }
576
762
  }
577
763
  createSendUnavailableError() {
578
- let ret = "You must call connect on the event bus before sending any request";
764
+ let ret;
579
765
  if (this.stompConnectionManager.maxConnectionAttemptsReached) {
580
766
  ret = "Max connection attempts reached event bus is not available";
767
+ } else if (this.stompConnectionManager.active) {
768
+ ret = "The event bus is not connected to the server";
769
+ } else {
770
+ ret = "You must call connect on the event bus before sending any request";
581
771
  }
582
772
  return new Error(ret);
583
773
  }
584
774
  _observe(cri) {
585
- if (this.stompConnectionManager?.rxStomp) {
586
- return this.stompConnectionManager.rxStomp.watch(cri).pipe(import_operators.map((message) => {
587
- const headers = new Map;
588
- let destination = "";
589
- for (const prop of Object.keys(message.headers)) {
590
- if (prop === "destination") {
591
- destination = message.headers[prop];
592
- } else {
593
- headers.set(prop, message.headers[prop]);
594
- }
775
+ return this.stompConnectionManager.rxStomp.watch(cri).pipe(import_operators2.map((message) => {
776
+ const headers = new Map;
777
+ let destination = "";
778
+ for (const prop of Object.keys(message.headers)) {
779
+ if (prop === "destination") {
780
+ destination = message.headers[prop];
781
+ } else {
782
+ headers.set(prop, message.headers[prop]);
595
783
  }
596
- return new Event(destination, headers, message.binaryBody);
597
- }));
598
- } else {
599
- throw this.createSendUnavailableError();
600
- }
784
+ }
785
+ return new Event(destination, headers, message.binaryBody.length > 0 ? message.binaryBody : undefined);
786
+ }));
601
787
  }
602
788
  }
603
789
 
@@ -620,28 +806,46 @@ class ChainedCredentialsResolver {
620
806
  }
621
807
  }
622
808
 
809
+ // packages/core/src/api/security/BasicCredentialsResolver.ts
810
+ class BasicCredentialsResolver {
811
+ name = "BasicCredentialsResolver";
812
+ credentials;
813
+ constructor(clientId, clientSecret, organizationId, applicationId) {
814
+ const authHeaders = { clientId, clientSecret };
815
+ if (organizationId != null)
816
+ authHeaders.organizationId = organizationId;
817
+ if (applicationId != null)
818
+ authHeaders.applicationId = applicationId;
819
+ this.credentials = { authHeaders, organizationId, applicationId };
820
+ }
821
+ async resolve(_server) {
822
+ return this.credentials;
823
+ }
824
+ }
825
+
826
+ // packages/core/src/api/security/BearerCredentialsResolver.ts
827
+ class BearerCredentialsResolver {
828
+ name = "BearerCredentialsResolver";
829
+ token;
830
+ constructor(token) {
831
+ this.token = token;
832
+ }
833
+ async resolve(_server) {
834
+ const token = typeof this.token === "function" ? await this.token() : this.token;
835
+ return { authHeaders: { Authorization: `Bearer ${token}` } };
836
+ }
837
+ }
838
+
623
839
  // packages/core/src/api/security/EnvCredentialsResolver.ts
624
840
  class EnvCredentialsResolver {
625
841
  name = "EnvCredentialsResolver";
626
- async resolve(_server) {
842
+ async resolve(server) {
627
843
  const env = typeof process !== "undefined" ? process.env : undefined;
628
844
  let ret = null;
629
845
  if (env?.KINOTIC_CLIENT_ID && env?.KINOTIC_CLIENT_SECRET) {
630
- const authHeaders = {
631
- clientId: env.KINOTIC_CLIENT_ID,
632
- clientSecret: env.KINOTIC_CLIENT_SECRET
633
- };
634
- if (env.KINOTIC_ORGANIZATION_ID)
635
- authHeaders.organizationId = env.KINOTIC_ORGANIZATION_ID;
636
- if (env.KINOTIC_APPLICATION_ID)
637
- authHeaders.applicationId = env.KINOTIC_APPLICATION_ID;
638
- ret = {
639
- authHeaders,
640
- organizationId: env.KINOTIC_ORGANIZATION_ID,
641
- applicationId: env.KINOTIC_APPLICATION_ID
642
- };
846
+ ret = await new BasicCredentialsResolver(env.KINOTIC_CLIENT_ID, env.KINOTIC_CLIENT_SECRET, env.KINOTIC_ORGANIZATION_ID || undefined, env.KINOTIC_APPLICATION_ID || undefined).resolve(server);
643
847
  } else if (env?.KINOTIC_TOKEN) {
644
- ret = { authHeaders: { Authorization: `Bearer ${env.KINOTIC_TOKEN}` } };
848
+ ret = await new BearerCredentialsResolver(env.KINOTIC_TOKEN).resolve(server);
645
849
  }
646
850
  return ret;
647
851
  }
@@ -657,7 +861,7 @@ class SessionCredentialsResolver {
657
861
 
658
862
  // packages/core/src/internal/api/Util.ts
659
863
  var DEFAULT_PORT = 58503;
660
- var DEFAULT_HOST = "api.kinotic.com";
864
+ var DEFAULT_HOST = "api.kinotic.ai";
661
865
 
662
866
  class Util {
663
867
  static createReplyEvent(incomingHeaders, headers, body) {
@@ -681,20 +885,18 @@ class Util {
681
885
  }
682
886
  return new Event(replyCRI, newHeaders, body || undefined);
683
887
  }
684
- static buildBrokerUrl(serverInfo) {
685
- return "ws" + (serverInfo.useSSL ? "s" : "") + "://" + serverInfo.host + (serverInfo.port ? ":" + serverInfo.port : "") + "/v1";
686
- }
687
888
  static resolveConnectOptions(options) {
688
889
  const opts = options ?? {};
890
+ const server = opts.server ?? {};
689
891
  const env = typeof process !== "undefined" ? process.env : undefined;
690
892
  const location = typeof window !== "undefined" ? window.location : undefined;
691
- let host = opts.host ?? env?.KINOTIC_SERVER_HOST;
893
+ let host = server.host ?? env?.KINOTIC_SERVER_HOST;
692
894
  const hostFromLocation = host == null && location != null;
693
895
  const hostDefaulted = host == null && location == null;
694
896
  if (host == null) {
695
897
  host = location?.hostname ?? DEFAULT_HOST;
696
898
  }
697
- let useSSL = opts.useSSL;
899
+ let useSSL = server.useSSL;
698
900
  if (useSSL == null) {
699
901
  if (env?.KINOTIC_SERVER_USE_SSL != null) {
700
902
  useSSL = env.KINOTIC_SERVER_USE_SSL === "true";
@@ -704,7 +906,7 @@ class Util {
704
906
  useSSL = hostDefaulted;
705
907
  }
706
908
  }
707
- let port = opts.port;
909
+ let port = server.port;
708
910
  if (port === undefined) {
709
911
  if (env?.KINOTIC_SERVER_PORT != null) {
710
912
  port = Number(env.KINOTIC_SERVER_PORT);
@@ -716,9 +918,7 @@ class Util {
716
918
  }
717
919
  return {
718
920
  ...opts,
719
- host,
720
- port,
721
- useSSL,
921
+ server: { host, port, useSSL },
722
922
  sessionKeepAlive: opts.sessionKeepAlive ?? "ACTIVITY" /* ACTIVITY */,
723
923
  credentials: opts.credentials ?? new ChainedCredentialsResolver(new EnvCredentialsResolver, new SessionCredentialsResolver)
724
924
  };
@@ -914,22 +1114,14 @@ class JsonArgumentResolver {
914
1114
  // packages/core/src/internal/api/ReturnValueConverter.ts
915
1115
  class BasicReturnValueConverter {
916
1116
  convert(incomingMetadata, returnValue) {
917
- return Util.createReplyEvent(incomingMetadata, new Map([["content-type" /* CONTENT_TYPE_HEADER */, "application/json"]]), new TextEncoder().encode(JSON.stringify(returnValue)));
1117
+ const json = returnValue === undefined ? "null" : JSON.stringify(returnValue);
1118
+ return Util.createReplyEvent(incomingMetadata, new Map([["content-type" /* CONTENT_TYPE_HEADER */, "application/json"]]), new TextEncoder().encode(json));
918
1119
  }
919
1120
  }
920
1121
 
921
- // packages/core/src/internal/api/Logger.ts
922
- var import_debug2 = __toESM(require("debug"));
923
- function createDebugLogger(namespace) {
924
- const debugLogger = import_debug2.default(namespace);
925
- return {
926
- trace: (...args) => debugLogger("TRACE", ...args),
927
- debug: (...args) => debugLogger("DEBUG", ...args),
928
- info: (...args) => debugLogger("INFO", ...args),
929
- warn: (...args) => debugLogger("WARN", ...args),
930
- error: (...args) => debugLogger("ERROR", ...args)
931
- };
932
- }
1122
+ // packages/core/src/internal/api/ServiceInvocationSupervisor.ts
1123
+ var import_rxjs3 = require("rxjs");
1124
+ var import_operators3 = require("rxjs/operators");
933
1125
 
934
1126
  // packages/core/src/api/ServiceIdentifier.ts
935
1127
  class ServiceIdentifier {
@@ -966,6 +1158,9 @@ class ServiceIdentifier {
966
1158
  }
967
1159
  return this._cri;
968
1160
  }
1161
+ unscopedCri() {
1162
+ return createCRI("srv" /* SERVICE_DESTINATION_SCHEME */, null, this.qualifiedName(), null, this.version || null);
1163
+ }
969
1164
  }
970
1165
 
971
1166
  // packages/core/src/api/ZoneUtil.ts
@@ -985,10 +1180,12 @@ function validateLabel(label) {
985
1180
 
986
1181
  // packages/core/src/api/KinoticDecorators.ts
987
1182
  var scopeFunctions = new WeakSet;
1183
+ var scopeOptionalFunctions = new WeakSet;
988
1184
  var versionRegistry = new WeakMap;
989
1185
  var zonesRegistry = new WeakMap;
990
1186
  var advertisedRegistry = new WeakMap;
991
1187
  var contextMarkedFunctions = new WeakSet;
1188
+ var authzResourceClasses = new WeakSet;
992
1189
  function findInConstructorChain(registry, constructor) {
993
1190
  let current = constructor;
994
1191
  while (current) {
@@ -1022,6 +1219,23 @@ function resolveScope(instance) {
1022
1219
  function Scope(value, _context) {
1023
1220
  scopeFunctions.add(value);
1024
1221
  }
1222
+ function ScopeOptional(value, _context) {
1223
+ scopeOptionalFunctions.add(value);
1224
+ }
1225
+ function scopeOptionalMethodNames(instance) {
1226
+ const ret = new Set;
1227
+ let proto = Object.getPrototypeOf(instance);
1228
+ while (proto && proto !== Object.prototype) {
1229
+ for (const key of Object.getOwnPropertyNames(proto)) {
1230
+ const descriptor = Object.getOwnPropertyDescriptor(proto, key);
1231
+ if (typeof descriptor?.value === "function" && scopeOptionalFunctions.has(descriptor.value)) {
1232
+ ret.add(key);
1233
+ }
1234
+ }
1235
+ proto = Object.getPrototypeOf(proto);
1236
+ }
1237
+ return ret;
1238
+ }
1025
1239
  function Version(version) {
1026
1240
  if (!/^\d+\.\d+\.\d+(-[a-zA-Z0-9]+)?$/.test(version)) {
1027
1241
  throw new Error(`Invalid semantic version: ${version}. Must follow X.Y.Z[-optional] format.`);
@@ -1062,6 +1276,24 @@ function resolveEffectiveZone(constructor) {
1062
1276
  }
1063
1277
  return effectiveZone;
1064
1278
  }
1279
+ function AuthzResource(declaration) {
1280
+ return function(value, _context) {
1281
+ authzResourceClasses.add(value);
1282
+ };
1283
+ }
1284
+ function AuthzCheck(declaration) {
1285
+ return function(_value, _context) {};
1286
+ }
1287
+ function AuthzUnchecked(_value, _context) {}
1288
+ function declaresAuthzResource(serviceInstance) {
1289
+ let ret = false;
1290
+ let current = serviceInstance.constructor;
1291
+ while (current && !ret) {
1292
+ ret = authzResourceClasses.has(current);
1293
+ current = Object.getPrototypeOf(current);
1294
+ }
1295
+ return ret;
1296
+ }
1065
1297
  function Publish(namespace, name, advertise = false) {
1066
1298
  return function(value, _context) {
1067
1299
  advertisedRegistry.set(value, advertise);
@@ -1084,6 +1316,94 @@ function Publish(namespace, name, advertise = false) {
1084
1316
  };
1085
1317
  }
1086
1318
 
1319
+ // packages/core/src/internal/api/ServiceInvocationSupervisor.ts
1320
+ var import_api2 = __toESM(require("@opentelemetry/api"));
1321
+ // packages/core/package.json
1322
+ var package_default = {
1323
+ name: "@kinotic-ai/core",
1324
+ version: "5.0.0-beta.21",
1325
+ type: "module",
1326
+ files: [
1327
+ "dist"
1328
+ ],
1329
+ module: "./dist/index.js",
1330
+ main: "./dist/index.cjs",
1331
+ types: "./dist/index.d.ts",
1332
+ exports: {
1333
+ ".": {
1334
+ import: {
1335
+ types: "./dist/index.d.ts",
1336
+ default: "./dist/index.js"
1337
+ },
1338
+ require: {
1339
+ types: "./dist/index.d.cts",
1340
+ default: "./dist/index.cjs"
1341
+ }
1342
+ },
1343
+ "./node": {
1344
+ import: {
1345
+ types: "./dist/node/index.d.ts",
1346
+ default: "./dist/node/index.js"
1347
+ },
1348
+ require: {
1349
+ types: "./dist/node/index.d.cts",
1350
+ default: "./dist/node/index.cjs"
1351
+ }
1352
+ },
1353
+ "./package.json": "./package.json"
1354
+ },
1355
+ homepage: "https://github.com/kinotic-ai/kinotic",
1356
+ repository: {
1357
+ type: "git",
1358
+ url: "git+https://github.com/kinotic-ai/kinotic.git",
1359
+ directory: "kinotic-js/workspace/packages/core"
1360
+ },
1361
+ license: "Elastic License 2.0",
1362
+ publishConfig: {
1363
+ access: "public"
1364
+ },
1365
+ scripts: {
1366
+ "type-check": "tsc --noEmit",
1367
+ test: "vitest run",
1368
+ coverage: "vitest run --coverage",
1369
+ "ui-test": "vitest --ui --coverage.enabled=true --mode development"
1370
+ },
1371
+ devDependencies: {
1372
+ "@opentelemetry/exporter-trace-otlp-grpc": "^0.221.0",
1373
+ "@opentelemetry/resources": "^2.10.0",
1374
+ "@opentelemetry/sdk-metrics": "^2.10.0",
1375
+ "@opentelemetry/sdk-node": "^0.221.0",
1376
+ "@opentelemetry/sdk-trace-node": "^2.10.0",
1377
+ "@types/debug": "^4.1.13",
1378
+ "@types/node": "^25.6.0",
1379
+ "@types/ws": "^8.18.0",
1380
+ "@vitest/coverage-v8": "^4.1.4",
1381
+ "@vitest/runner": "^4.1.4",
1382
+ "@vitest/ui": "^4.1.4",
1383
+ allure: "^3.19.1",
1384
+ "allure-vitest": "^3.13.0",
1385
+ dotenv: "^17.4.1",
1386
+ "properties-file": "^4.0.0",
1387
+ testcontainers: "^11.14.0",
1388
+ tslib: "^2.8.1",
1389
+ typescript: "^6.0.2",
1390
+ vitest: "^4.1.4"
1391
+ },
1392
+ dependencies: {
1393
+ "@kinotic-ai/idl": "workspace:*",
1394
+ "@opentelemetry/api": "^1.9.1",
1395
+ "@opentelemetry/semantic-conventions": "^1.40.0",
1396
+ "@stomp/rx-stomp": "^2.4.0",
1397
+ "@stomp/stompjs": "^7.3.0",
1398
+ debug: "^4.4.3",
1399
+ "p-tap": "^4.0.0",
1400
+ rxjs: "^7.8.2",
1401
+ "typescript-optional": "3.0.0-alpha.3",
1402
+ uuid: "^13.0.0",
1403
+ ws: "^8.21.0"
1404
+ }
1405
+ };
1406
+
1087
1407
  // packages/core/src/internal/api/ServiceInvocationSupervisor.ts
1088
1408
  class ServiceInvocationSupervisor {
1089
1409
  log;
@@ -1095,7 +1415,13 @@ class ServiceInvocationSupervisor {
1095
1415
  serviceIdentifier;
1096
1416
  serviceInstance;
1097
1417
  methodSubscription = null;
1418
+ unscopedSubscription = null;
1419
+ activeStreams = new Map;
1420
+ connectionEndedSubscription = null;
1421
+ connectionGeneration = 0;
1098
1422
  methodMap;
1423
+ scopeOptionalMethods;
1424
+ tracer;
1099
1425
  constructor(serviceIdentifier, serviceInstance, eventBusService, interceptorProvider, options = {}) {
1100
1426
  if (!serviceIdentifier)
1101
1427
  throw new Error("ServiceIdentifier must not be null");
@@ -1109,10 +1435,12 @@ class ServiceInvocationSupervisor {
1109
1435
  this.serviceInstance = serviceInstance;
1110
1436
  this._eventBus = eventBusService;
1111
1437
  this.interceptorProvider = interceptorProvider;
1112
- this.log = options.logger || createDebugLogger("kinoitc:ServiceInvocationSupervisor");
1438
+ this.log = options.logger || createDebugLogger("kinotic:ServiceInvocationSupervisor");
1113
1439
  this.argumentResolver = options.argumentResolver || new JsonArgumentResolver;
1114
1440
  this.returnValueConverter = options.returnValueConverter || new BasicReturnValueConverter;
1115
1441
  this.methodMap = this.buildMethodMap(serviceInstance);
1442
+ this.scopeOptionalMethods = scopeOptionalMethodNames(serviceInstance);
1443
+ this.tracer = import_api2.default.trace.getTracer(package_default.name, package_default.version);
1116
1444
  }
1117
1445
  isActive() {
1118
1446
  return this.active;
@@ -1132,7 +1460,22 @@ class ServiceInvocationSupervisor {
1132
1460
  }
1133
1461
  this.active = true;
1134
1462
  const criBase = this.serviceIdentifier.cri().baseResource();
1135
- this.methodSubscription = this._eventBus.observe(criBase).subscribe({
1463
+ this.methodSubscription = this.subscribeAt(criBase);
1464
+ this.log.info(`ServiceInvocationSupervisor started for ${criBase}`);
1465
+ if (this.serviceIdentifier.scope && this.scopeOptionalMethods.size > 0) {
1466
+ const unscopedBase = this.serviceIdentifier.unscopedCri().baseResource();
1467
+ this.unscopedSubscription = this.subscribeAt(unscopedBase);
1468
+ this.log.info(`ServiceInvocationSupervisor also listening for ScopeOptional methods at ${unscopedBase}`);
1469
+ }
1470
+ this.connectionEndedSubscription = this._eventBus.connectionEnded.subscribe(() => {
1471
+ this.connectionGeneration++;
1472
+ for (const stream of this.activeStreams.values()) {
1473
+ stream.subscription.unsubscribe();
1474
+ }
1475
+ });
1476
+ }
1477
+ subscribeAt(criBase) {
1478
+ return this._eventBus.observe(criBase).subscribe({
1136
1479
  next: async (event) => {
1137
1480
  await this.processEvent(event);
1138
1481
  },
@@ -1145,7 +1488,6 @@ class ServiceInvocationSupervisor {
1145
1488
  this.active = false;
1146
1489
  }
1147
1490
  });
1148
- this.log.info(`ServiceInvocationSupervisor started for ${criBase}`);
1149
1491
  }
1150
1492
  stop() {
1151
1493
  if (!this.active) {
@@ -1154,6 +1496,15 @@ class ServiceInvocationSupervisor {
1154
1496
  this.active = false;
1155
1497
  this.methodSubscription?.unsubscribe();
1156
1498
  this.methodSubscription = null;
1499
+ this.unscopedSubscription?.unsubscribe();
1500
+ this.unscopedSubscription = null;
1501
+ this.connectionEndedSubscription?.unsubscribe();
1502
+ this.connectionEndedSubscription = null;
1503
+ const serviceName = this.serviceIdentifier.qualifiedName();
1504
+ for (const stream of this.activeStreams.values()) {
1505
+ this.handleException(stream.request, new Error(`Service ${serviceName} stopped while producing the stream`));
1506
+ stream.subscription.unsubscribe();
1507
+ }
1157
1508
  this.log.info("ServiceInvocationSupervisor stopped");
1158
1509
  }
1159
1510
  buildMethodMap(serviceInstance) {
@@ -1193,10 +1544,19 @@ class ServiceInvocationSupervisor {
1193
1544
  if (!correlationId) {
1194
1545
  throw new Error("Streaming control plane messages require a CORRELATION_ID_HEADER");
1195
1546
  }
1196
- this.log.trace(`Processing control event for correlationId: ${correlationId}`);
1547
+ const control = event.getHeader("control" /* CONTROL_HEADER */);
1548
+ this.log.trace(`Processing control event ${control} for correlationId: ${correlationId}`);
1549
+ const stream = this.activeStreams.get(correlationId);
1550
+ if (stream) {
1551
+ stream.subscription.unsubscribe();
1552
+ if (control !== "cancel" /* CONTROL_VALUE_CANCEL */) {
1553
+ throw new Error(`Unknown control header value ${control}`);
1554
+ }
1555
+ }
1197
1556
  }
1198
1557
  async processInvocationRequest(event) {
1199
- const path = createCRI(event.cri).path();
1558
+ const incomingCri = createCRI(event.cri);
1559
+ const path = incomingCri.path();
1200
1560
  if (!path) {
1201
1561
  throw new Error("The methodId must not be blank");
1202
1562
  }
@@ -1204,49 +1564,167 @@ class ServiceInvocationSupervisor {
1204
1564
  if (!handlerMethod) {
1205
1565
  throw new Error(`No method resolved for methodId ${path}`);
1206
1566
  }
1567
+ if (this.serviceIdentifier.scope && !incomingCri.hasScope() && !this.scopeOptionalMethods.has(path)) {
1568
+ throw new Error(`Method ${path} of ${this.serviceIdentifier.qualifiedName()} requires a scoped invocation naming the service instance`);
1569
+ }
1207
1570
  const methodName = path;
1208
- const args = this.argumentResolver.resolveArguments(event);
1209
- const injectContext = receivesContext(this.serviceInstance, methodName);
1210
- let context2 = {};
1211
- const interceptor = this.interceptorProvider();
1212
- if (interceptor) {
1571
+ const span = this.startInvocationSpan(event, methodName);
1572
+ const generation = this.connectionGeneration;
1573
+ try {
1574
+ const args = this.argumentResolver.resolveArguments(event);
1575
+ const injectContext = receivesContext(this.serviceInstance, methodName);
1576
+ let serviceContext = {};
1577
+ const sender = event.getHeader("sender" /* SENDER_HEADER */);
1578
+ if (sender) {
1579
+ serviceContext.participant = JSON.parse(sender);
1580
+ }
1581
+ const interceptor = this.interceptorProvider();
1582
+ if (interceptor) {
1583
+ try {
1584
+ serviceContext = await interceptor.intercept(event, serviceContext);
1585
+ } catch (e) {
1586
+ this.log.error(`Interceptor failed to create context for event: ${JSON.stringify(event)}`, e);
1587
+ if (this.replyOwed(generation)) {
1588
+ this.handleException(event, new Error("Internal server error"));
1589
+ }
1590
+ this.failSpan(span, e);
1591
+ return;
1592
+ }
1593
+ }
1594
+ if (injectContext) {
1595
+ args.push(serviceContext);
1596
+ }
1597
+ const expectedArgsCount = handlerMethod.length;
1598
+ if (args.length !== expectedArgsCount) {
1599
+ throw new Error(`Argument count mismatch for method ${path}: expected ${expectedArgsCount}, got ${args.length}`);
1600
+ }
1601
+ let result;
1213
1602
  try {
1214
- context2 = await interceptor.intercept(event, context2);
1603
+ result = import_api2.context.with(import_api2.trace.setSpan(import_api2.context.active(), span), () => handlerMethod(...args));
1604
+ if (result instanceof Promise) {
1605
+ result.then((resolved) => this.processMethodInvocationResult(event, resolved, span, generation), (error) => this.failInvocation(event, error, span, generation)).catch((e) => {
1606
+ this.failInvocation(event, e, span, generation);
1607
+ });
1608
+ } else {
1609
+ this.processMethodInvocationResult(event, result, span, generation);
1610
+ }
1215
1611
  } catch (e) {
1216
- this.log.error(`Interceptor failed to create context for event: ${JSON.stringify(event)}`, e);
1217
- this.handleException(event, new Error("Internal server error"));
1218
- return;
1612
+ this.failInvocation(event, e, span, generation);
1219
1613
  }
1614
+ } catch (e) {
1615
+ this.failSpan(span, e);
1616
+ throw e;
1617
+ }
1618
+ }
1619
+ startInvocationSpan(event, methodName) {
1620
+ const carrier = {};
1621
+ for (const [key, value] of event.headers.entries()) {
1622
+ carrier[key] = value;
1623
+ }
1624
+ const serviceName = this.serviceIdentifier.qualifiedName();
1625
+ return this.tracer.startSpan(`${this.serviceIdentifier.name}/${methodName}`, {
1626
+ kind: import_api2.SpanKind.SERVER,
1627
+ attributes: {
1628
+ "rpc.system": "kinotic",
1629
+ "rpc.service": serviceName,
1630
+ "rpc.method": methodName
1631
+ }
1632
+ }, import_api2.propagation.extract(import_api2.context.active(), carrier));
1633
+ }
1634
+ failSpan(span, error) {
1635
+ span.recordException(error);
1636
+ span.setStatus({ code: import_api2.SpanStatusCode.ERROR });
1637
+ span.end();
1638
+ }
1639
+ replyOwed(generation) {
1640
+ return generation === this.connectionGeneration;
1641
+ }
1642
+ failInvocation(event, error, span, generation) {
1643
+ if (this.replyOwed(generation)) {
1644
+ this.handleException(event, error);
1645
+ }
1646
+ this.failSpan(span, error);
1647
+ }
1648
+ processMethodInvocationResult(event, result, span, generation) {
1649
+ if (!this.replyOwed(generation)) {
1650
+ span.end();
1651
+ } else if (import_rxjs3.isObservable(result)) {
1652
+ this.streamResult(event, result, span);
1653
+ } else {
1654
+ const reply = this.returnValueConverter.convert(event.headers, result);
1655
+ reply.setHeader("control" /* CONTROL_HEADER */, "complete" /* CONTROL_VALUE_COMPLETE */);
1656
+ this.sendReply(reply);
1657
+ span.end();
1220
1658
  }
1221
- if (injectContext) {
1222
- args.push(context2);
1659
+ }
1660
+ streamResult(event, stream, span) {
1661
+ const correlationId = event.getHeader("__correlation-id" /* CORRELATION_ID_HEADER */);
1662
+ if (!correlationId) {
1663
+ throw new Error("Streaming results require a CORRELATION_ID_HEADER to be set");
1664
+ }
1665
+ let subscription = null;
1666
+ let failed = false;
1667
+ subscription = stream.pipe(import_operators3.finalize(() => {
1668
+ this.activeStreams.delete(correlationId);
1669
+ span.end();
1670
+ })).subscribe({
1671
+ next: (value) => {
1672
+ if (failed) {
1673
+ return;
1674
+ }
1675
+ try {
1676
+ const reply = this.returnValueConverter.convert(event.headers, value);
1677
+ reply.setHeader("__origin-cri" /* ORIGIN_CRI_HEADER */, event.cri);
1678
+ this.sendReply(reply);
1679
+ } catch (e) {
1680
+ failed = true;
1681
+ this.handleException(event, e);
1682
+ span.recordException(e);
1683
+ span.setStatus({ code: import_api2.SpanStatusCode.ERROR });
1684
+ subscription?.unsubscribe();
1685
+ }
1686
+ },
1687
+ error: (error) => {
1688
+ if (failed) {
1689
+ return;
1690
+ }
1691
+ this.handleException(event, error);
1692
+ span.recordException(error);
1693
+ span.setStatus({ code: import_api2.SpanStatusCode.ERROR });
1694
+ },
1695
+ complete: () => {
1696
+ if (failed) {
1697
+ return;
1698
+ }
1699
+ this.sendReply(Util.createReplyEvent(event.headers, new Map([["control" /* CONTROL_HEADER */, "complete" /* CONTROL_VALUE_COMPLETE */]])));
1700
+ }
1701
+ });
1702
+ if (failed) {
1703
+ subscription.unsubscribe();
1223
1704
  }
1224
- const expectedArgsCount = handlerMethod.length;
1225
- if (args.length !== expectedArgsCount) {
1226
- throw new Error(`Argument count mismatch for method ${path}: expected ${expectedArgsCount}, got ${args.length}`);
1705
+ if (!subscription.closed) {
1706
+ this.activeStreams.set(correlationId, { request: event, subscription });
1227
1707
  }
1228
- let result;
1708
+ }
1709
+ sendReply(event) {
1229
1710
  try {
1230
- result = handlerMethod(...args);
1231
- if (result instanceof Promise) {
1232
- result.then((resolved) => this.processMethodInvocationResult(event, resolved), (error) => this.handleException(event, error));
1233
- } else {
1234
- this.processMethodInvocationResult(event, result);
1235
- }
1711
+ this._eventBus.send(event);
1236
1712
  } catch (e) {
1237
- this.handleException(event, e);
1713
+ this.log.warn(`Could not send reply to ${event.cri}`, e);
1238
1714
  }
1239
1715
  }
1240
- processMethodInvocationResult(event, result) {
1241
- const outgoingEvent = this.returnValueConverter.convert(event.headers, result);
1242
- this._eventBus.send(outgoingEvent);
1243
- }
1244
1716
  handleException(event, error) {
1245
- const errorEvent = Util.createReplyEvent(event.headers, new Map([
1246
- ["error" /* ERROR_HEADER */, error.message || "Unknown error"],
1247
- ["content-type" /* CONTENT_TYPE_HEADER */, "application/json"]
1248
- ]), new TextEncoder().encode(JSON.stringify({ message: error.message })));
1249
- this._eventBus.send(errorEvent);
1717
+ try {
1718
+ const errorMessage = error?.message || "Unknown error";
1719
+ const exceptionName = error instanceof Error ? error.constructor.name : "Error";
1720
+ const errorEvent = Util.createReplyEvent(event.headers, new Map([
1721
+ ["error" /* ERROR_HEADER */, errorMessage],
1722
+ ["content-type" /* CONTENT_TYPE_HEADER */, "application/json"]
1723
+ ]), new TextEncoder().encode(JSON.stringify({ exceptionName, exceptionClass: exceptionName, errorMessage })));
1724
+ this.sendReply(errorEvent);
1725
+ } catch (e) {
1726
+ this.log.warn(`Could not build the error reply for ${event.cri}`, e);
1727
+ }
1250
1728
  }
1251
1729
  validateReplyTo(event) {
1252
1730
  const replyTo = event.getHeader("reply-to" /* REPLY_TO_HEADER */);
@@ -1267,97 +1745,9 @@ class ServiceInvocationSupervisor {
1267
1745
  }
1268
1746
 
1269
1747
  // packages/core/src/api/ServiceRegistry.ts
1270
- var import_api2 = __toESM(require("@opentelemetry/api"));
1748
+ var import_api3 = __toESM(require("@opentelemetry/api"));
1271
1749
  var import_semantic_conventions = require("@opentelemetry/semantic-conventions");
1272
- var import_operators2 = require("rxjs/operators");
1273
- // packages/core/package.json
1274
- var package_default = {
1275
- name: "@kinotic-ai/core",
1276
- version: "5.0.0-beta.2",
1277
- type: "module",
1278
- files: [
1279
- "dist"
1280
- ],
1281
- module: "./dist/index.js",
1282
- main: "./dist/index.cjs",
1283
- types: "./dist/index.d.ts",
1284
- exports: {
1285
- ".": {
1286
- import: {
1287
- types: "./dist/index.d.ts",
1288
- default: "./dist/index.js"
1289
- },
1290
- require: {
1291
- types: "./dist/index.d.cts",
1292
- default: "./dist/index.cjs"
1293
- }
1294
- },
1295
- "./node": {
1296
- import: {
1297
- types: "./dist/node/index.d.ts",
1298
- default: "./dist/node/index.js"
1299
- },
1300
- require: {
1301
- types: "./dist/node/index.d.cts",
1302
- default: "./dist/node/index.cjs"
1303
- }
1304
- },
1305
- "./package.json": "./package.json"
1306
- },
1307
- homepage: "https://github.com/kinotic-ai/kinotic",
1308
- license: "Elastic License 2.0",
1309
- publishConfig: {
1310
- access: "public"
1311
- },
1312
- scripts: {
1313
- "type-check": "tsc --noEmit",
1314
- test: "vitest run",
1315
- coverage: "vitest run --coverage",
1316
- "ui-test": "vitest --ui --coverage.enabled=true --mode development"
1317
- },
1318
- devDependencies: {
1319
- "@opentelemetry/exporter-trace-otlp-grpc": "^0.214.0",
1320
- "@opentelemetry/resources": "^2.6.1",
1321
- "@opentelemetry/sdk-metrics": "^2.6.1",
1322
- "@opentelemetry/sdk-node": "^0.214.0",
1323
- "@opentelemetry/sdk-trace-node": "^2.6.1",
1324
- "@types/node": "^25.6.0",
1325
- "@types/uuid": "^11.0.0",
1326
- "@types/ws": "^8.18.0",
1327
- "@vitest/coverage-v8": "^4.1.4",
1328
- "@vitest/runner": "^4.1.4",
1329
- "@vitest/ui": "^4.1.4",
1330
- allure: "^3.4.1",
1331
- "allure-vitest": "^3.7.1",
1332
- dotenv: "^17.4.1",
1333
- "properties-file": "^4.0.0",
1334
- testcontainers: "^11.14.0",
1335
- tslib: "^2.8.1",
1336
- typescript: "^6.0.2",
1337
- vitest: "^4.1.4",
1338
- ws: "^8.20.0"
1339
- },
1340
- dependencies: {
1341
- "@opentelemetry/api": "^1.9.1",
1342
- "@opentelemetry/semantic-conventions": "^1.40.0",
1343
- "@stomp/rx-stomp": "^2.4.0",
1344
- "@stomp/stompjs": "^7.3.0",
1345
- "@types/debug": "^4.1.13",
1346
- debug: "^4.4.3",
1347
- "p-tap": "^4.0.0",
1348
- rxjs: "^7.8.2",
1349
- "typescript-optional": "3.0.0-alpha.3",
1350
- uuid: "^13.0.0",
1351
- ws: "^8.18.0"
1352
- },
1353
- peerDependenciesMeta: {
1354
- typescript: {
1355
- optional: true
1356
- }
1357
- }
1358
- };
1359
-
1360
- // packages/core/src/api/ServiceRegistry.ts
1750
+ var import_operators4 = require("rxjs/operators");
1361
1751
  class JsonEventFactory {
1362
1752
  create(cri, args) {
1363
1753
  const event = new Event(cri);
@@ -1391,12 +1781,63 @@ class TextEventFactory {
1391
1781
  return event;
1392
1782
  }
1393
1783
  }
1784
+ var SERVICE_DIRECTORY_SERVICE = "app-api~org.kinotic.app.api.services.ServiceDirectoryService";
1785
+ var APPLICATION_ZONE = /^app\.[^.]+\.([^.]+)(\.|$)/;
1786
+ var declaredDefinitions = new Map;
1787
+ function declareServiceDefinitions(definitions) {
1788
+ for (const definition of definitions) {
1789
+ declaredDefinitions.set(qualifiedNameOf(definition.namespace, definition.name), definition);
1790
+ }
1791
+ }
1792
+ function qualifiedNameOf(namespace, name) {
1793
+ return namespace ? `${namespace}.${name}` : name;
1794
+ }
1795
+ function servedFunctions(serviceInstance) {
1796
+ const ret = new Set;
1797
+ let proto = Object.getPrototypeOf(serviceInstance);
1798
+ while (proto && proto !== Object.prototype) {
1799
+ for (const key of Object.getOwnPropertyNames(proto)) {
1800
+ const descriptor = Object.getOwnPropertyDescriptor(proto, key);
1801
+ if (typeof descriptor?.value === "function" && key !== "constructor") {
1802
+ ret.add(key);
1803
+ }
1804
+ }
1805
+ proto = Object.getPrototypeOf(proto);
1806
+ }
1807
+ return [...ret].sort();
1808
+ }
1809
+ function directoryEntryOf(serviceInstance, serviceIdentifier) {
1810
+ let ret = null;
1811
+ const application = serviceIdentifier.zone ? APPLICATION_ZONE.exec(serviceIdentifier.zone) : null;
1812
+ if (application) {
1813
+ const qualifiedName = qualifiedNameOf(serviceIdentifier.namespace, serviceIdentifier.name);
1814
+ const definition = declaredDefinitions.get(qualifiedName);
1815
+ if (definition) {
1816
+ const declared = definition.functions.map((f) => f.name).sort();
1817
+ const served = servedFunctions(serviceInstance);
1818
+ if (declared.join() !== served.join()) {
1819
+ throw new Error(`${qualifiedName} serves the functions [${served}] but its definition declares [${declared}];` + " run kinotic sync and import the generated ServiceDefinitions module");
1820
+ }
1821
+ ret = {
1822
+ applicationId: application[1],
1823
+ zone: serviceIdentifier.zone,
1824
+ version: serviceIdentifier.version ?? null,
1825
+ advertised: isAdvertised(serviceInstance),
1826
+ serviceDefinition: definition
1827
+ };
1828
+ } else if (declaresAuthzResource(serviceInstance)) {
1829
+ throw new Error(`${qualifiedName} declares a resource but the project declares no definition for it;` + " run kinotic sync and import the generated ServiceDefinitions module");
1830
+ }
1831
+ }
1832
+ return ret;
1833
+ }
1394
1834
 
1395
1835
  class ServiceRegistry {
1396
1836
  _eventBus;
1397
1837
  supervisors = new Map;
1838
+ entries = new Map;
1398
1839
  contextInterceptor = null;
1399
- debugLogger = import_debug3.default("kinoitc:serviceRegistry");
1840
+ debugLogger = import_debug3.default("kinotic:serviceRegistry");
1400
1841
  constructor(eventBus) {
1401
1842
  this._eventBus = eventBus;
1402
1843
  }
@@ -1416,9 +1857,16 @@ class ServiceRegistry {
1416
1857
  const criString = serviceIdentifier.cri().raw();
1417
1858
  if (!this.supervisors.has(criString)) {
1418
1859
  this.debugLogger(`Registering service for CRI: ${criString}`);
1860
+ const entry = directoryEntryOf(service, serviceIdentifier);
1419
1861
  const supervisor = new ServiceInvocationSupervisor(serviceIdentifier, service, this.eventBus, () => this.contextInterceptor);
1420
1862
  this.supervisors.set(criString, supervisor);
1421
1863
  supervisor.start();
1864
+ if (entry) {
1865
+ this.entries.set(criString, entry);
1866
+ if (this.eventBus.isConnected()) {
1867
+ this.registerEntry(entry).catch((error) => this.debugLogger(`Failed to register ${criString} in the directory`, error));
1868
+ }
1869
+ }
1422
1870
  }
1423
1871
  }
1424
1872
  unRegister(serviceIdentifier) {
@@ -1428,8 +1876,18 @@ class ServiceRegistry {
1428
1876
  this.debugLogger(`Unregistering service for CRI: ${criString}`);
1429
1877
  supervisor.stop();
1430
1878
  this.supervisors.delete(criString);
1879
+ this.entries.delete(criString);
1431
1880
  }
1432
1881
  }
1882
+ async registerEntries() {
1883
+ for (const entry of this.entries.values()) {
1884
+ await this.registerEntry(entry);
1885
+ }
1886
+ }
1887
+ async registerEntry(entry) {
1888
+ this.debugLogger(`Registering ${entry.zone}~${qualifiedNameOf(entry.serviceDefinition.namespace, entry.serviceDefinition.name)} in the directory`);
1889
+ await this.serviceProxy(SERVICE_DIRECTORY_SERVICE).invoke("register", [entry]);
1890
+ }
1433
1891
  registerContextInterceptor(interceptor) {
1434
1892
  this.contextInterceptor = interceptor;
1435
1893
  }
@@ -1446,24 +1904,24 @@ class ServiceProxy {
1446
1904
  }
1447
1905
  this.serviceIdentifier = serviceIdentifier;
1448
1906
  this.serviceRegistry = serviceRegistry;
1449
- this.tracer = import_api2.default.trace.getTracer("kinoitc.client", package_default.version);
1907
+ this.tracer = import_api3.default.trace.getTracer(package_default.name, package_default.version);
1450
1908
  }
1451
1909
  invoke(methodIdentifier, args, scope, eventFactory) {
1452
1910
  return this.tracer.startActiveSpan(`${this.serviceIdentifier}/${methodIdentifier}`, {
1453
- kind: import_api2.SpanKind.CLIENT
1911
+ kind: import_api3.SpanKind.CLIENT
1454
1912
  }, async (span) => {
1455
1913
  if (scope) {
1456
- span.setAttribute("kinoitc.scope", scope);
1914
+ span.setAttribute("kinotic.scope", scope);
1457
1915
  }
1458
- span.setAttribute("rpc.system", "kinoitc");
1916
+ span.setAttribute("rpc.system", "kinotic");
1459
1917
  span.setAttribute("rpc.service", this.serviceIdentifier);
1460
1918
  span.setAttribute("rpc.method", methodIdentifier);
1461
- return this.__invokeStream(false, methodIdentifier, args, scope, eventFactory).pipe(import_operators2.first()).toPromise().then(async (value) => {
1919
+ return this.__invokeStream(false, methodIdentifier, args, scope, eventFactory).pipe(import_operators4.first()).toPromise().then(async (value) => {
1462
1920
  span.end();
1463
1921
  return value;
1464
1922
  }, async (ex) => {
1465
1923
  span.recordException(ex);
1466
- span.setStatus({ code: import_api2.SpanStatusCode.ERROR });
1924
+ span.setStatus({ code: import_api3.SpanStatusCode.ERROR });
1467
1925
  span.end();
1468
1926
  throw ex;
1469
1927
  });
@@ -1479,13 +1937,13 @@ class ServiceProxy {
1479
1937
  eventFactoryToUse = eventFactory;
1480
1938
  }
1481
1939
  let eventBusToUse = this.serviceRegistry.eventBus;
1482
- const span = import_api2.default.trace.getActiveSpan();
1940
+ const span = import_api3.default.trace.getActiveSpan();
1483
1941
  if (span) {
1484
1942
  span.setAttribute(import_semantic_conventions.ATTR_SERVER_ADDRESS, eventBusToUse.serverInfo?.host || "unknown");
1485
1943
  span.setAttribute(import_semantic_conventions.ATTR_SERVER_PORT, eventBusToUse.serverInfo?.port || "unknown");
1486
1944
  }
1487
1945
  let event = eventFactoryToUse.create(cri, args);
1488
- return eventBusToUse.requestStream(event, sendControlEvents).pipe(import_operators2.map((value) => {
1946
+ return eventBusToUse.requestStream(event, sendControlEvents).pipe(import_operators4.map((value) => {
1489
1947
  const contentType = value.getHeader("content-type" /* CONTENT_TYPE_HEADER */);
1490
1948
  if (contentType !== undefined) {
1491
1949
  if (contentType === "application/json" /* CONTENT_JSON */) {
@@ -1521,8 +1979,10 @@ class KinoticSingleton {
1521
1979
  this._eventBus = eventBus;
1522
1980
  this.serviceRegistry.eventBus = eventBus;
1523
1981
  }
1524
- connect(options) {
1525
- return this._eventBus.connect(Util.resolveConnectOptions(options));
1982
+ async connect(options) {
1983
+ const ret = await this._eventBus.connect(Util.resolveConnectOptions(options));
1984
+ await this.serviceRegistry.registerEntries();
1985
+ return ret;
1526
1986
  }
1527
1987
  disconnect(force) {
1528
1988
  return this._eventBus.disconnect(force);
@@ -1643,6 +2103,9 @@ class CrudServiceProxy {
1643
2103
  deleteById(id) {
1644
2104
  return this.serviceProxy.invoke("deleteById", [id]);
1645
2105
  }
2106
+ deleteByIdSync(id) {
2107
+ return this.serviceProxy.invoke("deleteByIdSync", [id]);
2108
+ }
1646
2109
  async findAll(pageable) {
1647
2110
  const page = await this.findAllSinglePage(pageable);
1648
2111
  return new FindAllIterablePage(pageable, page, this);
@@ -1765,32 +2228,11 @@ class Order {
1765
2228
  class Sort {
1766
2229
  orders = [];
1767
2230
  }
1768
- // packages/core/src/api/security/BasicCredentialsResolver.ts
1769
- class BasicCredentialsResolver {
1770
- name = "BasicCredentialsResolver";
1771
- credentials;
1772
- constructor(clientId, clientSecret, organizationId, applicationId) {
1773
- const authHeaders = { clientId, clientSecret };
1774
- if (organizationId != null)
1775
- authHeaders.organizationId = organizationId;
1776
- if (applicationId != null)
1777
- authHeaders.applicationId = applicationId;
1778
- this.credentials = { authHeaders, organizationId, applicationId };
1779
- }
1780
- async resolve(_server) {
1781
- return this.credentials;
1782
- }
1783
- }
1784
- // packages/core/src/api/security/BearerCredentialsResolver.ts
1785
- class BearerCredentialsResolver {
1786
- name = "BearerCredentialsResolver";
1787
- token;
1788
- constructor(token) {
1789
- this.token = token;
1790
- }
1791
- async resolve(_server) {
1792
- const token = typeof this.token === "function" ? await this.token() : this.token;
1793
- return { authHeaders: { Authorization: `Bearer ${token}` } };
2231
+ // packages/core/src/api/security/AuthorizationException.ts
2232
+ class AuthorizationException extends Error {
2233
+ constructor(message = "Access denied") {
2234
+ super(message);
2235
+ this.name = "AuthorizationException";
1794
2236
  }
1795
2237
  }
1796
2238
  // packages/core/src/api/security/ConnectedInfo.ts