@openfin/fdc3-api 37.80.39 → 37.81.20

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