@openfin/fdc3-api 36.78.10 → 36.78.12

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/out/fdc3-api.mjs DELETED
@@ -1,2163 +0,0 @@
1
- import require$$2 from 'lodash';
2
-
3
- var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
4
-
5
- var fdc31_2 = {};
6
-
7
- var base = {};
8
-
9
- var promises = {};
10
-
11
- Object.defineProperty(promises, "__esModule", { value: true });
12
- promises.promiseMapSerial = promises.serial = promises.promiseMap = promises.promisify = void 0;
13
- function promisify(func) {
14
- return (...args) => new Promise((resolve, reject) => {
15
- func(...args, (err, val) => (err ? reject(err) : resolve(val)));
16
- });
17
- }
18
- promises.promisify = promisify;
19
- async function promiseMap(arr, asyncF) {
20
- return Promise.all(arr.map(asyncF));
21
- }
22
- promises.promiseMap = promiseMap;
23
- async function serial(arr) {
24
- const ret = [];
25
- for (const func of arr) {
26
- // eslint-disable-next-line no-await-in-loop
27
- const next = await func();
28
- ret.push(next);
29
- }
30
- return ret;
31
- }
32
- promises.serial = serial;
33
- async function promiseMapSerial(arr, func) {
34
- return serial(arr.map((value, index, array) => () => func(value, index, array)));
35
- }
36
- promises.promiseMapSerial = promiseMapSerial;
37
-
38
- var __classPrivateFieldSet$2 = (commonjsGlobal && commonjsGlobal.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
39
- if (kind === "m") throw new TypeError("Private method is not writable");
40
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
41
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
42
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
43
- };
44
- var __classPrivateFieldGet$2 = (commonjsGlobal && commonjsGlobal.__classPrivateFieldGet) || function (receiver, state, kind, f) {
45
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
46
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
47
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
48
- };
49
- var _EmitterBase_emitterAccessor;
50
- Object.defineProperty(base, "__esModule", { value: true });
51
- base.Reply = base.EmitterBase = base.Base = void 0;
52
- const promises_1 = promises;
53
- class Base {
54
- /**
55
- * @internal
56
- */
57
- constructor(wire) {
58
- this.isNodeEnvironment = () => {
59
- return this.wire.environment.constructor.name === 'NodeEnvironment';
60
- };
61
- this.isOpenFinEnvironment = () => {
62
- return this.wire.environment.constructor.name === 'OpenFinEnvironment';
63
- };
64
- this.isBrowserEnvironment = () => {
65
- return this.wire.environment.constructor.name === 'BrowserEnvironment';
66
- };
67
- this.wire = wire;
68
- }
69
- get fin() {
70
- return this.wire.getFin();
71
- }
72
- /**
73
- * Provides access to the OpenFin representation of the current code context (usually a document
74
- * such as a {@link OpenFin.View} or {@link OpenFin.Window}), as well as to the current `Interop` context.
75
- *
76
- * Useful for debugging in the devtools console, where this will intelligently type itself based
77
- * on the context in which the devtools panel was opened.
78
- */
79
- get me() {
80
- return this.wire.me;
81
- }
82
- }
83
- base.Base = Base;
84
- /**
85
- * An entity that emits OpenFin events.
86
- *
87
- * @remarks Event-binding methods are asynchronous as they must cross process boundaries
88
- * and setup the listener in the browser process. When the `EventEmitter` receives an event from the browser process
89
- * and emits on the renderer, all of the functions attached to that specific event are called synchronously. Any values
90
- * returned by the called listeners are ignored and will be discarded. If the execution context of the window is destroyed
91
- * by page navigation or reload, any events that have been setup in that context will be destroyed.
92
- *
93
- * It is important to keep in mind that when an ordinary listener function is called, the standard `this` keyword is intentionally
94
- * set to reference the `EventEmitter` instance to which the listener is attached. It is possible to use ES6 Arrow Functions as
95
- * listeners, however, when doing so, the `this` keyword will no longer reference the `EventEmitter` instance.
96
- *
97
- * Events re-propagate from smaller/more-local scopes to larger/more-global scopes. For example, an event emitted on a specific
98
- * view will propagate to the window in which the view is embedded, and then to the application in which the window is running, and
99
- * finally to the OpenFin runtime itself at the "system" level. Re-propagated events are prefixed with the name of the scope in which
100
- * they originated - for example, a "shown" event emitted on a view will be re-propagated at the window level as "view-shown", and
101
- * then to the application as "window-view-shown", and finally at the system level as "application-window-view-shown".
102
- *
103
- * All event propagations are visible at the System level, regardless of source, so transitive re-propagations (e.g. from view to window
104
- * to application) are visible in their entirety at the system level. So, we can listen to the above event as "shown", "view-shown",
105
- * "window-view-shown", or "application-window-view-shown."
106
- */
107
- class EmitterBase extends Base {
108
- constructor(wire, topic, ...additionalAccessors) {
109
- super(wire);
110
- this.topic = topic;
111
- _EmitterBase_emitterAccessor.set(this, void 0);
112
- this.eventNames = () => (this.hasEmitter() ? this.getOrCreateEmitter().eventNames() : []);
113
- /**
114
- * @internal
115
- */
116
- this.emit = (eventType, payload, ...args) => {
117
- return this.hasEmitter() ? this.getOrCreateEmitter().emit(eventType, payload, ...args) : false;
118
- };
119
- this.hasEmitter = () => this.wire.eventAggregator.has(__classPrivateFieldGet$2(this, _EmitterBase_emitterAccessor, "f"));
120
- this.getOrCreateEmitter = () => this.wire.eventAggregator.getOrCreate(__classPrivateFieldGet$2(this, _EmitterBase_emitterAccessor, "f"));
121
- this.listeners = (type) => this.hasEmitter() ? this.getOrCreateEmitter().listeners(type) : [];
122
- this.listenerCount = (type) => this.hasEmitter() ? this.getOrCreateEmitter().listenerCount(type) : 0;
123
- this.registerEventListener = async (eventType, options = {}, applySubscription, undoSubscription) => {
124
- const runtimeEvent = {
125
- ...this.identity,
126
- timestamp: options.timestamp || Date.now(),
127
- topic: this.topic,
128
- type: eventType
129
- };
130
- const emitter = this.getOrCreateEmitter();
131
- // We apply the subscription and then undo if the async call fails to avoid
132
- // indeterminacy in subscription application order, which can break things elsewhere
133
- applySubscription(emitter);
134
- try {
135
- await this.wire.sendAction('subscribe-to-desktop-event', runtimeEvent);
136
- }
137
- catch (e) {
138
- undoSubscription(emitter);
139
- this.deleteEmitterIfNothingRegistered(emitter);
140
- throw e;
141
- }
142
- };
143
- this.deregisterEventListener = async (eventType, options = {}) => {
144
- if (this.hasEmitter()) {
145
- const runtimeEvent = {
146
- ...this.identity,
147
- timestamp: options.timestamp || Date.now(),
148
- topic: this.topic,
149
- type: eventType
150
- };
151
- await this.wire.sendAction('unsubscribe-to-desktop-event', runtimeEvent).catch(() => null);
152
- const emitter = this.getOrCreateEmitter();
153
- return emitter;
154
- }
155
- // This will only be reached if unsubscribe from event that does not exist but do not want to error here
156
- return Promise.resolve();
157
- };
158
- __classPrivateFieldSet$2(this, _EmitterBase_emitterAccessor, [topic, ...additionalAccessors], "f");
159
- this.listeners = (event) => this.hasEmitter() ? this.getOrCreateEmitter().listeners(event) : [];
160
- }
161
- /**
162
- * Adds a listener to the end of the listeners array for the specified event.
163
- *
164
- * @remarks Event payloads are documented in the {@link OpenFin.Events} namespace.
165
- */
166
- async on(eventType, listener, options) {
167
- await this.registerEventListener(eventType, options, (emitter) => {
168
- emitter.on(eventType, listener);
169
- }, (emitter) => {
170
- emitter.removeListener(eventType, listener);
171
- });
172
- return this;
173
- }
174
- /**
175
- * Adds a listener to the end of the listeners array for the specified event.
176
- */
177
- async addListener(eventType, listener, options) {
178
- return this.on(eventType, listener, options);
179
- }
180
- /**
181
- * Adds a one time listener for the event. The listener is invoked only the first time the event is fired, after which it is removed.
182
- *
183
- * @remarks Event payloads are documented in the {@link OpenFin.Events} namespace.
184
- */
185
- async once(eventType, listener, options) {
186
- const deregister = () => this.deregisterEventListener(eventType);
187
- await this.registerEventListener(eventType, options, (emitter) => {
188
- emitter.once(eventType, deregister);
189
- emitter.once(eventType, listener);
190
- }, (emitter) => {
191
- emitter.removeListener(eventType, deregister);
192
- emitter.removeListener(eventType, listener);
193
- });
194
- return this;
195
- }
196
- /**
197
- * Adds a listener to the beginning of the listeners array for the specified event.
198
- *
199
- * @remarks Event payloads are documented in the {@link OpenFin.Events} namespace.
200
- */
201
- async prependListener(eventType, listener, options) {
202
- await this.registerEventListener(eventType, options, (emitter) => {
203
- emitter.prependListener(eventType, listener);
204
- }, (emitter) => {
205
- emitter.removeListener(eventType, listener);
206
- });
207
- return this;
208
- }
209
- /**
210
- * Adds a one time listener for the event. The listener is invoked only the first time the event is fired,
211
- * after which it is removed. The listener is added to the beginning of the listeners array.
212
- *
213
- * @remarks Event payloads are documented in the {@link OpenFin.Events} namespace.
214
- */
215
- async prependOnceListener(eventType, listener, options) {
216
- const deregister = () => this.deregisterEventListener(eventType);
217
- await this.registerEventListener(eventType, options, (emitter) => {
218
- emitter.prependOnceListener(eventType, listener);
219
- emitter.once(eventType, deregister);
220
- }, (emitter) => {
221
- emitter.removeListener(eventType, listener);
222
- emitter.removeListener(eventType, deregister);
223
- });
224
- return this;
225
- }
226
- /**
227
- * Remove a listener from the listener array for the specified event.
228
- *
229
- * @remarks Caution: Calling this method changes the array indices in the listener array behind the listener.
230
- */
231
- async removeListener(eventType, listener, options) {
232
- const emitter = await this.deregisterEventListener(eventType, options);
233
- if (emitter) {
234
- emitter.removeListener(eventType, listener);
235
- this.deleteEmitterIfNothingRegistered(emitter);
236
- }
237
- return this;
238
- }
239
- async deregisterAllListeners(eventType) {
240
- const runtimeEvent = { ...this.identity, type: eventType, topic: this.topic };
241
- if (this.hasEmitter()) {
242
- const emitter = this.getOrCreateEmitter();
243
- const refCount = emitter.listenerCount(runtimeEvent.type);
244
- const unsubscribePromises = [];
245
- for (let i = 0; i < refCount; i++) {
246
- unsubscribePromises.push(this.wire.sendAction('unsubscribe-to-desktop-event', runtimeEvent).catch(() => null));
247
- }
248
- await Promise.all(unsubscribePromises);
249
- return emitter;
250
- }
251
- return undefined;
252
- }
253
- /**
254
- * Removes all listeners, or those of the specified event.
255
- *
256
- */
257
- async removeAllListeners(eventType) {
258
- const removeByEvent = async (event) => {
259
- const emitter = await this.deregisterAllListeners(event);
260
- if (emitter) {
261
- emitter.removeAllListeners(event);
262
- this.deleteEmitterIfNothingRegistered(emitter);
263
- }
264
- };
265
- if (eventType) {
266
- await removeByEvent(eventType);
267
- }
268
- else if (this.hasEmitter()) {
269
- const events = this.getOrCreateEmitter().eventNames();
270
- await (0, promises_1.promiseMap)(events, removeByEvent);
271
- }
272
- return this;
273
- }
274
- deleteEmitterIfNothingRegistered(emitter) {
275
- if (emitter.eventNames().length === 0) {
276
- this.wire.eventAggregator.delete(__classPrivateFieldGet$2(this, _EmitterBase_emitterAccessor, "f"));
277
- }
278
- }
279
- }
280
- base.EmitterBase = EmitterBase;
281
- _EmitterBase_emitterAccessor = new WeakMap();
282
- class Reply {
283
- }
284
- base.Reply = Reply;
285
-
286
- var utils$2 = {};
287
-
288
- var utils$1 = {};
289
-
290
- (function (exports) {
291
- Object.defineProperty(exports, "__esModule", { value: true });
292
- exports.wrapIntentHandler = exports.BROKER_ERRORS = exports.generateOverrideWarning = exports.generateOverrideError = exports.wrapContextHandler = exports.wrapInTryCatch = exports.generateId = void 0;
293
- const generateId = () => `${Math.random()}${Date.now()}`;
294
- exports.generateId = generateId;
295
- const wrapInTryCatch = (f, prefix) => (...args) => {
296
- try {
297
- return f(...args);
298
- }
299
- catch (e) {
300
- throw new Error((prefix || '') + e);
301
- }
302
- };
303
- exports.wrapInTryCatch = wrapInTryCatch;
304
- const wrapContextHandler = (handler, handlerId) => {
305
- return async (context) => {
306
- try {
307
- await handler(context);
308
- }
309
- catch (error) {
310
- console.error(`Error thrown by handler ${handlerId} for context type ${context.type}: ${error}`);
311
- throw error;
312
- }
313
- };
314
- };
315
- exports.wrapContextHandler = wrapContextHandler;
316
- const generateOverrideError = (clientApi, brokerApi) => {
317
- return `You have tried to to use ${clientApi} but ${brokerApi} has not been overridden in the Interop Broker. Please override this function. Refer to our documentation for more info.`;
318
- };
319
- exports.generateOverrideError = generateOverrideError;
320
- const generateOverrideWarning = (fdc3ClientApi, brokerApi, identity, interopClientApi) => {
321
- const { uuid, name } = identity;
322
- const message = interopClientApi
323
- ? `Entity with identity: ${uuid}/${name} has called ${interopClientApi} or ${fdc3ClientApi} but ${brokerApi} has not been overridden.`
324
- : `Entity with identity: ${uuid}/${name} has called ${fdc3ClientApi} but ${brokerApi} has not been overridden.`;
325
- return message;
326
- };
327
- exports.generateOverrideWarning = generateOverrideWarning;
328
- exports.BROKER_ERRORS = {
329
- fireIntent: (0, exports.generateOverrideError)('fireIntent', 'handleFiredIntent'),
330
- fireIntentForContext: (0, exports.generateOverrideError)('fireIntentForContext', 'handleFiredIntentForContext'),
331
- getInfoForIntent: (0, exports.generateOverrideError)('getInfoForIntent', 'handleInfoForIntent'),
332
- getInfoForIntentsByContext: (0, exports.generateOverrideError)('getInfoForIntentsByContext', 'handleInfoForIntentsByContext'),
333
- joinSessionContextGroupWithJoinContextGroup: 'The Context Group you have tried to join is a Session Context Group. Custom Context Groups can only be defined by the Interop Broker through code or manifest configuration. Please use joinSessionContextGroup.',
334
- fdc3Open: (0, exports.generateOverrideError)('fdc3.open', 'fdc3HandleOpen'),
335
- fdc3FindInstances: (0, exports.generateOverrideError)('fdc3.findInstances', 'fdc3HandleFindInstances'),
336
- fdc3GetAppMetadata: (0, exports.generateOverrideError)('fdc3.getAppMetadata', 'fdc3HandleGetAppMetadata'),
337
- fdc3GetInfo: (0, exports.generateOverrideError)('fdc3.getInfo', 'fdc3HandleGetInfo')
338
- };
339
- const wrapIntentHandler = (handler, handlerId) => {
340
- return async (intent) => {
341
- try {
342
- return handler(intent);
343
- }
344
- catch (error) {
345
- console.error(`Error thrown by handler ${handlerId}: ${error}`);
346
- throw error;
347
- }
348
- };
349
- };
350
- exports.wrapIntentHandler = wrapIntentHandler;
351
- } (utils$1));
352
-
353
- var PrivateChannelClient$1 = {};
354
-
355
- Object.defineProperty(PrivateChannelClient$1, "__esModule", { value: true });
356
- PrivateChannelClient$1.PrivateChannelClient = void 0;
357
- const utils = utils$1;
358
- class PrivateChannelClient {
359
- constructor(client, id) {
360
- this.id = id;
361
- this.client = client;
362
- this.listeners = new Map();
363
- }
364
- async broadcast(context) {
365
- return this.client.dispatch('broadcast', { context });
366
- }
367
- async getCurrentContext(contextType) {
368
- return this.client.dispatch('getCurrentContext', { contextType });
369
- }
370
- async addContextListener(contextType, handler) {
371
- if (typeof handler !== 'function') {
372
- throw new Error("Non-function argument passed to the second parameter 'handler'. Be aware that the argument order does not match the FDC3 standard.");
373
- }
374
- let handlerId;
375
- if (contextType) {
376
- handlerId = `contextHandler:invoke-${this.id}-${contextType}-${utils.generateId()}`;
377
- }
378
- else {
379
- handlerId = `contextHandler:invoke-${this.id}-${utils.generateId()}`;
380
- }
381
- this.client.register(handlerId, utils.wrapContextHandler(handler, handlerId));
382
- const listener = { unsubscribe: await this.createContextUnsubscribeCb(handlerId) };
383
- this.listeners.set(handlerId, listener);
384
- await this.client.dispatch(`contextHandlerAdded`, { handlerId, contextType });
385
- return listener;
386
- }
387
- createNonStandardUnsubscribeCb(handlerId) {
388
- return async () => {
389
- this.client.remove(handlerId);
390
- this.listeners.delete(handlerId);
391
- await this.client.dispatch('nonStandardHandlerRemoved', { handlerId });
392
- };
393
- }
394
- createContextUnsubscribeCb(handlerId) {
395
- return async () => {
396
- this.client.remove(handlerId);
397
- this.listeners.delete(handlerId);
398
- await this.client.dispatch('contextHandlerRemoved', { handlerId });
399
- };
400
- }
401
- onAddContextListener(handler) {
402
- const handlerId = `onContextHandlerAdded:invoke-${this.id}-${utils.generateId()}`;
403
- this.client.register(handlerId, handler);
404
- const listener = { unsubscribe: this.createNonStandardUnsubscribeCb(handlerId) };
405
- this.listeners.set(handlerId, listener);
406
- this.client.dispatch(`onAddContextHandlerAdded`, { handlerId });
407
- return listener;
408
- }
409
- onDisconnect(handler) {
410
- const handlerId = `onDisconnect:invoke-${this.id}-${utils.generateId()}`;
411
- this.client.register(handlerId, handler);
412
- const listener = { unsubscribe: this.createNonStandardUnsubscribeCb(handlerId) };
413
- this.listeners.set(handlerId, listener);
414
- this.client.dispatch(`onDisconnectHandlerAdded`, { handlerId });
415
- return listener;
416
- }
417
- onUnsubscribe(handler) {
418
- const handlerId = `onUnsubscribe:invoke-${this.id}-${utils.generateId()}`;
419
- this.client.register(handlerId, handler);
420
- const listener = { unsubscribe: this.createNonStandardUnsubscribeCb(handlerId) };
421
- this.listeners.set(handlerId, listener);
422
- this.client.dispatch(`onUnsubscribeHandlerAdded`, { handlerId });
423
- return listener;
424
- }
425
- async cleanUpAllSubs() {
426
- const listenerUnsubscribers = Array.from(this.listeners.keys());
427
- listenerUnsubscribers.forEach((handlerId) => {
428
- this.client.remove(handlerId);
429
- this.listeners.delete(handlerId);
430
- });
431
- }
432
- async disconnect() {
433
- try {
434
- await this.client.dispatch('clientDisconnecting');
435
- await this.cleanUpAllSubs();
436
- await this.client.disconnect();
437
- }
438
- catch (error) {
439
- throw new Error(error.message);
440
- }
441
- }
442
- }
443
- PrivateChannelClient$1.PrivateChannelClient = PrivateChannelClient;
444
-
445
- (function (exports) {
446
- Object.defineProperty(exports, "__esModule", { value: true });
447
- exports.getIntentResolution = exports.isChannel = exports.isContext = exports.connectPrivateChannel = exports.buildAppChannelObject = exports.buildPrivateChannelObject = exports.ChannelError = exports.ResultError = exports.UnsupportedChannelApiError = exports.getUnsupportedChannelApis = void 0;
448
- const utils_1 = utils$1;
449
- const PrivateChannelClient_1 = PrivateChannelClient$1;
450
- const lodash_1 = require$$2;
451
- const getUnsupportedChannelApis = (channelType) => {
452
- return {
453
- addContextListener: () => {
454
- throw new UnsupportedChannelApiError('Channel.addContextListener', channelType);
455
- },
456
- broadcast: () => {
457
- throw new UnsupportedChannelApiError('Channel.broadcast', channelType);
458
- },
459
- getCurrentContext: () => {
460
- throw new UnsupportedChannelApiError('Channel.getCurrentContext', channelType);
461
- }
462
- };
463
- };
464
- exports.getUnsupportedChannelApis = getUnsupportedChannelApis;
465
- class UnsupportedChannelApiError extends Error {
466
- constructor(apiName, channelType = 'System') {
467
- super(apiName);
468
- this.message = `Calling ${apiName} on an instance of a ${channelType} Channel returned by fdc3.get${channelType}Channels is not supported. If you would like to use a ${channelType} Channel, please use fdc3.joinChannel, fdc3.addContextListener, and fdc3.broadcast instead.`;
469
- }
470
- }
471
- exports.UnsupportedChannelApiError = UnsupportedChannelApiError;
472
- var ResultError;
473
- (function (ResultError) {
474
- /** Returned if the `IntentHandler` exited without returning a Promise or that
475
- * Promise was not resolved with a Context or Channel object.
476
- */
477
- ResultError["NoResultReturned"] = "NoResultReturned";
478
- /** Returned if the `IntentHandler` function processing the raised intent
479
- * throws an error or rejects the Promise it returned.
480
- */
481
- ResultError["IntentHandlerRejected"] = "IntentHandlerRejected";
482
- })(ResultError = exports.ResultError || (exports.ResultError = {}));
483
- (function (ChannelError) {
484
- /** Returned if the specified channel is not found when attempting to join a
485
- * channel via the `joinUserChannel` function of the DesktopAgent (`fdc3`).
486
- */
487
- ChannelError["NoChannelFound"] = "NoChannelFound";
488
- /** SHOULD be returned when a request to join a user channel or to a retrieve
489
- * a Channel object via the `joinUserChannel` or `getOrCreateChannel` methods
490
- * of the DesktopAgent (`fdc3`) object is denied.
491
- */
492
- ChannelError["AccessDenied"] = "AccessDenied";
493
- /** SHOULD be returned when a channel cannot be created or retrieved via the
494
- * `getOrCreateChannel` method of the DesktopAgent (`fdc3`).
495
- */
496
- ChannelError["CreationFailed"] = "CreationFailed";
497
- })(exports.ChannelError || (exports.ChannelError = {}));
498
- const buildPrivateChannelObject = (privateChannelClient) => {
499
- let clientDisconnected = false;
500
- const checkIfClientDisconnected = () => {
501
- if (clientDisconnected) {
502
- throw new Error('Private Channel Client has been disconnected from the Private Channel');
503
- }
504
- };
505
- return {
506
- id: privateChannelClient.id,
507
- type: 'private',
508
- broadcast: async (context) => {
509
- checkIfClientDisconnected();
510
- return privateChannelClient.broadcast(context);
511
- },
512
- getCurrentContext: async (contextType) => {
513
- checkIfClientDisconnected();
514
- return privateChannelClient.getCurrentContext(contextType);
515
- },
516
- addContextListener: async (contextType, handler) => {
517
- checkIfClientDisconnected();
518
- let handlerInUse = handler;
519
- let contextTypeInUse = contextType;
520
- if (typeof contextType === 'function') {
521
- console.warn('addContextListener(handler) has been deprecated. Please use addContextListener(null, handler)');
522
- handlerInUse = contextType;
523
- contextTypeInUse = null;
524
- }
525
- const listener = privateChannelClient.addContextListener(contextTypeInUse, handlerInUse);
526
- return listener;
527
- },
528
- onAddContextListener: (handler) => {
529
- checkIfClientDisconnected();
530
- return privateChannelClient.onAddContextListener(handler);
531
- },
532
- disconnect: async () => {
533
- checkIfClientDisconnected();
534
- clientDisconnected = true;
535
- return privateChannelClient.disconnect();
536
- },
537
- onDisconnect: (handler) => {
538
- checkIfClientDisconnected();
539
- return privateChannelClient.onDisconnect(handler);
540
- },
541
- onUnsubscribe: (handler) => {
542
- checkIfClientDisconnected();
543
- return privateChannelClient.onUnsubscribe(handler);
544
- }
545
- };
546
- };
547
- exports.buildPrivateChannelObject = buildPrivateChannelObject;
548
- const buildAppChannelObject = (sessionContextGroup) => {
549
- return {
550
- id: sessionContextGroup.id,
551
- type: 'app',
552
- broadcast: sessionContextGroup.setContext,
553
- getCurrentContext: async (contextType) => {
554
- const context = await sessionContextGroup.getCurrentContext(contextType);
555
- return context === undefined ? null : context;
556
- },
557
- addContextListener: (contextType, handler) => {
558
- let realHandler;
559
- let realType;
560
- if (typeof contextType === 'function') {
561
- console.warn('addContextListener(handler) has been deprecated. Please use addContextListener(null, handler)');
562
- realHandler = contextType;
563
- }
564
- else {
565
- realHandler = handler;
566
- if (typeof contextType === 'string') {
567
- realType = contextType;
568
- }
569
- }
570
- const listener = (async () => {
571
- let first = true;
572
- const currentContext = await sessionContextGroup.getCurrentContext(realType);
573
- const wrappedHandler = (context, contextMetadata) => {
574
- if (first) {
575
- first = false;
576
- if ((0, lodash_1.isEqual)(currentContext, context)) {
577
- return;
578
- }
579
- }
580
- // eslint-disable-next-line consistent-return
581
- return realHandler(context, contextMetadata);
582
- };
583
- return sessionContextGroup.addContextHandler(wrappedHandler, realType);
584
- })();
585
- return {
586
- ...listener,
587
- unsubscribe: () => listener.then((l) => l.unsubscribe())
588
- };
589
- }
590
- };
591
- };
592
- exports.buildAppChannelObject = buildAppChannelObject;
593
- const connectPrivateChannel = async (channelId) => {
594
- try {
595
- const channelClient = await fin.InterApplicationBus.Channel.connect(channelId);
596
- const privateChannelClient = new PrivateChannelClient_1.PrivateChannelClient(channelClient, channelId);
597
- return (0, exports.buildPrivateChannelObject)(privateChannelClient);
598
- }
599
- catch (error) {
600
- throw new Error(`Private Channel with id: ${channelId} doesn't exist`);
601
- }
602
- };
603
- exports.connectPrivateChannel = connectPrivateChannel;
604
- const isContext = (context) => {
605
- if (context && typeof context === 'object' && 'type' in context) {
606
- const { type } = context;
607
- return typeof type === 'string';
608
- }
609
- return false;
610
- };
611
- exports.isContext = isContext;
612
- const isChannel = (channel) => {
613
- if (channel && typeof channel === 'object' && 'type' in channel && 'id' in channel) {
614
- const { type, id } = channel;
615
- return typeof type === 'string' && typeof id === 'string' && (type === 'app' || type === 'private');
616
- }
617
- return false;
618
- };
619
- exports.isChannel = isChannel;
620
- const getIntentResolution = async (interopModule, context, app, intent) => {
621
- // Generate an ID to make a session context group with. We will pass that ID to the Broker.
622
- // The broker will then setContext on that session context group later with our Intent Result,
623
- const guid = (0, utils_1.generateId)();
624
- // Promise we'll use in getResult
625
- const getResultPromise = new Promise((resolve) => {
626
- fin.InterApplicationBus.subscribe({ uuid: '*' }, guid, (intentResult) => {
627
- resolve(intentResult);
628
- });
629
- });
630
- // Adding the intentResolutionResultId to the intentObj. Because fireIntent only accepts a single arg, we have to slap it in here.
631
- const metadata = app ? { target: app, intentResolutionResultId: guid } : { intentResolutionResultId: guid };
632
- const intentObj = intent ? { name: intent, context, metadata } : { ...context, metadata };
633
- // Set up the getResult call.
634
- const getResult = async () => {
635
- let intentResult = await getResultPromise;
636
- if (!intentResult || typeof intentResult !== 'object') {
637
- throw new Error(ResultError.NoResultReturned);
638
- }
639
- const { error } = intentResult;
640
- if (error) {
641
- throw new Error(ResultError.IntentHandlerRejected);
642
- }
643
- if ((0, exports.isChannel)(intentResult)) {
644
- const { id, type } = intentResult;
645
- switch (type) {
646
- case 'private': {
647
- intentResult = await (0, exports.connectPrivateChannel)(id);
648
- break;
649
- }
650
- case 'app': {
651
- const sessionContextGroup = await interopModule.joinSessionContextGroup(id);
652
- intentResult = (0, exports.buildAppChannelObject)(sessionContextGroup);
653
- break;
654
- }
655
- }
656
- }
657
- else if (!(0, exports.isContext)(intentResult)) {
658
- throw new Error(ResultError.NoResultReturned);
659
- }
660
- return intentResult;
661
- };
662
- // Finally fire the intent.
663
- const intentResolutionInfoFromBroker = intent
664
- ? await interopModule.fireIntent(intentObj)
665
- : await interopModule.fireIntentForContext(intentObj);
666
- if (typeof intentResolutionInfoFromBroker !== 'object') {
667
- return {
668
- source: {
669
- appId: '',
670
- instanceId: ''
671
- },
672
- intent: '',
673
- version: '2.0',
674
- getResult
675
- };
676
- }
677
- return { ...intentResolutionInfoFromBroker, getResult };
678
- };
679
- exports.getIntentResolution = getIntentResolution;
680
- } (utils$2));
681
-
682
- var InteropClient$1 = {};
683
-
684
- var SessionContextGroupClient$1 = {};
685
-
686
- var __classPrivateFieldSet$1 = (commonjsGlobal && commonjsGlobal.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
687
- if (kind === "m") throw new TypeError("Private method is not writable");
688
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
689
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
690
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
691
- };
692
- var __classPrivateFieldGet$1 = (commonjsGlobal && commonjsGlobal.__classPrivateFieldGet) || function (receiver, state, kind, f) {
693
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
694
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
695
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
696
- };
697
- var _SessionContextGroupClient_clientPromise;
698
- Object.defineProperty(SessionContextGroupClient$1, "__esModule", { value: true });
699
- const base_1$3 = base;
700
- const utils_1$3 = utils$1;
701
- class SessionContextGroupClient extends base_1$3.Base {
702
- constructor(wire, client, id) {
703
- super(wire);
704
- _SessionContextGroupClient_clientPromise.set(this, void 0);
705
- this.id = id;
706
- __classPrivateFieldSet$1(this, _SessionContextGroupClient_clientPromise, client, "f");
707
- }
708
- /**
709
- * Sets a context for the session context group.
710
- * @param context - New context to set.
711
- *
712
- * @tutorial interop.setContext
713
- */
714
- async setContext(context) {
715
- this.wire.sendAction('interop-session-context-group-set-context').catch((e) => {
716
- // don't expose, analytics-only call
717
- });
718
- const client = await __classPrivateFieldGet$1(this, _SessionContextGroupClient_clientPromise, "f");
719
- return client.dispatch(`sessionContextGroup:setContext-${this.id}`, {
720
- sessionContextGroupId: this.id,
721
- context
722
- });
723
- }
724
- async getCurrentContext(type) {
725
- this.wire.sendAction('interop-session-context-group-get-context').catch((e) => {
726
- // don't expose, analytics-only call
727
- });
728
- const client = await __classPrivateFieldGet$1(this, _SessionContextGroupClient_clientPromise, "f");
729
- return client.dispatch(`sessionContextGroup:getContext-${this.id}`, {
730
- sessionContextGroupId: this.id,
731
- type
732
- });
733
- }
734
- async addContextHandler(contextHandler, contextType) {
735
- this.wire.sendAction('interop-session-context-group-add-handler').catch((e) => {
736
- // don't expose, analytics-only call
737
- });
738
- if (typeof contextHandler !== 'function') {
739
- throw new Error("Non-function argument passed to the first parameter 'handler'. Be aware that the argument order does not match the FDC3 standard.");
740
- }
741
- const client = await __classPrivateFieldGet$1(this, _SessionContextGroupClient_clientPromise, "f");
742
- let handlerId;
743
- if (contextType) {
744
- handlerId = `sessionContextHandler:invoke-${this.id}-${contextType}-${(0, utils_1$3.generateId)()}`;
745
- }
746
- else {
747
- handlerId = `sessionContextHandler:invoke-${this.id}`;
748
- }
749
- client.register(handlerId, (0, utils_1$3.wrapContextHandler)(contextHandler, handlerId));
750
- await client.dispatch(`sessionContextGroup:handlerAdded-${this.id}`, { handlerId, contextType });
751
- return { unsubscribe: await this.createUnsubscribeCb(handlerId) };
752
- }
753
- async createUnsubscribeCb(handlerId) {
754
- const client = await __classPrivateFieldGet$1(this, _SessionContextGroupClient_clientPromise, "f");
755
- return async () => {
756
- client.remove(handlerId);
757
- await client.dispatch(`sessionContextGroup:handlerRemoved-${this.id}`, { handlerId });
758
- };
759
- }
760
- getUserInstance() {
761
- return {
762
- id: this.id,
763
- setContext: (0, utils_1$3.wrapInTryCatch)(this.setContext.bind(this), 'Failed to set context: '),
764
- getCurrentContext: (0, utils_1$3.wrapInTryCatch)(this.getCurrentContext.bind(this), 'Failed to get context: '),
765
- addContextHandler: (0, utils_1$3.wrapInTryCatch)(this.addContextHandler.bind(this), 'Failed to add context handler: ')
766
- };
767
- }
768
- }
769
- SessionContextGroupClient$1.default = SessionContextGroupClient;
770
- _SessionContextGroupClient_clientPromise = new WeakMap();
771
-
772
- var __classPrivateFieldSet = (commonjsGlobal && commonjsGlobal.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
773
- if (kind === "m") throw new TypeError("Private method is not writable");
774
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
775
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
776
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
777
- };
778
- var __classPrivateFieldGet = (commonjsGlobal && commonjsGlobal.__classPrivateFieldGet) || function (receiver, state, kind, f) {
779
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
780
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
781
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
782
- };
783
- var _InteropClient_clientPromise, _InteropClient_sessionContextGroups;
784
- Object.defineProperty(InteropClient$1, "__esModule", { value: true });
785
- InteropClient$1.InteropClient = void 0;
786
- const base_1$2 = base;
787
- const SessionContextGroupClient_1 = SessionContextGroupClient$1;
788
- const utils_1$2 = utils$1;
789
- /**
790
- * The Interop Client API is broken up into two groups:
791
- *
792
- * **Content Facing APIs** - For Application Developers putting Views into a Platform Window, who care about Context. These are APIs that send out and receive the Context data that flows between applications. Think of this as the Water in the Interop Pipes.
793
- *
794
- * **Context Grouping APIs** - For Platform Developers, to add and remove Views to and from Context Groups. These APIs are utilized under-the-hood in Platforms, so they don't need to be used to participate in Interop. These are the APIs that decide which entities the context data flows between. Think of these as the valves or pipes that control the flow of Context Data for Interop.
795
- *
796
- * ---
797
- *
798
- * All APIs are available at the `fin.me.interop` namespace.
799
- *
800
- * ---
801
- *
802
- * **You only need 2 things to participate in Interop Context Grouping:**
803
- * * A Context Handler for incoming context: {@link InteropClient#addContextHandler addContextHandler(handler, contextType?)}
804
- * * Call setContext on your context group when you want to share context with other group members: {@link InteropClient#setContext setContext(context)}
805
- *
806
- * ---
807
- *
808
- * ##### Constructor
809
- * Returned by {@link Interop.connectSync Interop.connectSync}.
810
- *
811
- * ---
812
- *
813
- * ##### Interop methods intended for Views
814
- *
815
- *
816
- * **Context Groups API**
817
- * * {@link InteropClient#addContextHandler addContextHandler(handler, contextType?)}
818
- * * {@link InteropClient#setContext setContext(context)}
819
- * * {@link InteropClient#getCurrentContext getCurrentContext(contextType?)}
820
- * * {@link InteropClient#joinSessionContextGroup joinSessionContextGroup(sessionContextGroupId)}
821
- *
822
- *
823
- * **Intents API**
824
- * * {@link InteropClient#fireIntent fireIntent(intent)}
825
- * * {@link InteropClient#registerIntentHandler registerIntentHandler(intentHandler, intentName)}
826
- * * {@link InteropClient#getInfoForIntent getInfoForIntent(infoForIntentOptions)}
827
- * * {@link InteropClient#getInfoForIntentsByContext getInfoForIntentsByContext(context)}
828
- * * {@link InteropClient#fireIntentForContext fireIntentForContext(contextForIntent)}
829
- *
830
- * ##### Interop methods intended for Windows
831
- * * {@link InteropClient#getContextGroups getContextGroups()}
832
- * * {@link InteropClient#joinContextGroup joinContextGroup(contextGroupId, target?)}
833
- * * {@link InteropClient#removeFromContextGroup removeFromContextGroup(target?)}
834
- * * {@link InteropClient#getInfoForContextGroup getInfoForContextGroup(contextGroupId)}
835
- * * {@link InteropClient#getAllClientsInContextGroup getAllClientsInContextGroup(contextGroupId)}
836
- *
837
- */
838
- class InteropClient extends base_1$2.Base {
839
- /**
840
- * @internal
841
- */
842
- constructor(wire, name, interopConfig = {}) {
843
- super(wire);
844
- _InteropClient_clientPromise.set(this, void 0);
845
- _InteropClient_sessionContextGroups.set(this, void 0);
846
- __classPrivateFieldSet(this, _InteropClient_sessionContextGroups, new Map(), "f");
847
- __classPrivateFieldSet(this, _InteropClient_clientPromise, this.wire.environment.whenReady().then(() => {
848
- return this.fin.InterApplicationBus.Channel.connect(`interop-broker-${name}`, {
849
- payload: interopConfig
850
- });
851
- }), "f");
852
- }
853
- /*
854
- Client APIs
855
- */
856
- /**
857
- * Sets a context for the context group of the current entity.
858
- *
859
- * @remarks The entity must be part of a context group in order set a context.
860
- *
861
- * @param context - New context to set.
862
- *
863
- * @example
864
- * ```js
865
- * setInstrumentContext = async (ticker) => {
866
- * fin.me.interop.setContext({type: 'instrument', id: {ticker}})
867
- * }
868
- *
869
- * // The user clicks an instrument of interest. We want to set that Instrument context so that the rest of our workflow updates with information for that instrument
870
- * instrumentElement.on('click', (evt) => {
871
- * setInstrumentContext(evt.ticker)
872
- * })
873
- * ```
874
- */
875
- async setContext(context) {
876
- this.wire.sendAction('interop-client-set-context').catch((e) => {
877
- // don't expose, analytics-only call
878
- });
879
- const client = await __classPrivateFieldGet(this, _InteropClient_clientPromise, "f");
880
- return client.dispatch('setContext', { context });
881
- }
882
- /**
883
- * Add a context handler for incoming context. If an entity is part of a context group, and then sets its context handler,
884
- * it will receive all of its declared contexts.
885
- *
886
- * @param handler - Handler for incoming context.
887
- * @param contextType - The type of context you wish to handle.
888
- *
889
- * @example
890
- * ```js
891
- * function handleIncomingContext(contextInfo) {
892
- * const { type, id } = contextInfo;
893
- * switch (type) {
894
- * case 'instrument':
895
- * handleInstrumentContext(contextInfo);
896
- * break;
897
- * case 'country':
898
- * handleCountryContext(contextInfo);
899
- * break;
900
- *
901
- * default:
902
- * break;
903
- * }
904
- * }
905
- *
906
- *
907
- * function handleInstrumentContext(contextInfo) {
908
- * const { type, id } = contextInfo;
909
- * console.log('contextInfo for instrument', contextInfo)
910
- * }
911
- *
912
- * function handleCountryContext(contextInfo) {
913
- * const { type, id } = contextInfo;
914
- * console.log('contextInfo for country', contextInfo)
915
- * }
916
- *
917
- * fin.me.interop.addContextHandler(handleIncomingContext);
918
- * ```
919
- *
920
- *
921
- * We are also testing the ability to add a context handler for specific contexts. If you would like to use
922
- * this, please make sure you add your context handlers at the top level of your application, on a page that
923
- * does not navigate/reload/re-render, to avoid memory leaks. This feature is experimental:
924
- *
925
- * ```js
926
- * function handleInstrumentContext(contextInfo) {
927
- * const { type, id } = contextInfo;
928
- * console.log('contextInfo for instrument', contextInfo)
929
- * }
930
- *
931
- * function handleCountryContext(contextInfo) {
932
- * const { type, id } = contextInfo;
933
- * console.log('contextInfo for country', contextInfo)
934
- * }
935
- *
936
- *
937
- * fin.me.interop.addContextHandler(handleInstrumentContext, 'instrument')
938
- * fin.me.interop.addContextHandler(handleCountryContext, 'country')
939
- * ```
940
- */
941
- async addContextHandler(handler, contextType) {
942
- this.wire.sendAction('interop-client-add-context-handler').catch((e) => {
943
- // don't expose, analytics-only call
944
- });
945
- if (typeof handler !== 'function') {
946
- throw new Error("Non-function argument passed to the first parameter 'handler'. Be aware that the argument order does not match the FDC3 standard.");
947
- }
948
- const client = await __classPrivateFieldGet(this, _InteropClient_clientPromise, "f");
949
- let handlerId;
950
- if (contextType) {
951
- handlerId = `invokeContextHandler-${contextType}-${(0, utils_1$2.generateId)()}`;
952
- console.warn(`Warning: By providing a contextType (${contextType}), you are using the experimental addContextHandler. To avoid issues, make sure you are adding your context handlers at the top level in your application.`);
953
- }
954
- else {
955
- handlerId = 'invokeContextHandler';
956
- }
957
- const wrappedHandler = (0, utils_1$2.wrapContextHandler)(handler, handlerId);
958
- client.register(handlerId, wrappedHandler);
959
- await client.dispatch('contextHandlerRegistered', { handlerId, contextType });
960
- return {
961
- unsubscribe: async () => {
962
- client.remove(handlerId);
963
- await client.dispatch('removeContextHandler', { handlerId });
964
- }
965
- };
966
- }
967
- /*
968
- Platform Window APIs
969
- */
970
- /**
971
- * Returns the Interop-Broker-defined context groups available for an entity to join.
972
- * Used by Platform Windows.
973
- *
974
- * @example
975
- * ```js
976
- * fin.me.interop.getContextGroups()
977
- * .then(contextGroups => {
978
- * contextGroups.forEach(contextGroup => {
979
- * console.log(contextGroup.displayMetadata.name)
980
- * console.log(contextGroup.displayMetadata.color)
981
- * })
982
- * })
983
- * ```
984
- */
985
- async getContextGroups() {
986
- this.wire.sendAction('interop-client-get-context-groups').catch((e) => {
987
- // don't expose, analytics-only call
988
- });
989
- const client = await __classPrivateFieldGet(this, _InteropClient_clientPromise, "f");
990
- return client.dispatch('getContextGroups');
991
- }
992
- /**
993
- * Join all Interop Clients at the given identity to context group `contextGroupId`.
994
- * If no target is specified, it adds the sender to the context group.
995
- *
996
- * @remarks Because multiple Channel connections/Interop Clients can potentially exist at a `uuid`/`name` combo, we currently join all Channel connections/Interop Clients at the given identity to the context group.
997
- * If an `endpointId` is provided (which is unlikely, unless the call is coming from an external adapter), then we only join that single connection to the context group.
998
- * For all intents and purposes, there will only be 1 connection present in Platform and Browser implmentations, so this point is more-or-less moot.
999
- * Used by Platform Windows.
1000
- *
1001
- * @param contextGroupId - Id of the context group.
1002
- * @param target - Identity of the entity you wish to join to a context group.
1003
- *
1004
- * @example
1005
- * ```js
1006
- * joinViewToContextGroup = async (contextGroupId, view) => {
1007
- * await fin.me.interop.joinContextGroup(contextGroupId, view);
1008
- * }
1009
- *
1010
- * getLastFocusedView()
1011
- * .then(lastFocusedViewIdentity => {
1012
- * joinViewToContextGroup('red', lastFocusedViewIdentity)
1013
- * })
1014
- * ```
1015
- */
1016
- async joinContextGroup(contextGroupId, target) {
1017
- this.wire.sendAction('interop-client-join-context-group').catch((e) => {
1018
- // don't expose, analytics-only call
1019
- });
1020
- const client = await __classPrivateFieldGet(this, _InteropClient_clientPromise, "f");
1021
- if (!contextGroupId) {
1022
- throw new Error('No contextGroupId specified for joinContextGroup.');
1023
- }
1024
- return client.dispatch('joinContextGroup', { contextGroupId, target });
1025
- }
1026
- /**
1027
- * Removes the specified target from a context group.
1028
- * If no target is specified, it removes the sender from their context group.
1029
- * Used by Platform Windows.
1030
- *
1031
- * @param target - Identity of the entity you wish to join to a context group.
1032
- *
1033
- * @example
1034
- * ```js
1035
- * removeViewFromContextGroup = async (view) => {
1036
- * await fin.me.interop.removeFromContextGroup(view);
1037
- * }
1038
- *
1039
- * getLastFocusedView()
1040
- * .then(lastFocusedViewIdentity => {
1041
- * removeViewFromContextGroup(lastFocusedViewIdentity)
1042
- * })
1043
- * ```
1044
- */
1045
- async removeFromContextGroup(target) {
1046
- this.wire.sendAction('interop-client-remove-from-context-group').catch((e) => {
1047
- // don't expose, analytics-only call
1048
- });
1049
- const client = await __classPrivateFieldGet(this, _InteropClient_clientPromise, "f");
1050
- return client.dispatch('removeFromContextGroup', { target });
1051
- }
1052
- /**
1053
- * Gets all clients for a context group.
1054
- *
1055
- * @remarks **This is primarily used for platform windows. Views within a platform should not have to use this API.**
1056
- *
1057
- * Returns the Interop-Broker-defined context groups available for an entity to join.
1058
- * @param contextGroupId - The id of context group you wish to get clients for.
1059
- *
1060
- * @example
1061
- * ```js
1062
- * fin.me.interop.getAllClientsInContextGroup('red')
1063
- * .then(clientsInContextGroup => {
1064
- * console.log(clientsInContextGroup)
1065
- * })
1066
- * ```
1067
- */
1068
- async getAllClientsInContextGroup(contextGroupId) {
1069
- this.wire.sendAction('interop-client-get-all-clients-in-context-group').catch((e) => {
1070
- // don't expose, analytics-only call
1071
- });
1072
- const client = await __classPrivateFieldGet(this, _InteropClient_clientPromise, "f");
1073
- if (!contextGroupId) {
1074
- throw new Error('No contextGroupId specified for getAllClientsInContextGroup.');
1075
- }
1076
- return client.dispatch('getAllClientsInContextGroup', { contextGroupId });
1077
- }
1078
- /**
1079
- * Gets display info for a context group
1080
- *
1081
- * @remarks Used by Platform Windows.
1082
- * @param contextGroupId - The id of context group you wish to get display info for.
1083
- *
1084
- * @example
1085
- * ```js
1086
- * fin.me.interop.getInfoForContextGroup('red')
1087
- * .then(contextGroupInfo => {
1088
- * console.log(contextGroupInfo.displayMetadata.name)
1089
- * console.log(contextGroupInfo.displayMetadata.color)
1090
- * })
1091
- * ```
1092
- */
1093
- async getInfoForContextGroup(contextGroupId) {
1094
- this.wire.sendAction('interop-client-get-info-for-context-group').catch((e) => {
1095
- // don't expose, analytics-only call
1096
- });
1097
- const client = await __classPrivateFieldGet(this, _InteropClient_clientPromise, "f");
1098
- if (!contextGroupId) {
1099
- throw new Error('No contextGroupId specified for getInfoForContextGroup.');
1100
- }
1101
- return client.dispatch('getInfoForContextGroup', { contextGroupId });
1102
- }
1103
- /**
1104
- * Sends an intent to the Interop Broker to resolve.
1105
- * @param intent - The combination of an action and a context that is passed to an application for resolution.
1106
- *
1107
- * @example
1108
- * ```js
1109
- * // View wants to fire an Intent after a user clicks on a ticker
1110
- * tickerElement.on('click', (element) => {
1111
- * const ticker = element.innerText;
1112
- * const intent = {
1113
- * name: 'ViewChart',
1114
- * context: {type: 'fdc3.instrument', id: { ticker }}
1115
- * }
1116
- *
1117
- * fin.me.interop.fireIntent(intent);
1118
- * })
1119
- * ```
1120
- */
1121
- async fireIntent(intent) {
1122
- this.wire.sendAction('interop-client-fire-intent').catch((e) => {
1123
- // don't expose, this is only for api analytics purposes
1124
- });
1125
- const client = await __classPrivateFieldGet(this, _InteropClient_clientPromise, "f");
1126
- return client.dispatch('fireIntent', intent);
1127
- }
1128
- /**
1129
- * Adds an intent handler for incoming intents. The last intent sent of the name subscribed to will be received.
1130
- * @param handler - Registered function meant to handle a specific intent type.
1131
- * @param intentName - The name of an intent.
1132
- *
1133
- * @example
1134
- * ```js
1135
- * const intentHandler = (intent) => {
1136
- * const { context } = intent;
1137
- * myViewChartHandler(context);
1138
- * };
1139
- *
1140
- * const subscription = await fin.me.interop.registerIntentHandler(intentHandler, 'ViewChart');
1141
- *
1142
- * function myAppCloseSequence() {
1143
- * // to unsubscribe the handler, simply call:
1144
- * subscription.unsubscribe();
1145
- * }
1146
- * ```
1147
- */
1148
- async registerIntentHandler(handler, intentName, options) {
1149
- this.wire.sendAction('interop-client-register-intent-handler').catch((e) => {
1150
- // don't expose, this is only for api analytics purposes
1151
- });
1152
- const client = await __classPrivateFieldGet(this, _InteropClient_clientPromise, "f");
1153
- const handlerId = `intent-handler-${intentName}`;
1154
- const wrappedHandler = (0, utils_1$2.wrapIntentHandler)(handler, handlerId);
1155
- try {
1156
- await client.register(handlerId, wrappedHandler);
1157
- await client.dispatch('intentHandlerRegistered', { handlerId, ...options });
1158
- }
1159
- catch (error) {
1160
- throw new Error('Unable to register intent handler');
1161
- }
1162
- return {
1163
- unsubscribe: async () => {
1164
- client.remove(handlerId);
1165
- }
1166
- };
1167
- }
1168
- /**
1169
- * Gets the last context of the Context Group currently subscribed to. It takes an optional Context Type and returns the
1170
- * last context of that type.
1171
- * @param contextType
1172
- *
1173
- * @example
1174
- * ```js
1175
- * await fin.me.interop.joinContextGroup('yellow');
1176
- * await fin.me.interop.setContext({ type: 'instrument', id: { ticker: 'FOO' }});
1177
- * const currentContext = await fin.me.interop.getCurrentContext();
1178
- *
1179
- * // with a specific context
1180
- * await fin.me.interop.joinContextGroup('yellow');
1181
- * await fin.me.interop.setContext({ type: 'country', id: { ISOALPHA3: 'US' }});
1182
- * await fin.me.interop.setContext({ type: 'instrument', id: { ticker: 'FOO' }});
1183
- * const currentContext = await fin.me.interop.getCurrentContext('country');
1184
- * ```
1185
- */
1186
- async getCurrentContext(contextType) {
1187
- this.wire.sendAction('interop-client-get-current-context').catch((e) => {
1188
- // don't expose, analytics-only call
1189
- });
1190
- const client = await __classPrivateFieldGet(this, _InteropClient_clientPromise, "f");
1191
- return client.dispatch('getCurrentContext', { contextType });
1192
- }
1193
- /**
1194
- * Get information for a particular Intent from the Interop Broker.
1195
- *
1196
- * @remarks To resolve this info, the function handleInfoForIntent is meant to be overridden in the Interop Broker.
1197
- * The format for the response will be determined by the App Provider overriding the function.
1198
- *
1199
- * @param options
1200
- *
1201
- * @example
1202
- * ```js
1203
- * const intentInfo = await fin.me.interop.getInfoForIntent('ViewChart');
1204
- * ```
1205
- */
1206
- async getInfoForIntent(options) {
1207
- this.wire.sendAction('interop-client-get-info-for-intent').catch((e) => {
1208
- // don't expose, analytics-only call
1209
- });
1210
- const client = await __classPrivateFieldGet(this, _InteropClient_clientPromise, "f");
1211
- return client.dispatch('getInfoForIntent', options);
1212
- }
1213
- /**
1214
- * Get information from the Interop Broker on all Intents that are meant to handle a particular context.
1215
- *
1216
- * @remarks To resolve this info, the function handleInfoForIntentsByContext is meant to be overridden in the Interop Broker.
1217
- * The format for the response will be determined by the App Provider overriding the function.
1218
- *
1219
- * @param context
1220
- *
1221
- * @example
1222
- * ```js
1223
- * tickerElement.on('click', (element) => {
1224
- * const ticker = element.innerText;
1225
- *
1226
- * const context = {
1227
- * type: 'fdc3.instrument',
1228
- * id: {
1229
- * ticker
1230
- * }
1231
- * }
1232
- *
1233
- * const intentsInfo = await fin.me.interop.getInfoForIntentByContext(context);
1234
- * })
1235
- * ```
1236
- */
1237
- async getInfoForIntentsByContext(context) {
1238
- this.wire.sendAction('interop-client-get-info-for-intents-by-context').catch((e) => {
1239
- // don't expose, analytics-only call
1240
- });
1241
- const client = await __classPrivateFieldGet(this, _InteropClient_clientPromise, "f");
1242
- return client.dispatch('getInfoForIntentsByContext', context);
1243
- }
1244
- /**
1245
- * Sends a Context that will be resolved to an Intent by the Interop Broker.
1246
- * This context accepts a metadata property.
1247
- *
1248
- * @remarks To resolve this info, the function handleFiredIntentByContext is meant to be overridden in the Interop Broker.
1249
- * The format for the response will be determined by the App Provider overriding the function.
1250
- *
1251
- * @param context
1252
- *
1253
- * @example
1254
- * ```js
1255
- * tickerElement.on('click', (element) => {
1256
- * const ticker = element.innerText;
1257
- *
1258
- * const context = {
1259
- * type: 'fdc3.instrument',
1260
- * id: {
1261
- * ticker
1262
- * }
1263
- * }
1264
- *
1265
- * const intentResolution = await fin.me.interop.fireIntentForContext(context);
1266
- * })
1267
- * ```
1268
- */
1269
- async fireIntentForContext(context) {
1270
- this.wire.sendAction('interop-client-fire-intent-for-context').catch((e) => {
1271
- // don't expose, analytics-only call
1272
- });
1273
- const client = await __classPrivateFieldGet(this, _InteropClient_clientPromise, "f");
1274
- return client.dispatch('fireIntentForContext', context);
1275
- }
1276
- /**
1277
- * Join the current entity to session context group `sessionContextGroupId` and return a sessionContextGroup instance.
1278
- * If the sessionContextGroup doesn't exist, one will get created.
1279
- *
1280
- * @remarks Session Context Groups do not persist between runs and aren't present on snapshots.
1281
- * @param sessionContextGroupId - Id of the context group.
1282
- *
1283
- * @example
1284
- * Say we want to have a Session Context Group that holds UI theme information for all apps to consume:
1285
- *
1286
- * My color-picker View:
1287
- * ```js
1288
- * const themeSessionContextGroup = await fin.me.interop.joinSessionContextGroup('theme');
1289
- *
1290
- * const myColorPickerElement = document.getElementById('color-palette-picker');
1291
- * myColorPickerElement.addEventListener('change', event => {
1292
- * themeSessionContextGroup.setContext({ type: 'color-palette', selection: event.value });
1293
- * });
1294
- * ```
1295
- *
1296
- * In other views:
1297
- * ```js
1298
- * const themeSessionContextGroup = await fin.me.interop.joinSessionContextGroup('theme');
1299
- *
1300
- * const changeColorPalette = ({ selection }) => {
1301
- * // change the color palette to the selection
1302
- * };
1303
- *
1304
- * // If the context is already set by the time the handler was set, the handler will get invoked immediately with the current context.
1305
- * themeSessionContextGroup.addContextHandler(changeColorPalette, 'color-palette');
1306
- * ```
1307
- */
1308
- async joinSessionContextGroup(sessionContextGroupId) {
1309
- try {
1310
- const currentSessionContextGroup = __classPrivateFieldGet(this, _InteropClient_sessionContextGroups, "f").get(sessionContextGroupId);
1311
- if (currentSessionContextGroup) {
1312
- return currentSessionContextGroup.getUserInstance();
1313
- }
1314
- const client = await __classPrivateFieldGet(this, _InteropClient_clientPromise, "f");
1315
- const { hasConflict } = await client.dispatch('sessionContextGroup:createIfNeeded', {
1316
- sessionContextGroupId
1317
- });
1318
- if (hasConflict) {
1319
- console.warn(`A (non-session) context group with the name "${sessionContextGroupId}" already exists. If you are trying to join a Context Group, call joinContextGroup instead.`);
1320
- }
1321
- const newSessionContextGroup = new SessionContextGroupClient_1.default(this.wire, __classPrivateFieldGet(this, _InteropClient_clientPromise, "f"), sessionContextGroupId);
1322
- __classPrivateFieldGet(this, _InteropClient_sessionContextGroups, "f").set(sessionContextGroupId, newSessionContextGroup);
1323
- return newSessionContextGroup.getUserInstance();
1324
- }
1325
- catch (error) {
1326
- console.error(`Error thrown trying to create Session Context Group with id "${sessionContextGroupId}": ${error}`);
1327
- throw error;
1328
- }
1329
- }
1330
- /**
1331
- * Register a listener that is called when the Interop Client has been disconnected from the Interop Broker.
1332
- * Only one listener per Interop Client can be set.
1333
- * @param listener
1334
- *
1335
- * @example
1336
- * ```js
1337
- * const listener = (event) => {
1338
- * const { type, topic, brokerName} = event;
1339
- * console.log(`Disconnected from Interop Broker ${brokerName} `);
1340
- * }
1341
- *
1342
- * await fin.me.interop.onDisconnection(listener);
1343
- * ```
1344
- */
1345
- async onDisconnection(listener) {
1346
- this.wire.sendAction('interop-client-add-ondisconnection-listener').catch((e) => {
1347
- // don't expose, analytics-only call
1348
- });
1349
- const client = await __classPrivateFieldGet(this, _InteropClient_clientPromise, "f");
1350
- return client.onDisconnection((event) => {
1351
- const { uuid } = event;
1352
- listener({ type: 'interop-broker', topic: 'disconnected', brokerName: uuid });
1353
- });
1354
- }
1355
- /**
1356
- * @internal
1357
- *
1358
- * Used to ferry fdc3-only calls from the fdc3 shim to the Interop Broker
1359
- */
1360
- static async ferryFdc3Call(interopClient, action, payload) {
1361
- const client = await __classPrivateFieldGet(interopClient, _InteropClient_clientPromise, "f");
1362
- return client.dispatch(action, payload || null);
1363
- }
1364
- }
1365
- InteropClient$1.InteropClient = InteropClient;
1366
- _InteropClient_clientPromise = new WeakMap(), _InteropClient_sessionContextGroups = new WeakMap();
1367
-
1368
- Object.defineProperty(fdc31_2, "__esModule", { value: true });
1369
- var Fdc3Module_1 = fdc31_2.Fdc3Module = void 0;
1370
- const base_1$1 = base;
1371
- const utils_1$1 = utils$2;
1372
- const utils_2$1 = utils$1;
1373
- const InteropClient_1$1 = InteropClient$1;
1374
- const lodash_1 = require$$2;
1375
- /**
1376
- * @version 1.2
1377
- * The FDC3 Client Library provides a set APIs to be used for FDC3 compliance,
1378
- * while using our Interop API under the hood. In order to use this set of APIs
1379
- * you will need to set up your own {@link InteropBroker InteropBroker} or use a Platform application, which does the setup for you. Refer to our documentation on
1380
- * our {@link https://developers.openfin.co/of-docs/docs/enable-color-linking Interop API}.
1381
- *
1382
- * To enable the FDC3 APIs in a {@link Window Window} or {@link View View}, add the fdc3InteropApi
1383
- * property to its options:
1384
- *
1385
- * ```js
1386
- * {
1387
- * autoShow: false,
1388
- * saveWindowState: true,
1389
- * url: 'https://openfin.co',
1390
- * fdc3InteropApi: '1.2'
1391
- * }
1392
- * ```
1393
- *
1394
- * If using a {@link Platform Platform } application, you can set this property in defaultWindowOptions and defaultViewOptions.
1395
- *
1396
- * In order to ensure that the FDC3 Api is ready before use, you can use the 'fdc3Ready' event fired on the DOM Window object:
1397
- *
1398
- * ```js
1399
- * function fdc3Action() {
1400
- * // Make some fdc3 API calls here
1401
- * }
1402
- *
1403
- * if (window.fdc3) {
1404
- * fdc3Action();
1405
- * } else {
1406
- * window.addEventListener('fdc3Ready', fdc3Action);
1407
- * }
1408
- * ```
1409
- */
1410
- class Fdc3Module extends base_1$1.Base {
1411
- /**
1412
- * Add a context handler for incoming context. If an entity is part of a context group, and then sets its context handler, it will receive all of its declared contexts. If you wish to listen for all incoming contexts, pass `null` for the contextType argument.
1413
- * @param contextType - The type of context you wish to handle.
1414
- * @param handler - Handler for incoming context.
1415
- *
1416
- * @tutorial fdc3.addContextListener
1417
- * @static
1418
- */
1419
- addContextListener(contextType, handler) {
1420
- this.wire.sendAction('fdc3-add-context-listener').catch((e) => {
1421
- // we do not want to expose this error, just continue if this analytics-only call fails
1422
- });
1423
- let listener;
1424
- if (typeof contextType === 'function') {
1425
- console.warn('addContextListener(handler) has been deprecated. Please use addContextListener(null, handler)');
1426
- listener = this.fin.me.interop.addContextHandler(contextType);
1427
- }
1428
- else {
1429
- listener = this.fin.me.interop.addContextHandler(handler, contextType === null ? undefined : contextType);
1430
- }
1431
- return {
1432
- ...listener,
1433
- unsubscribe: () => listener.then((l) => l.unsubscribe())
1434
- };
1435
- }
1436
- /**
1437
- * Broadcasts a context for the channel of the current entity.
1438
- * @param context - New context to set.
1439
- *
1440
- * @tutorial fdc3.broadcast
1441
- * @static
1442
- */
1443
- async broadcast(context) {
1444
- this.wire.sendAction('fdc3-broadcast').catch((e) => {
1445
- // we do not want to expose this error, just continue if this analytics-only call fails
1446
- });
1447
- return this.fin.me.interop.setContext(context);
1448
- }
1449
- /**
1450
- * Returns the Interop-Broker-defined context groups available for an entity to join.
1451
- *
1452
- * @tutorial fdc3.getSystemChannels
1453
- * @static
1454
- */
1455
- async getSystemChannels() {
1456
- this.wire.sendAction('fdc3-get-system-channels').catch((e) => {
1457
- // we do not want to expose this error, just continue if this analytics-only call fails
1458
- });
1459
- const channels = await this.fin.me.interop.getContextGroups();
1460
- // fdc3 implementation of getSystemChannels returns on array of channels, have to decorate over
1461
- // this so people know that these APIs are not supported
1462
- return channels.map((channel) => {
1463
- return { ...channel, type: 'system', ...(0, utils_1$1.getUnsupportedChannelApis)() };
1464
- });
1465
- }
1466
- /**
1467
- * Join all Interop Clients at the given identity to context group `contextGroupId`.
1468
- * If no target is specified, it adds the sender to the context group.
1469
- * Because multiple Channel connections/Interop Clients can potentially exist at a `uuid`/`name` combo, we currently join all Channel connections/Interop Clients at the given identity to the context group.
1470
- * If an `endpointId` is provided (which is unlikely, unless the call is coming from an external adapter), then we only join that single connection to the context group.
1471
- * For all intents and purposes, there will only be 1 connection present in Platform and Browser implementations, so this point is more-or-less moot.
1472
- * @param channelId - Id of the context group.
1473
- *
1474
- * @tutorial fdc3.joinChannel
1475
- * @static
1476
- */
1477
- async joinChannel(channelId) {
1478
- this.wire.sendAction('fdc3-join-channel').catch((e) => {
1479
- // we do not want to expose this error, just continue if this analytics-only call fails
1480
- });
1481
- try {
1482
- return await this.fin.me.interop.joinContextGroup(channelId);
1483
- }
1484
- catch (error) {
1485
- if (error.message === utils_2$1.BROKER_ERRORS.joinSessionContextGroupWithJoinContextGroup) {
1486
- console.error('The Channel you have tried to join is an App Channel. Custom Channels can only be defined by the Interop Broker through code or manifest configuration. Please use getOrCreateChannel.');
1487
- }
1488
- else {
1489
- console.error(error.message);
1490
- }
1491
- if (error.message.startsWith('Attempting to join a context group that does not exist')) {
1492
- throw new Error(utils_1$1.ChannelError.NoChannelFound);
1493
- }
1494
- throw new Error(utils_1$1.ChannelError.AccessDenied);
1495
- }
1496
- }
1497
- /**
1498
- * Removes the specified target from a context group.
1499
- * If no target is specified, it removes the sender from their context group.
1500
- *
1501
- * @tutorial fdc3.leaveCurrentChannel
1502
- * @static
1503
- */
1504
- async leaveCurrentChannel() {
1505
- this.wire.sendAction('fdc3-leave-current-channel').catch((e) => {
1506
- // we do not want to expose this error, just continue if this analytics-only call fails
1507
- });
1508
- return this.fin.me.interop.removeFromContextGroup();
1509
- }
1510
- /**
1511
- * Adds a listener for incoming Intents.
1512
- * @param intent - Name of the Intent
1513
- * @param handler - Handler for incoming Intent
1514
- *
1515
- * @tutorial fdc3.addIntentListener
1516
- * @static
1517
- */
1518
- addIntentListener(intent, handler) {
1519
- this.wire.sendAction('fdc3-add-intent-listener').catch((e) => {
1520
- // we do not want to expose this error, just continue if this analytics-only call fails
1521
- });
1522
- const contextHandler = (raisedIntent) => {
1523
- const { context, metadata: intentMetadata } = raisedIntent;
1524
- const { metadata } = context;
1525
- const intentResolutionResultId = intentMetadata?.intentResolutionResultId || metadata?.intentResolutionResultId;
1526
- if (intentResolutionResultId) {
1527
- this.fin.InterApplicationBus.publish(intentResolutionResultId, null);
1528
- }
1529
- handler(raisedIntent.context);
1530
- };
1531
- const listener = this.fin.me.interop.registerIntentHandler(contextHandler, intent, {
1532
- fdc3Version: '1.2'
1533
- });
1534
- return {
1535
- ...listener,
1536
- unsubscribe: () => listener.then((l) => l.unsubscribe())
1537
- };
1538
- }
1539
- /**
1540
- * Raises a specific intent.
1541
- * @param intent Name of the Intent.
1542
- * @param context Context associated with the Intent.
1543
- * @param app App that will resolve the Intent. This is added as metadata to the Intent. Can be accessed by the app provider in {@link InteropBroker#handleFiredIntent InteropBroker.handleFiredIntent}.
1544
- *
1545
- * @tutorial fdc3.raiseIntent
1546
- * @static
1547
- */
1548
- async raiseIntent(intent, context, app) {
1549
- this.wire.sendAction('fdc3-raise-intent').catch((e) => {
1550
- // we do not want to expose this error, just continue if this analytics-only call fails
1551
- });
1552
- const intentObj = app
1553
- ? { name: intent, context, metadata: { target: app } }
1554
- : { name: intent, context };
1555
- try {
1556
- return await this.fin.me.interop.fireIntent(intentObj);
1557
- }
1558
- catch (error) {
1559
- const errorToThrow = error.message === utils_2$1.BROKER_ERRORS.fireIntent ? 'ResolverUnavailable' : error.message;
1560
- throw new Error(errorToThrow);
1561
- }
1562
- }
1563
- /**
1564
- * Returns the Channel that the entity is subscribed to. Returns null if not joined to a channel.
1565
- *
1566
- * @tutorial fdc3.getCurrentChannel
1567
- */
1568
- async getCurrentChannel() {
1569
- this.wire.sendAction('fdc3-get-current-channel').catch((e) => {
1570
- // we do not want to expose this error, just continue if this analytics-only call fails
1571
- });
1572
- const currentContextGroupInfo = await this.getCurrentContextGroupInfo();
1573
- if (!currentContextGroupInfo) {
1574
- return null;
1575
- }
1576
- return this.buildChannelObject(currentContextGroupInfo);
1577
- }
1578
- /**
1579
- * Find out more information about a particular intent by passing its name, and optionally its context.
1580
- * @param intent Name of the Intent
1581
- * @param context
1582
- *
1583
- * @tutorial fdc3.findIntent
1584
- */
1585
- async findIntent(intent, context) {
1586
- this.wire.sendAction('fdc3-find-intent').catch((e) => {
1587
- // we do not want to expose this error, just continue if this analytics-only call fails
1588
- });
1589
- try {
1590
- return await this.fin.me.interop.getInfoForIntent({ name: intent, context });
1591
- }
1592
- catch (error) {
1593
- const errorToThrow = error.message === utils_2$1.BROKER_ERRORS.getInfoForIntent ? 'ResolverUnavailable' : error.message;
1594
- throw new Error(errorToThrow);
1595
- }
1596
- }
1597
- /**
1598
- * Find all the available intents for a particular context.
1599
- * @param context
1600
- *
1601
- * @tutorial fdc3.findIntentsByContext
1602
- */
1603
- async findIntentsByContext(context) {
1604
- this.wire.sendAction('fdc3-find-intents-by-context').catch((e) => {
1605
- // we do not want to expose this error, just continue if this analytics-only call fails
1606
- });
1607
- try {
1608
- return await this.fin.me.interop.getInfoForIntentsByContext(context);
1609
- }
1610
- catch (error) {
1611
- const errorToThrow = error.message === utils_2$1.BROKER_ERRORS.getInfoForIntentsByContext ? 'ResolverUnavailable' : error.message;
1612
- throw new Error(errorToThrow);
1613
- }
1614
- }
1615
- /**
1616
- * Finds and raises an intent against a target app based purely on context data.
1617
- * @param context
1618
- * @param app
1619
- *
1620
- * @tutorial fdc3.raiseIntentForContext
1621
- */
1622
- async raiseIntentForContext(context, app) {
1623
- this.wire.sendAction('fdc3-raise-intent-for-context').catch((e) => {
1624
- // we do not want to expose this error, just continue if this analytics-only call fails
1625
- });
1626
- try {
1627
- return await this.fin.me.interop.fireIntentForContext({ ...context, metadata: { target: app } });
1628
- }
1629
- catch (error) {
1630
- const errorToThrow = error.message === utils_2$1.BROKER_ERRORS.fireIntentForContext ? 'ResolverUnavailable' : error.message;
1631
- throw new Error(errorToThrow);
1632
- }
1633
- }
1634
- /**
1635
- * Returns a Channel object for the specified channel, creating it as an App Channel if it does not exist.
1636
- * @param channelId
1637
- *
1638
- * @tutorial fdc3.getOrCreateChannel
1639
- */
1640
- async getOrCreateChannel(channelId) {
1641
- this.wire.sendAction('fdc3-get-or-create-channel').catch((e) => {
1642
- // we do not want to expose this error, just continue if this analytics-only call fails
1643
- });
1644
- const systemChannels = await this.getSystemChannels();
1645
- const userChannel = systemChannels.find((channel) => channel.id === channelId);
1646
- if (userChannel) {
1647
- return { ...userChannel, type: 'system', ...(0, utils_1$1.getUnsupportedChannelApis)() };
1648
- }
1649
- try {
1650
- const sessionContextGroup = await this.fin.me.interop.joinSessionContextGroup(channelId);
1651
- return (0, utils_1$1.buildAppChannelObject)(sessionContextGroup);
1652
- }
1653
- catch (error) {
1654
- console.error(error.message);
1655
- throw new Error(utils_1$1.ChannelError.CreationFailed);
1656
- }
1657
- }
1658
- /**
1659
- * Returns metadata relating to the FDC3 object and its provider, including the supported version of the FDC3 specification and the name of the provider of the implementation.
1660
- *
1661
- * @tutorial fdc3.getInfo
1662
- */
1663
- getInfo() {
1664
- this.wire.sendAction('fdc3-get-info').catch((e) => {
1665
- // we do not want to expose this error, just continue if this analytics-only call fails
1666
- });
1667
- // @ts-expect-error
1668
- const { uuid, fdc3InteropApi } = fin.__internal_.initialOptions;
1669
- // @ts-expect-error
1670
- const runtimeVersion = fin.desktop.getVersion();
1671
- return {
1672
- fdc3Version: fdc3InteropApi,
1673
- provider: `openfin-${uuid}`,
1674
- providerVersion: runtimeVersion
1675
- };
1676
- }
1677
- /**
1678
- * Launches an app with target information, which can either be a string or an AppMetadata object.
1679
- * @param app
1680
- * @param context
1681
- *
1682
- * @tutorial fdc3.open
1683
- */
1684
- async open(app, context) {
1685
- this.wire.sendAction('fdc3-open').catch((e) => {
1686
- // we do not want to expose this error, just continue if this analytics-only call fails
1687
- });
1688
- try {
1689
- return await InteropClient_1$1.InteropClient.ferryFdc3Call(this.fin.me.interop, 'fdc3Open', { app, context });
1690
- }
1691
- catch (error) {
1692
- const errorToThrow = error.message === utils_2$1.BROKER_ERRORS.fdc3Open ? 'ResolverUnavailable' : error.message;
1693
- throw new Error(errorToThrow);
1694
- }
1695
- }
1696
- // utils
1697
- // eslint-disable-next-line class-methods-use-this
1698
- async getCurrentContextGroupInfo() {
1699
- const contextGroups = await this.fin.me.interop.getContextGroups();
1700
- const clientsInCtxGroupsPromise = contextGroups.map(async (ctxGroup) => {
1701
- return this.fin.me.interop.getAllClientsInContextGroup(ctxGroup.id);
1702
- });
1703
- const clientsInCtxGroups = await Promise.all(clientsInCtxGroupsPromise);
1704
- const clientIdx = clientsInCtxGroups.findIndex((clientIdentityArr) => {
1705
- return clientIdentityArr.some((clientIdentity) => {
1706
- const { uuid, name } = clientIdentity;
1707
- return this.fin.me.uuid === uuid && this.fin.me.name === name;
1708
- });
1709
- });
1710
- return contextGroups[clientIdx];
1711
- }
1712
- async buildChannelObject(currentContextGroupInfo) {
1713
- return {
1714
- ...currentContextGroupInfo,
1715
- type: 'system',
1716
- addContextListener: (contextType, handler) => {
1717
- let realHandler;
1718
- let realType;
1719
- if (typeof contextType === 'function') {
1720
- console.warn('addContextListener(handler) has been deprecated. Please use addContextListener(null, handler)');
1721
- realHandler = contextType;
1722
- }
1723
- else {
1724
- realHandler = handler;
1725
- if (typeof contextType === 'string') {
1726
- realType = contextType;
1727
- }
1728
- }
1729
- const listener = (async () => {
1730
- let first = true;
1731
- const currentContext = await this.fin.me.interop.getCurrentContext(realType);
1732
- const wrappedHandler = (context, contextMetadata) => {
1733
- if (first) {
1734
- first = false;
1735
- if ((0, lodash_1.isEqual)(currentContext, context)) {
1736
- return;
1737
- }
1738
- }
1739
- // eslint-disable-next-line consistent-return
1740
- return realHandler(context, contextMetadata);
1741
- };
1742
- return this.fin.me.interop.addContextHandler(wrappedHandler, realType);
1743
- })();
1744
- return {
1745
- ...listener,
1746
- unsubscribe: () => listener.then((l) => l.unsubscribe())
1747
- };
1748
- },
1749
- broadcast: this.broadcast.bind(this),
1750
- getCurrentContext: async (contextType) => {
1751
- const context = await this.fin.me.interop.getCurrentContext(contextType);
1752
- return context === undefined ? null : context;
1753
- }
1754
- };
1755
- }
1756
- }
1757
- Fdc3Module_1 = fdc31_2.Fdc3Module = Fdc3Module;
1758
-
1759
- var fdc3 = {};
1760
-
1761
- var fdc32_0 = {};
1762
-
1763
- Object.defineProperty(fdc32_0, "__esModule", { value: true });
1764
- var Fdc3Module2_1 = fdc32_0.Fdc3Module2 = void 0;
1765
- const base_1 = base;
1766
- const utils_1 = utils$1;
1767
- const InteropClient_1 = InteropClient$1;
1768
- const utils_2 = utils$2;
1769
- const fdc3_1_2_1 = fdc31_2;
1770
- const PrivateChannelClient_1 = PrivateChannelClient$1;
1771
- /**
1772
- * @version 2.0
1773
- * The FDC3 Client Library provides a set APIs to be used for FDC3 compliance,
1774
- * while using our Interop API under the hood. In order to use this set of APIs
1775
- * you will need to set up your own {@link InteropBroker InteropBroker} or use a Platform application, which does the setup for you. Refer to our documentation on
1776
- * our {@link https://developers.openfin.co/of-docs/docs/enable-context-sharing Interop API}.
1777
- *
1778
- * To enable the FDC3 APIs in a {@link Window Window} or {@link View View}, add the fdc3InteropApi
1779
- * property to its options:
1780
- *
1781
- * ```js
1782
- * {
1783
- * autoShow: false,
1784
- * saveWindowState: true,
1785
- * url: 'https://openfin.co',
1786
- * fdc3InteropApi: '2.0'
1787
- * }
1788
- * ```
1789
- *
1790
- * If using a {@link Platform Platform } application, you can set this property in defaultWindowOptions and defaultViewOptions.
1791
- *
1792
- * In order to ensure that the FDC3 Api is ready before use, you can use the 'fdc3Ready' event fired on the DOM Window object:
1793
- *
1794
- * ```js
1795
- * function fdc3Action() {
1796
- * // Make some fdc3 API calls here
1797
- * }
1798
- *
1799
- * if (window.fdc3) {
1800
- * fdc3Action();
1801
- * } else {
1802
- * window.addEventListener('fdc3Ready', fdc3Action);
1803
- * }
1804
- * ```
1805
- */
1806
- class Fdc3Module2 extends base_1.Base {
1807
- constructor(wire) {
1808
- super(wire);
1809
- // we get the module for fdc 1.2 here so we can reuse it wherever we can
1810
- this.fdc3Module = new fdc3_1_2_1.Fdc3Module(this.wire);
1811
- }
1812
- /**
1813
- * Launches an app, specified via an AppIdentifier object.
1814
- * @param app
1815
- * @param context
1816
- *
1817
- * @tutorial fdc3.open
1818
- */
1819
- async open(app, context) {
1820
- if (typeof app === 'string') {
1821
- console.warn('Passing a string as the app parameter is deprecated, please use an AppIdentifier ({ appId: string; instanceId?: string }).');
1822
- }
1823
- return this.fdc3Module.open(app, context);
1824
- }
1825
- /**
1826
- * Find all the available instances for a particular application.
1827
- * @param app
1828
- *
1829
- * @tutorial fdc3v2.findInstances
1830
- */
1831
- async findInstances(app) {
1832
- this.wire.sendAction('fdc3-find-instances').catch((e) => {
1833
- // we do not want to expose this error, just continue if this analytics-only call fails
1834
- });
1835
- try {
1836
- return await InteropClient_1.InteropClient.ferryFdc3Call(this.fin.me.interop, 'fdc3FindInstances', app);
1837
- }
1838
- catch (error) {
1839
- const errorToThrow = error.message === utils_1.BROKER_ERRORS.fdc3FindInstances ? 'ResolverUnavailable' : error.message;
1840
- throw new Error(errorToThrow);
1841
- }
1842
- }
1843
- /**
1844
- * Retrieves the AppMetadata for an AppIdentifier, which provides additional metadata (such as icons, a title and description) from the App Directory record for the application, that may be used for display purposes.
1845
- * @param app
1846
- *
1847
- * @tutorial fdc3v2.getAppMetadata
1848
- */
1849
- async getAppMetadata(app) {
1850
- this.wire.sendAction('fdc3-get-app-metadata').catch((e) => {
1851
- // we do not want to expose this error, just continue if this analytics-only call fails
1852
- });
1853
- try {
1854
- return await InteropClient_1.InteropClient.ferryFdc3Call(this.fin.me.interop, 'fdc3GetAppMetadata', app);
1855
- }
1856
- catch (error) {
1857
- const errorToThrow = error.message === utils_1.BROKER_ERRORS.fdc3GetAppMetadata ? 'ResolverUnavailable' : error.message;
1858
- throw new Error(errorToThrow);
1859
- }
1860
- }
1861
- /**
1862
- * Broadcasts a context for the channel of the current entity.
1863
- * @param context - New context to set.
1864
- *
1865
- * @tutorial fdc3.broadcast
1866
- */
1867
- async broadcast(context) {
1868
- return this.fdc3Module.broadcast(context);
1869
- }
1870
- /**
1871
- * Add a context handler for incoming context. If an entity is part of a context group, and then sets its context handler, it will receive all of its declared contexts. If you wish to listen for all incoming contexts, pass `null` for the contextType argument.
1872
- * @param contextType
1873
- * @param handler
1874
- *
1875
- * @tutorial fdc3.addContextListener
1876
- */
1877
- async addContextListener(contextType, handler) {
1878
- this.wire.sendAction('fdc3-add-context-listener').catch((e) => {
1879
- // we do not want to expose this error, just continue if this analytics-only call fails
1880
- });
1881
- // The FDC3 ContextHandler only expects the context and optional ContextMetadata, so we wrap the handler
1882
- // here so it only gets passed these parameters
1883
- const getWrappedHandler = (handlerToWrap) => {
1884
- return (context) => {
1885
- const { contextMetadata, ...rest } = context;
1886
- const args = contextMetadata ? [{ ...rest }, contextMetadata] : [context, null];
1887
- handlerToWrap(...args);
1888
- };
1889
- };
1890
- let actualHandler = handler;
1891
- let wrappedHandler = getWrappedHandler(actualHandler);
1892
- if (typeof contextType === 'function') {
1893
- console.warn('addContextListener(handler) has been deprecated. Please use addContextListener(null, handler)');
1894
- actualHandler = contextType;
1895
- wrappedHandler = getWrappedHandler(actualHandler);
1896
- return this.fin.me.interop.addContextHandler(wrappedHandler);
1897
- }
1898
- return this.fin.me.interop.addContextHandler(wrappedHandler, contextType === null ? undefined : contextType);
1899
- }
1900
- /**
1901
- * Find out more information about a particular intent by passing its name, and optionally its context and resultType.
1902
- * @param intent Name of the Intent
1903
- * @param context Context
1904
- * @param resultType The type of result returned for any intent specified during resolution.
1905
- *
1906
- * @tutorial fdc3.findIntent
1907
- */
1908
- async findIntent(intent, context, resultType) {
1909
- this.wire.sendAction('fdc3-find-intent').catch((e) => {
1910
- // we do not want to expose this error, just continue if this analytics-only call fails
1911
- });
1912
- try {
1913
- return await this.fin.me.interop.getInfoForIntent({ name: intent, context, metadata: { resultType } });
1914
- }
1915
- catch (error) {
1916
- const errorToThrow = error.message === utils_1.BROKER_ERRORS.getInfoForIntent ? 'ResolverUnavailable' : error.message;
1917
- throw new Error(errorToThrow);
1918
- }
1919
- }
1920
- /**
1921
- * Find all the available intents for a particular context.
1922
- * @param context
1923
- * @param resultType The type of result returned for any intent specified during resolution.
1924
- *
1925
- * @tutorial fdc3v2.findIntentsByContext
1926
- */
1927
- async findIntentsByContext(context, resultType) {
1928
- this.wire.sendAction('fdc3-find-intents-by-context').catch((e) => {
1929
- // we do not want to expose this error, just continue if this analytics-only call fails
1930
- });
1931
- const payload = resultType ? { context, metadata: { resultType } } : context;
1932
- try {
1933
- return await InteropClient_1.InteropClient.ferryFdc3Call(this.fin.me.interop, 'fdc3v2FindIntentsByContext', payload);
1934
- }
1935
- catch (error) {
1936
- const errorToThrow = error.message === utils_1.BROKER_ERRORS.getInfoForIntentsByContext ? 'ResolverUnavailable' : error.message;
1937
- throw new Error(errorToThrow);
1938
- }
1939
- }
1940
- /**
1941
- * Raises a specific intent for resolution against apps registered with the desktop agent.
1942
- * @param intent Name of the Intent
1943
- * @param context Context associated with the Intent
1944
- * @param app
1945
- *
1946
- * @tutorial fdc3v2.raiseIntent
1947
- */
1948
- async raiseIntent(intent, context, app) {
1949
- this.wire.sendAction('fdc3-raise-intent').catch((e) => {
1950
- // we do not want to expose this error, just continue if this analytics-only call fails
1951
- });
1952
- try {
1953
- if (typeof app === 'string') {
1954
- console.warn('Passing a string as the app parameter is deprecated, please use an AppIdentifier ({ appId: string; instanceId?: string }).');
1955
- }
1956
- return (0, utils_2.getIntentResolution)(this.fin.me.interop, context, app, intent);
1957
- }
1958
- catch (error) {
1959
- const errorToThrow = error.message === utils_1.BROKER_ERRORS.fireIntent ? 'ResolverUnavailable' : error.message;
1960
- throw new Error(errorToThrow);
1961
- }
1962
- }
1963
- /**
1964
- * Finds and raises an intent against apps registered with the desktop agent based purely on the type of the context data.
1965
- * @param context Context associated with the Intent
1966
- * @param app
1967
- *
1968
- * @tutorial fdc3v2.raiseIntentForContext
1969
- */
1970
- async raiseIntentForContext(context, app) {
1971
- // TODO: We have to do the same thing we do for raiseIntent here as well.
1972
- this.wire.sendAction('fdc3-raise-intent-for-context').catch((e) => {
1973
- // we do not want to expose this error, just continue if this analytics-only call fails
1974
- });
1975
- try {
1976
- if (typeof app === 'string') {
1977
- console.warn('Passing a string as the app parameter is deprecated, please use an AppIdentifier ({ appId: string; instanceId?: string }).');
1978
- }
1979
- return (0, utils_2.getIntentResolution)(this.fin.me.interop, context, app);
1980
- }
1981
- catch (error) {
1982
- const errorToThrow = error.message === utils_1.BROKER_ERRORS.fireIntent ? 'ResolverUnavailable' : error.message;
1983
- throw new Error(errorToThrow);
1984
- }
1985
- }
1986
- /**
1987
- * Adds a listener for incoming intents.
1988
- * @param intent Name of the Intent
1989
- * @param handler A callback that handles a context event and may return a promise of a Context or Channel object to be returned to the application that raised the intent.
1990
- *
1991
- * @tutorial fdc3.addIntentListener
1992
- */
1993
- async addIntentListener(intent, handler) {
1994
- this.wire.sendAction('fdc3-add-intent-listener').catch((e) => {
1995
- // we do not want to expose this error, just continue if this analytics-only call fails
1996
- });
1997
- if (typeof intent !== 'string') {
1998
- throw new Error('First argument must be an Intent name');
1999
- }
2000
- // The FDC3 Intenter handler only expects the context and contextMetadata to be passed to the handler,
2001
- // so we wrap it here and only pass those paramaters.
2002
- const contextHandler = async (raisedIntent) => {
2003
- let intentResult;
2004
- let intentResultToSend;
2005
- const { context, metadata: intentMetadata } = raisedIntent;
2006
- const { contextMetadata, metadata, ...rest } = context;
2007
- const intentResolutionResultId = intentMetadata?.intentResolutionResultId || metadata?.intentResolutionResultId;
2008
- try {
2009
- const newContext = metadata ? { metadata, ...rest } : { ...rest };
2010
- intentResult = await handler(newContext, contextMetadata);
2011
- intentResultToSend = intentResult;
2012
- }
2013
- catch (error) {
2014
- intentResult = error;
2015
- intentResultToSend = { error: true };
2016
- }
2017
- if (intentResolutionResultId) {
2018
- this.fin.InterApplicationBus.publish(intentResolutionResultId, intentResultToSend);
2019
- }
2020
- if (intentResult instanceof Error) {
2021
- throw new Error(intentResult.message);
2022
- }
2023
- return intentResult;
2024
- };
2025
- return this.fin.me.interop.registerIntentHandler(contextHandler, intent, { fdc3Version: '2.0' });
2026
- }
2027
- /**
2028
- * Returns a Channel object for the specified channel, creating it as an App Channel if it does not exist.
2029
- * @param channelId
2030
- *
2031
- * @tutorial fdc3.getOrCreateChannel
2032
- */
2033
- async getOrCreateChannel(channelId) {
2034
- return this.fdc3Module.getOrCreateChannel(channelId);
2035
- }
2036
- /**
2037
- * Returns a Channel with an auto-generated identity that is intended for private communication between applications. Primarily used to create channels that will be returned to other applications via an IntentResolution for a raised intent.
2038
- *
2039
- * @tutorial fdc3v2.createPrivateChannel
2040
- */
2041
- async createPrivateChannel() {
2042
- const channelId = (0, utils_1.generateId)();
2043
- await InteropClient_1.InteropClient.ferryFdc3Call(this.fin.me.interop, 'createPrivateChannelProvider', { channelId });
2044
- const channelClient = await this.fin.InterApplicationBus.Channel.connect(channelId);
2045
- const newPrivateChannelClient = new PrivateChannelClient_1.PrivateChannelClient(channelClient, channelId);
2046
- return (0, utils_2.buildPrivateChannelObject)(newPrivateChannelClient);
2047
- }
2048
- /**
2049
- * Retrieves a list of the User Channels available for the app to join.
2050
- *
2051
- * @tutorial fdc3v2.getUserChannels
2052
- */
2053
- async getUserChannels() {
2054
- const channels = await this.fin.me.interop.getContextGroups();
2055
- // fdc3 implementation of getUserChannels returns on array of channels, have to decorate over
2056
- // this so people know that these APIs are not supported
2057
- return channels.map((channel) => {
2058
- return { ...channel, type: 'user', ...(0, utils_2.getUnsupportedChannelApis)('User') };
2059
- });
2060
- }
2061
- /**
2062
- * Retrieves a list of the User Channels available for the app to join.
2063
- *
2064
- * @deprecated Please use {@link fdc3.getUserChannels fdc3.getUserChannels} instead
2065
- * @tutorial fdc3.getSystemChannels
2066
- */
2067
- async getSystemChannels() {
2068
- console.warn('This API has been deprecated. Please use fdc3.getUserChannels instead.');
2069
- return this.fdc3Module.getSystemChannels();
2070
- }
2071
- /**
2072
- * Join an app to a specified User channel.
2073
- * @param channelId Channel name
2074
- *
2075
- * @tutorial fdc3v2.joinUserChannel
2076
- */
2077
- async joinUserChannel(channelId) {
2078
- return this.fdc3Module.joinChannel(channelId);
2079
- }
2080
- /**
2081
- * Join an app to a specified User channel.
2082
- * @param channelId Channel name
2083
- * @deprecated Please use {@link fdc3.joinUserChannel fdc3.joinUserChannel} instead
2084
- *
2085
- * @tutorial fdc3.joinChannel
2086
- */
2087
- async joinChannel(channelId) {
2088
- console.warn('This API has been deprecated. Please use fdc3.joinUserChannel instead.');
2089
- return this.fdc3Module.joinChannel(channelId);
2090
- }
2091
- /**
2092
- * Returns the Channel object for the current User channel membership
2093
- *
2094
- * @tutorial fdc3.getCurrentChannel
2095
- */
2096
- async getCurrentChannel() {
2097
- const currentChannel = await this.fdc3Module.getCurrentChannel();
2098
- if (!currentChannel) {
2099
- return null;
2100
- }
2101
- return {
2102
- ...currentChannel,
2103
- type: 'user',
2104
- broadcast: this.broadcast.bind(this)
2105
- };
2106
- }
2107
- /**
2108
- * Removes the app from any User channel membership.
2109
- *
2110
- * @tutorial fdc3.leaveCurrentChannel
2111
- */
2112
- async leaveCurrentChannel() {
2113
- return this.fdc3Module.leaveCurrentChannel();
2114
- }
2115
- /**
2116
- * Retrieves information about the FDC3 implementation, including the supported version of the FDC3 specification, the name of the provider of the implementation, its own version number, details of whether optional API features are implemented and the metadata of the calling application according to the desktop agent.
2117
- * fdc3HandleGetInfo must be overridden in the InteropBroker so that the ImplementationMetadata will have the appMetadata info.
2118
- *
2119
- * @tutorial fdc3v2.getInfo
2120
- */
2121
- async getInfo() {
2122
- return InteropClient_1.InteropClient.ferryFdc3Call(this.fin.me.interop, 'fdc3v2GetInfo', { fdc3Version: '2.0' });
2123
- }
2124
- }
2125
- Fdc3Module2_1 = fdc32_0.Fdc3Module2 = Fdc3Module2;
2126
-
2127
- (function (exports) {
2128
- Object.defineProperty(exports, "__esModule", { value: true });
2129
- exports.getFdc3 = exports.versionMap = void 0;
2130
- /* eslint-disable no-console */
2131
- /* eslint-disable no-param-reassign */
2132
- /* eslint-disable @typescript-eslint/no-non-null-assertion */
2133
- const fdc3_1_2_1 = fdc31_2;
2134
- const fdc3_2_0_1 = fdc32_0;
2135
- exports.versionMap = {
2136
- '1.2': fdc3_1_2_1.Fdc3Module,
2137
- '2.0': fdc3_2_0_1.Fdc3Module2
2138
- };
2139
- const latestVersion = '2.0';
2140
- function getFdc3(transport, version = latestVersion) {
2141
- if (!(version in exports.versionMap)) {
2142
- console.warn(`FDC3 API version: ${version} is not supported. Defaulting to latest version: ${latestVersion}.`);
2143
- version = latestVersion;
2144
- }
2145
- const Fdc3Api = exports.versionMap[version];
2146
- const fdc3 = new Fdc3Api(transport);
2147
- window.dispatchEvent(new CustomEvent('fdc3Ready'));
2148
- return fdc3;
2149
- }
2150
- exports.getFdc3 = getFdc3;
2151
- } (fdc3));
2152
-
2153
- var versions = {};
2154
-
2155
- Object.defineProperty(versions, "__esModule", { value: true });
2156
-
2157
- async function fdc3FromFin(fin, version) {
2158
- // @ts-expect-error
2159
- return fdc3.getFdc3(fin.wire, version);
2160
- }
2161
-
2162
- var Fdc3Version = versions.Fdc3Version;
2163
- export { Fdc3Module_1 as Fdc3Module, Fdc3Module2_1 as Fdc3Module2, Fdc3Version, fdc3FromFin };