@openfin/cloud-interop-core-api 0.0.1-alpha.0034b20

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