@openfin/cloud-interop-core-api 0.0.1-alpha.fffeb9a → 10.0.0-beta.1d

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/index.mjs ADDED
@@ -0,0 +1,661 @@
1
+ import { Buffer } from 'buffer';
2
+ import mqtt from 'mqtt';
3
+
4
+ class CloudInteropAPIError extends Error {
5
+ code;
6
+ constructor(message = 'An unexpected error has occurred', code = 'UNEXPECTED_ERROR', cause) {
7
+ super(message, { cause: cause });
8
+ this.name = this.constructor.name;
9
+ this.code = code;
10
+ }
11
+ }
12
+ class AuthorizationError extends CloudInteropAPIError {
13
+ constructor(message = 'Not authorized', code = 'ERR_UNAUTHORIZED') {
14
+ super(message, code, undefined);
15
+ }
16
+ }
17
+
18
+ class EventController {
19
+ #eventListeners = new Map();
20
+ addEventListener(type, callback) {
21
+ const listeners = this.#eventListeners.get(type) || [];
22
+ listeners.push(callback);
23
+ this.#eventListeners.set(type, listeners);
24
+ }
25
+ removeEventListener(type, callback) {
26
+ const listeners = this.#eventListeners.get(type) || [];
27
+ const index = listeners.indexOf(callback);
28
+ if (index !== -1) {
29
+ listeners.splice(index, 1);
30
+ }
31
+ this.#eventListeners.set(type, listeners);
32
+ }
33
+ once(type, callback) {
34
+ const listener = (...args) => {
35
+ this.removeEventListener(type, listener);
36
+ // @ts-expect-error - TS doesn't like the spread operator here
37
+ callback(...args);
38
+ };
39
+ this.addEventListener(type, listener);
40
+ }
41
+ emitEvent(type, ...args) {
42
+ const listeners = this.#eventListeners.get(type) || [];
43
+ listeners.forEach((listener) => listener(...args));
44
+ }
45
+ }
46
+
47
+ const isErrorIntentResult = (result) => 'error' in result;
48
+
49
+ const APP_ID_DELIM = '::';
50
+ const getRequestHeaders = (connectionParameters) => {
51
+ const headers = {};
52
+ headers['Content-Type'] = 'application/json';
53
+ if (connectionParameters.authenticationType === 'jwt' && connectionParameters.jwtAuthenticationParameters) {
54
+ const tokenResult = connectionParameters.jwtAuthenticationParameters.jwtRequestCallback();
55
+ if (!tokenResult) {
56
+ throw new Error('jwtRequestCallback must return a token');
57
+ }
58
+ headers['x-of-auth-id'] = connectionParameters.jwtAuthenticationParameters.authenticationId;
59
+ headers['Authorization'] =
60
+ typeof tokenResult === 'string' ? `Bearer ${tokenResult}` : `Bearer ${Buffer.from(JSON.stringify(tokenResult)).toString('base64')}`;
61
+ }
62
+ if (connectionParameters.authenticationType === 'basic' && connectionParameters.basicAuthenticationParameters) {
63
+ const { username, password } = connectionParameters.basicAuthenticationParameters;
64
+ headers['Authorization'] = `Basic ${Buffer.from(`${username}:${password}`).toString('base64')}`;
65
+ }
66
+ return headers;
67
+ };
68
+ /**
69
+ * Encodes all app intents in the format: `appId::sourceId::sessionId`,
70
+ * where sourceId and sessionId are URI encoded
71
+ * @param appIntents
72
+ * @param source
73
+ * @returns
74
+ */
75
+ const encodeAppIntents = (appIntents, source) => appIntents.map((intent) => ({
76
+ ...intent,
77
+ apps: intent.apps.map((app) => ({ ...app, appId: encodeAppId(app.appId, source) })),
78
+ }));
79
+ /**
80
+ * Decodes all app intents by URI decoding the parts previously encoded by `encodeAppIntents`
81
+ * @param appIntents
82
+ * @returns
83
+ */
84
+ const decodeAppIntents = (appIntents) => appIntents.map((intent) => ({
85
+ ...intent,
86
+ apps: intent.apps.map((app) => ({ ...app, appId: decodeAppId(app.appId) })),
87
+ }));
88
+ const encodeAppId = (appIdString, { sessionId, sourceId }) => {
89
+ const id = encodeURIComponent(appIdString);
90
+ const sId = encodeURIComponent(sourceId);
91
+ return `${id}${APP_ID_DELIM}${sId}${APP_ID_DELIM}${sessionId}`;
92
+ };
93
+ const decodeAppId = (appId) => {
94
+ const [encodedAppId, encodedSourceId, sessionId] = appId.split(APP_ID_DELIM);
95
+ const id = decodeURIComponent(encodedAppId);
96
+ const sourceId = decodeURIComponent(encodedSourceId);
97
+ return `${id}${APP_ID_DELIM}${sourceId}${APP_ID_DELIM}${sessionId}`;
98
+ };
99
+ /**
100
+ * Decodes the AppIdentifier to extract the appId, sourceId, and sessionId.
101
+ * @returns an object with:
102
+ * - appId: The appId, or the original appId if unable to parse.
103
+ * - sourceId: The sourceId, or an '' if unable to parse.
104
+ * - sessionId: The sessionId, or an '' if unable to parse.
105
+ */
106
+ const parseCloudAppId = (appId = '') => {
107
+ const originalAppString = typeof appId === 'string' ? appId : (appId.appId ?? '');
108
+ const parts = originalAppString.split(APP_ID_DELIM);
109
+ return {
110
+ appId: parts[0]?.trim() ?? originalAppString,
111
+ sourceId: parts[1]?.trim() ?? '',
112
+ sessionId: parts[2]?.trim() ?? '',
113
+ };
114
+ };
115
+ const getSourceFromSession = (sessionDetails) => ({
116
+ sessionId: sessionDetails.sessionId,
117
+ sourceId: sessionDetails.sourceId,
118
+ userId: sessionDetails.sub,
119
+ orgId: sessionDetails.orgId,
120
+ platformId: sessionDetails.platformId,
121
+ });
122
+
123
+ const MIN_TIMEOUT = 500;
124
+ const DEFAULT_TIMEOUT = 3000;
125
+ const newDiscovery = () => ({
126
+ id: undefined,
127
+ pendingIntentDetailsEvents: [],
128
+ sessionCount: 0,
129
+ responseCount: 0,
130
+ state: 'not-started',
131
+ });
132
+ class IntentController {
133
+ #url;
134
+ #mqttClient;
135
+ #sessionDetails;
136
+ #connectionParams;
137
+ #events;
138
+ #logger;
139
+ #discovery = newDiscovery();
140
+ #discoveryTimeout;
141
+ constructor(url, mqttClient, sessionDetails, connectionParameters, events, logger) {
142
+ this.#url = url;
143
+ this.#mqttClient = mqttClient;
144
+ this.#sessionDetails = sessionDetails;
145
+ this.#connectionParams = connectionParameters;
146
+ this.#events = events;
147
+ this.#logger = logger;
148
+ }
149
+ async startIntentDiscovery(options) {
150
+ if (this.#discovery.state === 'in-progress') {
151
+ throw new Error('Intent discovery already in progress');
152
+ }
153
+ const { timeout = DEFAULT_TIMEOUT, findOptions } = options;
154
+ // clamp min value to 500ms
155
+ const clampedTimeout = Math.max(timeout, MIN_TIMEOUT);
156
+ try {
157
+ const startResponse = await fetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}`, {
158
+ method: 'POST',
159
+ headers: getRequestHeaders(this.#connectionParams),
160
+ body: JSON.stringify({ findOptions }),
161
+ });
162
+ if (!startResponse.ok) {
163
+ throw new Error(`Error creating intent discovery record: ${startResponse.statusText}`);
164
+ }
165
+ // TODO: type this response?
166
+ const json = await startResponse.json();
167
+ this.#discovery.id = json.discoveryId;
168
+ this.#discovery.sessionCount = json.sessionCount;
169
+ this.#discovery.state = 'in-progress';
170
+ if (this.#discovery.sessionCount === 1) {
171
+ // since we have no other connected sessions, we can end discovery immediately
172
+ await this.#endIntentDiscovery(false);
173
+ return;
174
+ }
175
+ // Listen out for discovery results directly sent to us
176
+ await this.#mqttClient.subscribeAsync(`${this.#sessionDetails.sessionRootTopic}/commands/${this.#discovery.id}`);
177
+ this.#discoveryTimeout = setTimeout(() => this.#endIntentDiscovery(), clampedTimeout);
178
+ }
179
+ catch (error) {
180
+ // Clean up any ongoing discoveries
181
+ this.#endIntentDiscovery();
182
+ throw new CloudInteropAPIError('Error starting intent discovery', 'ERR_STARTING_INTENT_DISCOVERY', error);
183
+ }
184
+ }
185
+ async #endIntentDiscovery(mqttUnsubscribe = true) {
186
+ if (this.#discovery.state !== 'in-progress') {
187
+ return;
188
+ }
189
+ if (this.#discoveryTimeout) {
190
+ clearTimeout(this.#discoveryTimeout);
191
+ this.#discoveryTimeout = undefined;
192
+ }
193
+ this.#discovery.state = 'ended';
194
+ // emit our aggregated events
195
+ this.#events.emitEvent('aggregate-intent-details', { responses: this.#discovery.pendingIntentDetailsEvents });
196
+ if (mqttUnsubscribe) {
197
+ // gracefully end discovery
198
+ await this.#mqttClient.unsubscribeAsync(`${this.#sessionDetails.sessionRootTopic}/commands/${this.#discovery.id}`).catch(() => {
199
+ this.#logger('warn', `Error ending intent discovery: could not unsubscribe from discovery id ${this.#discovery.id}`);
200
+ });
201
+ }
202
+ await fetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}/${this.#discovery.id}`, {
203
+ method: 'DELETE',
204
+ headers: getRequestHeaders(this.#connectionParams),
205
+ })
206
+ .then((deleteResponse) => {
207
+ if (!deleteResponse.ok) {
208
+ throw new Error(`Error ending intent discovery: ${deleteResponse.statusText}`);
209
+ }
210
+ })
211
+ .catch((error) => {
212
+ this.#logger('warn', `Error ending intent discovery: ${error}`);
213
+ });
214
+ // clean up
215
+ this.#discovery = newDiscovery();
216
+ }
217
+ async raiseIntent({ raiseOptions, appId }) {
218
+ const targetSessionId = parseCloudAppId(appId).sessionId;
219
+ if (!targetSessionId) {
220
+ // TODO: should we add more info here about the format?
221
+ throw new CloudInteropAPIError(`Invalid AppId specified, must be encoded as a cloud-session app id`, 'ERR_INVALID_TARGET_SESSION_ID');
222
+ }
223
+ const postResponse = await fetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}/sessions/${targetSessionId}`, {
224
+ method: 'POST',
225
+ headers: getRequestHeaders(this.#connectionParams),
226
+ body: JSON.stringify({ raiseOptions }),
227
+ });
228
+ if (!postResponse.ok) {
229
+ // TODO: maybe add a debug flag to print these when dev'ing?
230
+ // console.log(`Error raising intent: ${await postResponse.text()}`);
231
+ throw new CloudInteropAPIError(`Error raising intent`, 'ERR_RAISING_INTENT', new Error(postResponse.statusText));
232
+ }
233
+ }
234
+ async reportAppIntents(discoveryId, intents) {
235
+ intents = encodeAppIntents(intents, getSourceFromSession(this.#sessionDetails));
236
+ try {
237
+ const reportResponse = await fetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}/${discoveryId}`, {
238
+ method: 'POST',
239
+ headers: getRequestHeaders(this.#connectionParams),
240
+ body: JSON.stringify({ intents }),
241
+ });
242
+ if (reportResponse.ok) {
243
+ return true;
244
+ }
245
+ throw new CloudInteropAPIError('Error reporting intents', 'ERR_REPORTING_INTENTS', new Error(reportResponse.statusText));
246
+ }
247
+ catch (error) {
248
+ this.#logger('warn', `Error reporting intents for discovery ID ${discoveryId}: ${error}`);
249
+ }
250
+ return false;
251
+ }
252
+ async sendIntentResult(initiatingSessionId, result) {
253
+ if (!isErrorIntentResult(result)) {
254
+ // cloud-encode the source app id to support chained intent actions over cloud
255
+ // https://fdc3.finos.org/docs/2.0/api/spec#resolution-object -> "Use metadata about the resolving app instance to target a further intent"
256
+ const source = getSourceFromSession(this.#sessionDetails);
257
+ const encoded = encodeAppId(typeof result.source === 'string' ? result.source : result.source.appId, source);
258
+ result.source = typeof result.source === 'string' ? encoded : { ...result.source, appId: encoded };
259
+ }
260
+ const { sessionId } = getSourceFromSession(this.#sessionDetails);
261
+ const resultResponse = await fetch(`${this.#url}/api/intents/${initiatingSessionId}/result/${sessionId}`, {
262
+ method: 'POST',
263
+ headers: getRequestHeaders(this.#connectionParams),
264
+ body: JSON.stringify({ result }),
265
+ });
266
+ if (!resultResponse.ok) {
267
+ throw new CloudInteropAPIError('Error sending intent result', 'ERR_SENDING_INTENT_RESULT', new Error(resultResponse.statusText));
268
+ }
269
+ }
270
+ handleCommandMessage(message) {
271
+ switch (message.command) {
272
+ case 'report-intents': {
273
+ if (message.initiatingSessionId === this.#sessionDetails?.sessionId) {
274
+ // Ignore if this originated from us
275
+ return;
276
+ }
277
+ const { command: _, ...event } = message;
278
+ this.#events.emitEvent('report-intents', event);
279
+ break;
280
+ }
281
+ case 'intent-details': {
282
+ /**
283
+ * We aggregate intent details commands from all connected sessions on the server side
284
+ * to ensure upstream clients don't have to do this. Also given @openfin/cloud-interop
285
+ * exposes FDC3 compliant APIs, there is no concept of streaming available, hence we
286
+ * aggregate the responses here and send them in a synchronous manner.
287
+ */
288
+ const { command: _, ...event } = message;
289
+ // Decode intents before emitting to client
290
+ event.intents = decodeAppIntents(event.intents);
291
+ // always emit individual intent-details events in addition to aggregate-intent-details
292
+ // for flexibility after intent discovery has ended, this can be useful for late-joining
293
+ // clients nearing the timeout
294
+ this.#events.emitEvent('intent-details', event);
295
+ if (message.discoveryId !== this.#discovery.id || this.#discovery.state !== 'in-progress') {
296
+ // Ignore if its any other discovery id for some reason, or
297
+ // if we're not in the middle of a discovery
298
+ return;
299
+ }
300
+ this.#discovery.responseCount += 1;
301
+ this.#logger('debug', `Received intent details from ${message.source.sessionId}, received: ${this.#discovery.responseCount}, out of connected sessions: ${this.#discovery.sessionCount - 1}`);
302
+ this.#discovery.pendingIntentDetailsEvents.push(event);
303
+ const allResponded = this.#discovery.responseCount === this.#discovery.sessionCount - 1;
304
+ if (allResponded) {
305
+ this.#endIntentDiscovery();
306
+ }
307
+ break;
308
+ }
309
+ case 'raise-intent': {
310
+ if (message.targetSessionId === this.#sessionDetails?.sessionId) {
311
+ const { command: _, ...event } = message;
312
+ this.#events.emitEvent('raise-intent', event);
313
+ }
314
+ break;
315
+ }
316
+ case 'intent-result': {
317
+ if (message.initiatingSessionId === this.#sessionDetails?.sessionId) {
318
+ // Return result to originator and end discovery
319
+ const { command: _, ...resultEvent } = message;
320
+ this.#events.emitEvent('intent-result', resultEvent);
321
+ }
322
+ break;
323
+ }
324
+ default: {
325
+ this.#logger('warn', `Unknown command message received:\n${JSON.stringify(message, null, 2)}`);
326
+ break;
327
+ }
328
+ }
329
+ }
330
+ }
331
+
332
+ // Error codes as defined in https://docs.emqx.com/en/cloud/latest/connect_to_deployments/mqtt_client_error_codes.html
333
+ const BadUserNamePasswordError = 134;
334
+ /**
335
+ * Represents a single connection to a Cloud Interop service
336
+ *
337
+ * @public
338
+ * @class
339
+ */
340
+ class CloudInteropAPI {
341
+ #cloudInteropSettings;
342
+ #sessionDetails;
343
+ #mqttClient;
344
+ #reconnectRetryLimit = 30;
345
+ #keepAliveIntervalSeconds = 30;
346
+ #logger = (level, message) => {
347
+ console[level](message);
348
+ };
349
+ #reconnectRetries = 0;
350
+ #connectionParams;
351
+ #attemptingToReconnect = false;
352
+ #events = new EventController();
353
+ #intents;
354
+ constructor(cloudInteropSettings) {
355
+ this.#cloudInteropSettings = cloudInteropSettings;
356
+ }
357
+ get sessionDetails() {
358
+ return this.#sessionDetails;
359
+ }
360
+ get mqttClient() {
361
+ return this.#mqttClient;
362
+ }
363
+ /**
364
+ * Connects and creates a session on the Cloud Interop service
365
+ *
366
+ * @param {ConnectParameters} parameters - The parameters to use to connect
367
+ * @returns {*} {Promise<void>}
368
+ * @memberof CloudInteropAPI
369
+ * @throws {CloudInteropAPIError} - If an error occurs during connection
370
+ * @throws {AuthorizationError} - If the connection is unauthorized
371
+ */
372
+ async connect(parameters) {
373
+ this.#validateConnectParams(parameters);
374
+ this.#connectionParams = parameters;
375
+ this.#reconnectRetryLimit = parameters.reconnectRetryLimit || this.#reconnectRetryLimit;
376
+ this.#keepAliveIntervalSeconds = parameters.keepAliveIntervalSeconds || this.#keepAliveIntervalSeconds;
377
+ this.#logger = parameters.logger || this.#logger;
378
+ const { sourceId, platformId } = this.#connectionParams;
379
+ const createSessionResponse = await fetch(`${this.#cloudInteropSettings.url}/api/sessions`, {
380
+ method: 'POST',
381
+ headers: getRequestHeaders(this.#connectionParams),
382
+ body: JSON.stringify({ sourceId: sourceId.trim(), platformId }),
383
+ });
384
+ if (!createSessionResponse.ok) {
385
+ if (createSessionResponse.status === 401 || createSessionResponse.status === 403) {
386
+ throw new AuthorizationError();
387
+ }
388
+ throw new CloudInteropAPIError();
389
+ }
390
+ if (createSessionResponse.status !== 201) {
391
+ throw new CloudInteropAPIError(`Failed to connect to the Cloud Interop service: ${this.#cloudInteropSettings.url}`, 'ERR_CONNECT', new Error(createSessionResponse.statusText));
392
+ }
393
+ this.#sessionDetails = (await createSessionResponse.json());
394
+ const sessionRootTopic = this.#sessionDetails.sessionRootTopic;
395
+ const clientOptions = {
396
+ keepalive: this.#keepAliveIntervalSeconds,
397
+ clientId: this.#sessionDetails.sessionId,
398
+ clean: true,
399
+ protocolVersion: 5,
400
+ // The "will" message will be published on an unexpected disconnection
401
+ // The server can then tidy up. So it needs every for this client to do that, the session details is perfect
402
+ will: {
403
+ topic: 'interop/lastwill',
404
+ payload: Buffer.from(JSON.stringify(this.#sessionDetails)),
405
+ qos: 0,
406
+ retain: false,
407
+ },
408
+ username: this.#sessionDetails.token,
409
+ };
410
+ this.#mqttClient = await mqtt.connectAsync(this.#sessionDetails.url, clientOptions);
411
+ // TODO: Dynamic intent discovery
412
+ // search for any ongoing discoveries in DB and fire report-intents on self
413
+ this.#logger('log', `Cloud Interop successfully connected to ${this.#cloudInteropSettings.url}`);
414
+ this.#mqttClient.on('error', async (error) => {
415
+ // We will receive errors for each failed reconnection attempt
416
+ // We don't want to disconnect on these else we will never reconnect
417
+ if (!this.#attemptingToReconnect) {
418
+ await this.#disconnect(false);
419
+ }
420
+ if (error instanceof mqtt.ErrorWithReasonCode) {
421
+ switch (error.code) {
422
+ case BadUserNamePasswordError: {
423
+ await this.#disconnect(false);
424
+ this.#logger('warn', `Session expired`);
425
+ this.#events.emitEvent('session-expired');
426
+ return;
427
+ }
428
+ default: {
429
+ this.#logger('error', `Unknown Infrastructure Error Code ${error.code} : ${error.message}${this.#attemptingToReconnect ? ' during reconnection attempt' : ''}`);
430
+ // As we are in the middle of a reconnect, lets not emit an error to cut down on the event noise
431
+ if (!this.#attemptingToReconnect) {
432
+ this.#events.emitEvent('error', new CloudInteropAPIError(`Unknown Infrastructure Error Code ${error.code} : ${error.message}`, 'ERR_INFRASTRUCTURE', error));
433
+ break;
434
+ }
435
+ }
436
+ }
437
+ }
438
+ else {
439
+ this.#logger('error', `Unknown Error${this.#attemptingToReconnect ? ' during reconnection attempt' : ''}: ${error}`);
440
+ // As we are in the middle of a reconnect, lets not emit an error to cut down on the event noise
441
+ if (!this.#attemptingToReconnect) {
442
+ this.#events.emitEvent('error', new CloudInteropAPIError(`Unknown Error`, 'ERR_UNKNOWN', error));
443
+ }
444
+ }
445
+ });
446
+ this.#mqttClient.on('reconnect', () => {
447
+ this.#attemptingToReconnect = true;
448
+ this.#reconnectRetries += 1;
449
+ this.#logger('debug', `Cloud Interop attempting reconnection - ${this.#reconnectRetries}...`);
450
+ if (this.#reconnectRetries === this.#reconnectRetryLimit) {
451
+ this.#logger('warn', `Cloud Interop reached max reconnection attempts - ${this.#reconnectRetryLimit}...`);
452
+ this.#disconnect(true);
453
+ }
454
+ this.#events.emitEvent('reconnecting', this.#reconnectRetries);
455
+ });
456
+ // Does not fire on initial connection, only successful reconnection attempts
457
+ this.#mqttClient.on('connect', () => {
458
+ this.#logger('debug', `Cloud Interop successfully reconnected after ${this.#reconnectRetries} attempts`);
459
+ this.#reconnectRetries = 0;
460
+ this.#attemptingToReconnect = false;
461
+ this.#events.emitEvent('reconnected');
462
+ });
463
+ this.#mqttClient.on('message', (topic, message) => {
464
+ if (!this.#sessionDetails) {
465
+ this.#logger('warn', 'Received message when session not connected');
466
+ return;
467
+ }
468
+ this.#handleMessage(topic, message, this.#sessionDetails);
469
+ });
470
+ // Subscribe to all context groups
471
+ this.#mqttClient.subscribe(`${sessionRootTopic}/context-groups/#`);
472
+ // Listen out for global commands
473
+ this.#mqttClient.subscribe(`${sessionRootTopic}/commands`);
474
+ this.#initControllers(this.#mqttClient, this.#sessionDetails, this.#connectionParams);
475
+ }
476
+ /**
477
+ * Disconnects from the Cloud Interop service
478
+ *
479
+ * @returns {*} {Promise<void>}
480
+ * @memberof CloudInteropAPI
481
+ * @throws {CloudInteropAPIError} - If an error occurs during disconnection
482
+ */
483
+ async disconnect() {
484
+ await this.#disconnect(true);
485
+ }
486
+ /**
487
+ * Publishes a new context for the given context group to the other connected sessions
488
+ *
489
+ * @param {string} contextGroup - The context group to publish to
490
+ * @param {object} context - The context to publish
491
+ * @returns {*} {Promise<void>}
492
+ * @memberof CloudInteropAPI
493
+ */
494
+ async setContext(contextGroup, context) {
495
+ // TODO: make context of type OpenFin.Context
496
+ if (!this.#sessionDetails || !this.#connectionParams) {
497
+ throw new Error('Session not connected');
498
+ }
499
+ if (!this.#mqttClient) {
500
+ throw new Error('MQTT client not connected');
501
+ }
502
+ const payload = {
503
+ context,
504
+ timestamp: Date.now(),
505
+ };
506
+ const postResponse = await fetch(`${this.#cloudInteropSettings.url}/api/context-groups/${this.#sessionDetails.sessionId}/${contextGroup}`, {
507
+ method: 'POST',
508
+ headers: getRequestHeaders(this.#connectionParams),
509
+ body: JSON.stringify(payload),
510
+ });
511
+ if (!postResponse.ok) {
512
+ throw new CloudInteropAPIError(`Error setting context for ${contextGroup}`, 'ERR_SETTING_CONTEXT', new Error(postResponse.statusText));
513
+ }
514
+ }
515
+ /**
516
+ * Starts an intent discovery operation
517
+ *
518
+ * @returns {*} {Promise<void>}
519
+ * @memberof CloudInteropAPI
520
+ * @throws {CloudInteropAPIError} - If an error occurs during intent discovery
521
+ */
522
+ async startIntentDiscovery(options) {
523
+ this.#throwIfNotConnected();
524
+ return this.#intents?.startIntentDiscovery(options);
525
+ }
526
+ async raiseIntent(options) {
527
+ this.#throwIfNotConnected();
528
+ return this.#intents?.raiseIntent(options);
529
+ }
530
+ async reportAppIntents(discoveryId, intents) {
531
+ this.#throwIfNotConnected();
532
+ return this.#intents?.reportAppIntents(discoveryId, intents) ?? false;
533
+ }
534
+ async sendIntentResult(initiatingSessionId, result) {
535
+ this.#throwIfNotConnected();
536
+ return this.#intents?.sendIntentResult(initiatingSessionId, result);
537
+ }
538
+ parseSessionId(appId) {
539
+ return parseCloudAppId(appId).sessionId;
540
+ }
541
+ parseAppId(appId) {
542
+ return parseCloudAppId(appId).appId;
543
+ }
544
+ addEventListener(type, callback) {
545
+ this.#events.addEventListener(type, callback);
546
+ }
547
+ removeEventListener(type, callback) {
548
+ this.#events.removeEventListener(type, callback);
549
+ }
550
+ once(type, callback) {
551
+ this.#events.once(type, callback);
552
+ }
553
+ async #disconnect(fireDisconnectedEvent) {
554
+ if (!this.#sessionDetails) {
555
+ return;
556
+ }
557
+ try {
558
+ if (!this.#connectionParams) {
559
+ throw new Error('Connect parameters must be provided');
560
+ }
561
+ const disconnectResponse = await fetch(`${this.#cloudInteropSettings.url}/api/sessions/${this.#sessionDetails.sessionId}`, {
562
+ method: 'DELETE',
563
+ headers: getRequestHeaders(this.#connectionParams),
564
+ });
565
+ if (disconnectResponse.status !== 200) {
566
+ throw new CloudInteropAPIError('Error during session tear down - unexpected status', 'ERR_DISCONNECT', new Error(disconnectResponse.statusText));
567
+ }
568
+ }
569
+ catch (error) {
570
+ throw new CloudInteropAPIError('Error during disconnection', 'ERR_DISCONNECT', error);
571
+ }
572
+ finally {
573
+ this.#destroyControllers();
574
+ this.#mqttClient?.removeAllListeners();
575
+ await this.#mqttClient?.endAsync(true);
576
+ this.#sessionDetails = undefined;
577
+ this.#mqttClient = undefined;
578
+ this.#reconnectRetries = 0;
579
+ this.#attemptingToReconnect = false;
580
+ if (fireDisconnectedEvent) {
581
+ this.#events.emitEvent('disconnected');
582
+ }
583
+ }
584
+ }
585
+ #handleMessage(topic, message, sessionDetails) {
586
+ if (message.length === 0 || !sessionDetails) {
587
+ // Ignore clean up messages
588
+ return;
589
+ }
590
+ const messageEnvelope = JSON.parse(message.toString());
591
+ if (topic.startsWith(`${sessionDetails.sessionRootTopic}/context-groups/`)) {
592
+ const contextEvent = messageEnvelope;
593
+ if (contextEvent.source.sessionId === sessionDetails.sessionId) {
594
+ return;
595
+ }
596
+ const { context, payload, contextGroup, channelName, source, history } = contextEvent;
597
+ this.#events.emitEvent('context', {
598
+ contextGroup: channelName || contextGroup,
599
+ context: payload || context,
600
+ source,
601
+ history: { ...history, clientReceived: Date.now() },
602
+ });
603
+ }
604
+ else if (topic.startsWith(`${sessionDetails.sessionRootTopic}/commands`)) {
605
+ this.#handleCommandMessage(messageEnvelope);
606
+ }
607
+ }
608
+ #handleCommandMessage(message) {
609
+ switch (message.command) {
610
+ case 'report-intents':
611
+ case 'intent-details':
612
+ case 'raise-intent':
613
+ case 'intent-result': {
614
+ this.#intents?.handleCommandMessage(message);
615
+ break;
616
+ }
617
+ default: {
618
+ this.#logger('warn', `Unknown command message received:\n${JSON.stringify(message, null, 2)}`);
619
+ break;
620
+ }
621
+ }
622
+ }
623
+ #validateConnectParams = (parameters) => {
624
+ if (!parameters) {
625
+ throw new Error('Connect parameters must be provided');
626
+ }
627
+ if (!parameters.sourceId) {
628
+ throw new Error('sourceId must be provided');
629
+ }
630
+ if (parameters.sourceId.includes(APP_ID_DELIM)) {
631
+ throw new Error(`sourceId cannot contain "${APP_ID_DELIM}"`);
632
+ }
633
+ if (!parameters.platformId) {
634
+ throw new Error('platformId must be provided');
635
+ }
636
+ if (parameters.authenticationType === 'jwt' &&
637
+ (!parameters.jwtAuthenticationParameters?.jwtRequestCallback || !parameters.jwtAuthenticationParameters?.authenticationId)) {
638
+ throw new Error('jwtAuthenticationParameters must be provided when using jwt authentication');
639
+ }
640
+ if (parameters.authenticationType === 'basic' &&
641
+ (!parameters.basicAuthenticationParameters?.username || !parameters.basicAuthenticationParameters?.password)) {
642
+ throw new Error('basicAuthenticationParameters must be provided when using basic authentication');
643
+ }
644
+ };
645
+ #initControllers(mqttClient, sessionDetails, connectionParameters) {
646
+ this.#intents = new IntentController(this.#cloudInteropSettings.url, mqttClient, sessionDetails, connectionParameters, this.#events, this.#logger);
647
+ }
648
+ #destroyControllers() {
649
+ this.#intents = undefined;
650
+ }
651
+ #throwIfNotConnected() {
652
+ if (!this.#sessionDetails || !this.#connectionParams) {
653
+ throw new Error('Session not connected');
654
+ }
655
+ if (!this.#mqttClient) {
656
+ throw new Error('MQTT client not connected');
657
+ }
658
+ }
659
+ }
660
+
661
+ export { AuthorizationError, CloudInteropAPI, CloudInteropAPIError };