@kinotic-ai/core 5.0.0-beta.1 → 5.0.0-beta.3

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
@@ -69,12 +69,14 @@ __export(exports_src, {
69
69
  receivesContext: () => receivesContext,
70
70
  isAdvertised: () => isAdvertised,
71
71
  createCRI: () => createCRI,
72
- createAuthenticatedWebSocketFactory: () => createAuthenticatedWebSocketFactory,
72
+ buildServerUrl: () => buildServerUrl,
73
+ buildBrokerUrl: () => buildBrokerUrl,
73
74
  Zone: () => Zone,
74
75
  Version: () => Version,
75
76
  TextEventFactory: () => TextEventFactory,
76
77
  Sort: () => Sort,
77
78
  SessionKeepAliveMode: () => SessionKeepAliveMode,
79
+ SessionCredentialsResolver: () => SessionCredentialsResolver,
78
80
  ServiceRegistry: () => ServiceRegistry,
79
81
  ServerInfo: () => ServerInfo,
80
82
  Scope: () => Scope,
@@ -91,6 +93,7 @@ __export(exports_src, {
91
93
  EventConstants: () => EventConstants,
92
94
  EventBus: () => EventBus,
93
95
  Event: () => Event,
96
+ EnvCredentialsResolver: () => EnvCredentialsResolver,
94
97
  Direction: () => Direction,
95
98
  DefaultCRI: () => DefaultCRI,
96
99
  DataSourceUtils: () => DataSourceUtils,
@@ -98,32 +101,32 @@ __export(exports_src, {
98
101
  CrudServiceProxyFactory: () => CrudServiceProxyFactory,
99
102
  CrudServiceProxy: () => CrudServiceProxy,
100
103
  Context: () => Context,
101
- ConnectionInfo: () => ConnectionInfo,
102
104
  ConnectedInfo: () => ConnectedInfo,
103
- BearerTokenAuthProvider: () => BearerTokenAuthProvider,
104
- BasicAuthProvider: () => BasicAuthProvider,
105
+ ChainedCredentialsResolver: () => ChainedCredentialsResolver,
106
+ BearerCredentialsResolver: () => BearerCredentialsResolver,
107
+ BasicCredentialsResolver: () => BasicCredentialsResolver,
105
108
  AbstractIterablePage: () => AbstractIterablePage
106
109
  });
107
110
  module.exports = __toCommonJS(exports_src);
108
111
 
109
- // packages/core/src/api/ConnectionInfo.ts
112
+ // packages/core/src/api/ConnectOptions.ts
110
113
  class ServerInfo {
111
114
  host;
112
115
  port;
113
116
  useSSL;
114
117
  }
118
+ function buildServerUrl(server, scheme) {
119
+ return scheme + (server.useSSL ? "s" : "") + "://" + server.host + (server.port ? ":" + server.port : "");
120
+ }
121
+ function buildBrokerUrl(server) {
122
+ return buildServerUrl(server, "ws") + "/v1";
123
+ }
115
124
  var SessionKeepAliveMode;
116
125
  ((SessionKeepAliveMode2) => {
117
126
  SessionKeepAliveMode2["NONE"] = "NONE";
118
127
  SessionKeepAliveMode2["ACTIVITY"] = "ACTIVITY";
119
128
  SessionKeepAliveMode2["CONNECTION"] = "CONNECTION";
120
129
  })(SessionKeepAliveMode ||= {});
121
-
122
- class ConnectionInfo extends ServerInfo {
123
- webSocketFactory;
124
- maxConnectionAttempts;
125
- sessionKeepAlive = "ACTIVITY" /* ACTIVITY */;
126
- }
127
130
  // packages/core/src/api/event/IEventBus.ts
128
131
  var EventConstants;
129
132
  ((EventConstants2) => {
@@ -154,34 +157,6 @@ var EventConstants;
154
157
  EventConstants2["TRACESTATE_HEADER"] = "tracestate";
155
158
  })(EventConstants ||= {});
156
159
 
157
- // packages/core/src/internal/api/Util.ts
158
- class Util {
159
- static createReplyEvent(incomingHeaders, headers, body) {
160
- if (!incomingHeaders) {
161
- throw new Error("incomingHeaders cannot be null");
162
- }
163
- const replyCRI = incomingHeaders.get("reply-to" /* REPLY_TO_HEADER */);
164
- if (!replyCRI || replyCRI.trim() === "") {
165
- throw new Error("No reply-to header found, cannot create outgoing message");
166
- }
167
- const newHeaders = new Map;
168
- for (const [key, value] of incomingHeaders) {
169
- if (key.startsWith("__")) {
170
- newHeaders.set(key, value);
171
- }
172
- }
173
- if (headers) {
174
- for (const [key, value] of headers) {
175
- newHeaders.set(key, value);
176
- }
177
- }
178
- return new Event(replyCRI, newHeaders, body || undefined);
179
- }
180
- static buildBrokerUrl(serverInfo) {
181
- return "ws" + (serverInfo.useSSL ? "s" : "") + "://" + serverInfo.host + (serverInfo.port ? ":" + serverInfo.port : "") + "/v1";
182
- }
183
- }
184
-
185
160
  // packages/core/src/internal/api/StompConnectionManager.ts
186
161
  var import_rx_stomp = require("@stomp/rx-stomp");
187
162
  var import_stompjs = require("@stomp/stompjs");
@@ -219,42 +194,50 @@ class StompConnectionManager {
219
194
  get fatalErrors() {
220
195
  return this._fatalErrors;
221
196
  }
222
- activate(connectionInfo) {
223
- return new Promise((resolve, reject) => {
224
- if (!connectionInfo) {
225
- reject("You must supply a valid connectionInfo object");
226
- return;
227
- }
228
- if (!connectionInfo.host) {
229
- reject("No host provided");
230
- return;
197
+ async activate(options) {
198
+ if (!options?.server?.host) {
199
+ throw new Error("No host provided");
200
+ }
201
+ if (this.rxStomp) {
202
+ throw new Error("Stomp connection already active");
203
+ }
204
+ const server = options.server;
205
+ const credentialsResolver = options.credentials;
206
+ let headerAuth = false;
207
+ if (!options.webSocketFactory) {
208
+ if (!credentialsResolver) {
209
+ throw new Error("No credentials supplied and no default resolution applied");
231
210
  }
232
- if (this.rxStomp) {
233
- reject("Stomp connection already active");
234
- return;
211
+ const resolved = await credentialsResolver.resolve(server);
212
+ if (resolved === null) {
213
+ throw new Error("No Kinotic credentials found; consulted: " + credentialsResolver.name);
235
214
  }
215
+ headerAuth = resolved.authHeaders != null;
216
+ }
217
+ return new Promise((resolve, reject) => {
236
218
  this.connectionAttempts = 0;
237
219
  this.initialConnectionSuccessful = false;
238
220
  this.lastWebsocketError = null;
239
221
  this.maxConnectionAttemptsReached = false;
240
- const url = Util.buildBrokerUrl(connectionInfo);
222
+ const url = buildBrokerUrl(server);
241
223
  this.rxStomp = new import_rx_stomp.RxStomp;
242
224
  let preparedSocket = null;
243
- const userWebSocketFactory = connectionInfo.webSocketFactory;
225
+ const userWebSocketFactory = options.webSocketFactory;
226
+ const usesPreparedSocket = userWebSocketFactory != null || headerAuth;
244
227
  const stompConfig = {
245
228
  brokerURL: url,
246
229
  connectHeaders: {
247
- ["session-keep-alive" /* SESSION_KEEP_ALIVE_HEADER */]: connectionInfo.sessionKeepAlive
230
+ ["session-keep-alive" /* SESSION_KEEP_ALIVE_HEADER */]: options.sessionKeepAlive ?? "ACTIVITY" /* ACTIVITY */
248
231
  },
249
232
  heartbeatIncoming: 120000,
250
233
  heartbeatOutgoing: 30000,
251
234
  reconnectDelay: this.INITIAL_RECONNECT_DELAY,
252
235
  maxReconnectDelay: this.MAX_RECONNECT_DELAY,
253
236
  reconnectTimeMode: import_stompjs.ReconnectionTimeMode.EXPONENTIAL,
254
- webSocketFactory: userWebSocketFactory ? () => preparedSocket : undefined,
237
+ webSocketFactory: usesPreparedSocket ? () => preparedSocket : undefined,
255
238
  beforeConnect: async () => {
256
- if (!userWebSocketFactory) {
257
- const sessionCheckUrl = "http" + (connectionInfo.useSSL ? "s" : "") + "://" + connectionInfo.host + (connectionInfo.port ? ":" + connectionInfo.port : "") + SESSION_CHECK_PATH;
239
+ if (!usesPreparedSocket) {
240
+ const sessionCheckUrl = buildServerUrl(server, "http") + SESSION_CHECK_PATH;
258
241
  try {
259
242
  const res = await fetch(sessionCheckUrl, { credentials: "include" });
260
243
  if (res.status === 401) {
@@ -263,9 +246,9 @@ class StompConnectionManager {
263
246
  }
264
247
  } catch {}
265
248
  }
266
- if (connectionInfo?.maxConnectionAttempts) {
249
+ if (options?.maxConnectionAttempts) {
267
250
  this.connectionAttempts++;
268
- if (this.connectionAttempts > connectionInfo.maxConnectionAttempts) {
251
+ if (this.connectionAttempts > options.maxConnectionAttempts) {
269
252
  this.maxConnectionAttemptsReached = true;
270
253
  await this.signalFatal(new Error("Max number of reconnection attempts reached", { cause: this.lastWebsocketError ?? undefined }));
271
254
  return;
@@ -281,6 +264,18 @@ class StompConnectionManager {
281
264
  } catch (e) {
282
265
  await this.signalFatal(new Error("WebSocket factory failed", { cause: e }));
283
266
  }
267
+ } else if (headerAuth) {
268
+ try {
269
+ const resolved = await credentialsResolver.resolve(server);
270
+ if (resolved?.authHeaders == null) {
271
+ await this.signalFatal(new Error("Credentials resolver no longer supplies auth headers: " + credentialsResolver.name));
272
+ } else {
273
+ const WS = WebSocket;
274
+ preparedSocket = new WS(url, { headers: resolved.authHeaders });
275
+ }
276
+ } catch (e) {
277
+ await this.signalFatal(new Error("Credential resolution failed", { cause: e }));
278
+ }
284
279
  }
285
280
  }
286
281
  };
@@ -290,8 +285,12 @@ class StompConnectionManager {
290
285
  };
291
286
  }
292
287
  this.rxStomp.configure(stompConfig);
293
- this.rxStomp.webSocketErrors$.subscribe((value) => {
288
+ this.rxStomp.webSocketErrors$.subscribe(async (value) => {
294
289
  this.lastWebsocketError = value;
290
+ if (options?.maxConnectionAttempts && this.connectionAttempts >= options.maxConnectionAttempts) {
291
+ this.maxConnectionAttemptsReached = true;
292
+ await this.signalFatal(new Error("Max number of reconnection attempts reached", { cause: value ?? undefined }));
293
+ }
295
294
  });
296
295
  this.stompErrorsSubscription = this.rxStomp.stompErrors$.subscribe(async (frame) => {
297
296
  const stompError = new Error(frame.headers["message"], { cause: frame });
@@ -436,15 +435,12 @@ class EventBus {
436
435
  isConnected() {
437
436
  return this.stompConnectionManager.connected;
438
437
  }
439
- connect(connectionInfo) {
438
+ connect(options) {
440
439
  return this.serializeLifecycle(async () => {
441
440
  if (!this.stompConnectionManager.active) {
442
441
  this.cleanup();
443
- const connectedInfo = await this.stompConnectionManager.activate(connectionInfo);
444
- this.serverInfo = new ServerInfo;
445
- this.serverInfo.host = connectionInfo.host;
446
- this.serverInfo.port = connectionInfo.port;
447
- this.serverInfo.useSSL = connectionInfo.useSSL;
442
+ const connectedInfo = await this.stompConnectionManager.activate(options);
443
+ this.serverInfo = { ...options.server };
448
444
  this.replyToCri = this.stompConnectionManager.replyToCri;
449
445
  return connectedInfo;
450
446
  } else {
@@ -610,6 +606,144 @@ class EventBus {
610
606
  }
611
607
  }
612
608
 
609
+ // packages/core/src/api/security/ChainedCredentialsResolver.ts
610
+ class ChainedCredentialsResolver {
611
+ name;
612
+ resolvers;
613
+ constructor(...resolvers) {
614
+ this.resolvers = resolvers;
615
+ this.name = `ChainedCredentialsResolver(${resolvers.map((r) => r.name).join(" -> ")})`;
616
+ }
617
+ async resolve(server) {
618
+ for (const resolver of this.resolvers) {
619
+ const resolved = await resolver.resolve(server);
620
+ if (resolved !== null) {
621
+ return resolved;
622
+ }
623
+ }
624
+ return null;
625
+ }
626
+ }
627
+
628
+ // packages/core/src/api/security/BasicCredentialsResolver.ts
629
+ class BasicCredentialsResolver {
630
+ name = "BasicCredentialsResolver";
631
+ credentials;
632
+ constructor(clientId, clientSecret, organizationId, applicationId) {
633
+ const authHeaders = { clientId, clientSecret };
634
+ if (organizationId != null)
635
+ authHeaders.organizationId = organizationId;
636
+ if (applicationId != null)
637
+ authHeaders.applicationId = applicationId;
638
+ this.credentials = { authHeaders, organizationId, applicationId };
639
+ }
640
+ async resolve(_server) {
641
+ return this.credentials;
642
+ }
643
+ }
644
+
645
+ // packages/core/src/api/security/BearerCredentialsResolver.ts
646
+ class BearerCredentialsResolver {
647
+ name = "BearerCredentialsResolver";
648
+ token;
649
+ constructor(token) {
650
+ this.token = token;
651
+ }
652
+ async resolve(_server) {
653
+ const token = typeof this.token === "function" ? await this.token() : this.token;
654
+ return { authHeaders: { Authorization: `Bearer ${token}` } };
655
+ }
656
+ }
657
+
658
+ // packages/core/src/api/security/EnvCredentialsResolver.ts
659
+ class EnvCredentialsResolver {
660
+ name = "EnvCredentialsResolver";
661
+ async resolve(server) {
662
+ const env = typeof process !== "undefined" ? process.env : undefined;
663
+ let ret = null;
664
+ if (env?.KINOTIC_CLIENT_ID && env?.KINOTIC_CLIENT_SECRET) {
665
+ ret = await new BasicCredentialsResolver(env.KINOTIC_CLIENT_ID, env.KINOTIC_CLIENT_SECRET, env.KINOTIC_ORGANIZATION_ID || undefined, env.KINOTIC_APPLICATION_ID || undefined).resolve(server);
666
+ } else if (env?.KINOTIC_TOKEN) {
667
+ ret = await new BearerCredentialsResolver(env.KINOTIC_TOKEN).resolve(server);
668
+ }
669
+ return ret;
670
+ }
671
+ }
672
+
673
+ // packages/core/src/api/security/SessionCredentialsResolver.ts
674
+ class SessionCredentialsResolver {
675
+ name = "SessionCredentialsResolver";
676
+ async resolve(_server) {
677
+ return typeof document !== "undefined" ? {} : null;
678
+ }
679
+ }
680
+
681
+ // packages/core/src/internal/api/Util.ts
682
+ var DEFAULT_PORT = 58503;
683
+ var DEFAULT_HOST = "api.kinotic.com";
684
+
685
+ class Util {
686
+ static createReplyEvent(incomingHeaders, headers, body) {
687
+ if (!incomingHeaders) {
688
+ throw new Error("incomingHeaders cannot be null");
689
+ }
690
+ const replyCRI = incomingHeaders.get("reply-to" /* REPLY_TO_HEADER */);
691
+ if (!replyCRI || replyCRI.trim() === "") {
692
+ throw new Error("No reply-to header found, cannot create outgoing message");
693
+ }
694
+ const newHeaders = new Map;
695
+ for (const [key, value] of incomingHeaders) {
696
+ if (key.startsWith("__")) {
697
+ newHeaders.set(key, value);
698
+ }
699
+ }
700
+ if (headers) {
701
+ for (const [key, value] of headers) {
702
+ newHeaders.set(key, value);
703
+ }
704
+ }
705
+ return new Event(replyCRI, newHeaders, body || undefined);
706
+ }
707
+ static resolveConnectOptions(options) {
708
+ const opts = options ?? {};
709
+ const server = opts.server ?? {};
710
+ const env = typeof process !== "undefined" ? process.env : undefined;
711
+ const location = typeof window !== "undefined" ? window.location : undefined;
712
+ let host = server.host ?? env?.KINOTIC_SERVER_HOST;
713
+ const hostFromLocation = host == null && location != null;
714
+ const hostDefaulted = host == null && location == null;
715
+ if (host == null) {
716
+ host = location?.hostname ?? DEFAULT_HOST;
717
+ }
718
+ let useSSL = server.useSSL;
719
+ if (useSSL == null) {
720
+ if (env?.KINOTIC_SERVER_USE_SSL != null) {
721
+ useSSL = env.KINOTIC_SERVER_USE_SSL === "true";
722
+ } else if (hostFromLocation) {
723
+ useSSL = location.protocol === "https:";
724
+ } else {
725
+ useSSL = hostDefaulted;
726
+ }
727
+ }
728
+ let port = server.port;
729
+ if (port === undefined) {
730
+ if (env?.KINOTIC_SERVER_PORT != null) {
731
+ port = Number(env.KINOTIC_SERVER_PORT);
732
+ } else if (hostFromLocation) {
733
+ port = location.port ? Number(location.port) : null;
734
+ } else {
735
+ port = useSSL ? null : DEFAULT_PORT;
736
+ }
737
+ }
738
+ return {
739
+ ...opts,
740
+ server: { host, port, useSSL },
741
+ sessionKeepAlive: opts.sessionKeepAlive ?? "ACTIVITY" /* ACTIVITY */,
742
+ credentials: opts.credentials ?? new ChainedCredentialsResolver(new EnvCredentialsResolver, new SessionCredentialsResolver)
743
+ };
744
+ }
745
+ }
746
+
613
747
  // packages/core/src/api/ServiceRegistry.ts
614
748
  var import_debug3 = __toESM(require("debug"));
615
749
 
@@ -1158,7 +1292,7 @@ var import_operators2 = require("rxjs/operators");
1158
1292
  // packages/core/package.json
1159
1293
  var package_default = {
1160
1294
  name: "@kinotic-ai/core",
1161
- version: "5.0.0-beta.1",
1295
+ version: "5.0.0-beta.3",
1162
1296
  type: "module",
1163
1297
  files: [
1164
1298
  "dist"
@@ -1177,6 +1311,16 @@ var package_default = {
1177
1311
  default: "./dist/index.cjs"
1178
1312
  }
1179
1313
  },
1314
+ "./node": {
1315
+ import: {
1316
+ types: "./dist/node/index.d.ts",
1317
+ default: "./dist/node/index.js"
1318
+ },
1319
+ require: {
1320
+ types: "./dist/node/index.d.cts",
1321
+ default: "./dist/node/index.cjs"
1322
+ }
1323
+ },
1180
1324
  "./package.json": "./package.json"
1181
1325
  },
1182
1326
  homepage: "https://github.com/kinotic-ai/kinotic",
@@ -1198,7 +1342,7 @@ var package_default = {
1198
1342
  "@opentelemetry/sdk-trace-node": "^2.6.1",
1199
1343
  "@types/node": "^25.6.0",
1200
1344
  "@types/uuid": "^11.0.0",
1201
- "@types/ws": "^8.18.1",
1345
+ "@types/ws": "^8.18.0",
1202
1346
  "@vitest/coverage-v8": "^4.1.4",
1203
1347
  "@vitest/runner": "^4.1.4",
1204
1348
  "@vitest/ui": "^4.1.4",
@@ -1222,7 +1366,8 @@ var package_default = {
1222
1366
  "p-tap": "^4.0.0",
1223
1367
  rxjs: "^7.8.2",
1224
1368
  "typescript-optional": "3.0.0-alpha.3",
1225
- uuid: "^13.0.0"
1369
+ uuid: "^13.0.0",
1370
+ ws: "^8.18.0"
1226
1371
  },
1227
1372
  peerDependenciesMeta: {
1228
1373
  typescript: {
@@ -1395,8 +1540,8 @@ class KinoticSingleton {
1395
1540
  this._eventBus = eventBus;
1396
1541
  this.serviceRegistry.eventBus = eventBus;
1397
1542
  }
1398
- connect(connectionInfo) {
1399
- return this._eventBus.connect(connectionInfo);
1543
+ connect(options) {
1544
+ return this._eventBus.connect(Util.resolveConnectOptions(options));
1400
1545
  }
1401
1546
  disconnect(force) {
1402
1547
  return this._eventBus.disconnect(force);
@@ -1639,41 +1784,6 @@ class Order {
1639
1784
  class Sort {
1640
1785
  orders = [];
1641
1786
  }
1642
- // packages/core/src/api/security/AuthenticatedWebSocketFactory.ts
1643
- function createAuthenticatedWebSocketFactory(serverInfo, authProvider) {
1644
- const brokerUrl = Util.buildBrokerUrl(serverInfo);
1645
- return async () => {
1646
- const headers = await authProvider.getAuthHeaders();
1647
- const WS = WebSocket;
1648
- return new WS(brokerUrl, { headers });
1649
- };
1650
- }
1651
- // packages/core/src/api/security/BasicAuthProvider.ts
1652
- class BasicAuthProvider {
1653
- authHeader;
1654
- constructor(login, passcode) {
1655
- const bytes = new TextEncoder().encode(`${login}:${passcode}`);
1656
- let binary = "";
1657
- for (const byte of bytes) {
1658
- binary += String.fromCharCode(byte);
1659
- }
1660
- this.authHeader = `Basic ${btoa(binary)}`;
1661
- }
1662
- getAuthHeaders() {
1663
- return { Authorization: this.authHeader };
1664
- }
1665
- }
1666
- // packages/core/src/api/security/BearerTokenAuthProvider.ts
1667
- class BearerTokenAuthProvider {
1668
- token;
1669
- constructor(token) {
1670
- this.token = token;
1671
- }
1672
- async getAuthHeaders() {
1673
- const token = typeof this.token === "function" ? await this.token() : this.token;
1674
- return { Authorization: `Bearer ${token}` };
1675
- }
1676
- }
1677
1787
  // packages/core/src/api/security/ConnectedInfo.ts
1678
1788
  class ConnectedInfo {
1679
1789
  replyToId;