@openfin/cloud-interop-core-api 0.0.1-alpha.e6793f0 → 0.0.1-alpha.e8aa2c9

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