@interopio/fdc3 2.0.1

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.
@@ -0,0 +1,3164 @@
1
+ /******************************************************************************
2
+ Copyright (c) Microsoft Corporation.
3
+
4
+ Permission to use, copy, modify, and/or distribute this software for any
5
+ purpose with or without fee is hereby granted.
6
+
7
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
8
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
9
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
10
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
11
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
12
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
13
+ PERFORMANCE OF THIS SOFTWARE.
14
+ ***************************************************************************** */
15
+
16
+ function __rest$1(s, e) {
17
+ var t = {};
18
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
19
+ t[p] = s[p];
20
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
21
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
22
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
23
+ t[p[i]] = s[p[i]];
24
+ }
25
+ return t;
26
+ }
27
+
28
+ function __awaiter(thisArg, _arguments, P, generator) {
29
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
30
+ return new (P || (P = Promise))(function (resolve, reject) {
31
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
32
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
33
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
34
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
35
+ });
36
+ }
37
+
38
+ let nanoid = (size = 21) =>
39
+ crypto.getRandomValues(new Uint8Array(size)).reduce((id, byte) => {
40
+ byte &= 63;
41
+ if (byte < 36) {
42
+ id += byte.toString(36);
43
+ } else if (byte < 62) {
44
+ id += (byte - 26).toString(36).toUpperCase();
45
+ } else if (byte > 62) {
46
+ id += '-';
47
+ } else {
48
+ id += '_';
49
+ }
50
+ return id
51
+ }, '');
52
+
53
+ navigator.userAgent.toLowerCase().includes(" electron/");
54
+ navigator.userAgent.toLowerCase().includes(" tick42-glue-desktop/");
55
+ const isValidNonEmptyObject = (obj) => {
56
+ return typeof obj === "object" && !Array.isArray(obj) && Object.keys(obj).length !== 0;
57
+ };
58
+ const AsyncListener = (actualUnsub) => {
59
+ return {
60
+ unsubscribe() {
61
+ if (!actualUnsub) {
62
+ console.error("Failed to unsubscribe!");
63
+ return;
64
+ }
65
+ if (typeof actualUnsub === "function") {
66
+ actualUnsub();
67
+ }
68
+ else {
69
+ actualUnsub.then((unsubFunc) => unsubFunc()).catch(console.error);
70
+ }
71
+ }
72
+ };
73
+ };
74
+ const checkIfInElectron = (globalFdc3) => {
75
+ const hasGlue42electron = typeof window !== "undefined" && "glue42electron" in window;
76
+ if (!hasGlue42electron) {
77
+ return;
78
+ }
79
+ const runningInElectron = typeof process !== "undefined" && "contextIsolated" in process;
80
+ if (runningInElectron) {
81
+ const contextBridge = require("electron").contextBridge;
82
+ contextBridge.exposeInMainWorld("fdc3", globalFdc3);
83
+ }
84
+ };
85
+ const promisePlus = (promise, timeoutMilliseconds, timeoutMessage) => {
86
+ return new Promise((resolve, reject) => {
87
+ const timeout = setTimeout(() => {
88
+ const message = timeoutMessage || `Promise timeout hit: ${timeoutMilliseconds}`;
89
+ reject(message);
90
+ }, timeoutMilliseconds);
91
+ promise()
92
+ .then((result) => {
93
+ clearTimeout(timeout);
94
+ resolve(result);
95
+ })
96
+ .catch((error) => {
97
+ clearTimeout(timeout);
98
+ reject(error);
99
+ });
100
+ });
101
+ };
102
+ const generateCommandId = () => {
103
+ return nanoid();
104
+ };
105
+
106
+ var IntentHandlerResultTypes;
107
+ (function (IntentHandlerResultTypes) {
108
+ IntentHandlerResultTypes["Context"] = "Context";
109
+ IntentHandlerResultTypes["Channel"] = "Channel";
110
+ })(IntentHandlerResultTypes || (IntentHandlerResultTypes = {}));
111
+ var ChannelTypes;
112
+ (function (ChannelTypes) {
113
+ ChannelTypes["User"] = "user";
114
+ ChannelTypes["App"] = "app";
115
+ ChannelTypes["Private"] = "private";
116
+ })(ChannelTypes || (ChannelTypes = {}));
117
+ const fdc3ChannelNames = ["fdc3.channel.1", "fdc3.channel.4", "fdc3.channel.6", "fdc3.channel.3", "fdc3.channel.2", "fdc3.channel.8", "fdc3.channel.7", "fdc3.channel.5"];
118
+ const defaultChannelsProps = ["id", "type", "broadcast", "addContextListener", "getCurrentContext"];
119
+ const defaultContextProps = ["type"];
120
+ const defaultGlue42APIs = ["contexts", "channels", "interop", "intents", "appManager", "windows"];
121
+ const responseInteropMethodPrefix = "T42.FDC3.Open.Listener.Response";
122
+ const glueChannelNamePrefix = "___channel___";
123
+ const fdc3NothingContextType = "fdc3.nothing";
124
+ const Glue42EnterpriseNoAppWindow = "no-app-window";
125
+ const RaiseTimeoutMs = 75 * 1000;
126
+ const IntentsMethodPrefix = "Tick42.FDC3.Intents.";
127
+
128
+ const Glue42FDC3SystemMethod = "T42.FDC3.Client.Control";
129
+ const PrivateChannelPrefix = "___privateFDC3Channel___";
130
+ var PrivateChannelEventMethods;
131
+ (function (PrivateChannelEventMethods) {
132
+ PrivateChannelEventMethods["OnAddContextListener"] = "onAddContextListener";
133
+ PrivateChannelEventMethods["OnUnsubscribe"] = "onUnsubscribe";
134
+ PrivateChannelEventMethods["OnDisconnect"] = "onDisconnect";
135
+ })(PrivateChannelEventMethods || (PrivateChannelEventMethods = {}));
136
+
137
+ /**
138
+ * Wraps values in an `Ok` type.
139
+ *
140
+ * Example: `ok(5) // => {ok: true, result: 5}`
141
+ */
142
+ var ok = function (result) { return ({ ok: true, result: result }); };
143
+ /**
144
+ * Wraps errors in an `Err` type.
145
+ *
146
+ * Example: `err('on fire') // => {ok: false, error: 'on fire'}`
147
+ */
148
+ var err = function (error) { return ({ ok: false, error: error }); };
149
+ /**
150
+ * Create a `Promise` that either resolves with the result of `Ok` or rejects
151
+ * with the error of `Err`.
152
+ */
153
+ var asPromise = function (r) {
154
+ return r.ok === true ? Promise.resolve(r.result) : Promise.reject(r.error);
155
+ };
156
+ /**
157
+ * Unwraps a `Result` and returns either the result of an `Ok`, or
158
+ * `defaultValue`.
159
+ *
160
+ * Example:
161
+ * ```
162
+ * Result.withDefault(5, number().run(json))
163
+ * ```
164
+ *
165
+ * It would be nice if `Decoder` had an instance method that mirrored this
166
+ * function. Such a method would look something like this:
167
+ * ```
168
+ * class Decoder<A> {
169
+ * runWithDefault = (defaultValue: A, json: any): A =>
170
+ * Result.withDefault(defaultValue, this.run(json));
171
+ * }
172
+ *
173
+ * number().runWithDefault(5, json)
174
+ * ```
175
+ * Unfortunately, the type of `defaultValue: A` on the method causes issues
176
+ * with type inference on the `object` decoder in some situations. While these
177
+ * inference issues can be solved by providing the optional type argument for
178
+ * `object`s, the extra trouble and confusion doesn't seem worth it.
179
+ */
180
+ var withDefault = function (defaultValue, r) {
181
+ return r.ok === true ? r.result : defaultValue;
182
+ };
183
+ /**
184
+ * Return the successful result, or throw an error.
185
+ */
186
+ var withException = function (r) {
187
+ if (r.ok === true) {
188
+ return r.result;
189
+ }
190
+ else {
191
+ throw r.error;
192
+ }
193
+ };
194
+ /**
195
+ * Apply `f` to the result of an `Ok`, or pass the error through.
196
+ */
197
+ var map = function (f, r) {
198
+ return r.ok === true ? ok(f(r.result)) : r;
199
+ };
200
+ /**
201
+ * Apply `f` to the result of two `Ok`s, or pass an error through. If both
202
+ * `Result`s are errors then the first one is returned.
203
+ */
204
+ var map2 = function (f, ar, br) {
205
+ return ar.ok === false ? ar :
206
+ br.ok === false ? br :
207
+ ok(f(ar.result, br.result));
208
+ };
209
+ /**
210
+ * Apply `f` to the error of an `Err`, or pass the success through.
211
+ */
212
+ var mapError = function (f, r) {
213
+ return r.ok === true ? r : err(f(r.error));
214
+ };
215
+ /**
216
+ * Chain together a sequence of computations that may fail, similar to a
217
+ * `Promise`. If the first computation fails then the error will propagate
218
+ * through. If it succeeds, then `f` will be applied to the value, returning a
219
+ * new `Result`.
220
+ */
221
+ var andThen = function (f, r) {
222
+ return r.ok === true ? f(r.result) : r;
223
+ };
224
+
225
+ /*! *****************************************************************************
226
+ Copyright (c) Microsoft Corporation.
227
+
228
+ Permission to use, copy, modify, and/or distribute this software for any
229
+ purpose with or without fee is hereby granted.
230
+
231
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
232
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
233
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
234
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
235
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
236
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
237
+ PERFORMANCE OF THIS SOFTWARE.
238
+ ***************************************************************************** */
239
+ /* global Reflect, Promise */
240
+
241
+
242
+
243
+ var __assign = function() {
244
+ __assign = Object.assign || function __assign(t) {
245
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
246
+ s = arguments[i];
247
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
248
+ }
249
+ return t;
250
+ };
251
+ return __assign.apply(this, arguments);
252
+ };
253
+
254
+ function __rest(s, e) {
255
+ var t = {};
256
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
257
+ t[p] = s[p];
258
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
259
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
260
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
261
+ t[p[i]] = s[p[i]];
262
+ }
263
+ return t;
264
+ }
265
+
266
+ function isEqual(a, b) {
267
+ if (a === b) {
268
+ return true;
269
+ }
270
+ if (a === null && b === null) {
271
+ return true;
272
+ }
273
+ if (typeof (a) !== typeof (b)) {
274
+ return false;
275
+ }
276
+ if (typeof (a) === 'object') {
277
+ // Array
278
+ if (Array.isArray(a)) {
279
+ if (!Array.isArray(b)) {
280
+ return false;
281
+ }
282
+ if (a.length !== b.length) {
283
+ return false;
284
+ }
285
+ for (var i = 0; i < a.length; i++) {
286
+ if (!isEqual(a[i], b[i])) {
287
+ return false;
288
+ }
289
+ }
290
+ return true;
291
+ }
292
+ // Hash table
293
+ var keys = Object.keys(a);
294
+ if (keys.length !== Object.keys(b).length) {
295
+ return false;
296
+ }
297
+ for (var i = 0; i < keys.length; i++) {
298
+ if (!b.hasOwnProperty(keys[i])) {
299
+ return false;
300
+ }
301
+ if (!isEqual(a[keys[i]], b[keys[i]])) {
302
+ return false;
303
+ }
304
+ }
305
+ return true;
306
+ }
307
+ }
308
+ /*
309
+ * Helpers
310
+ */
311
+ var isJsonArray = function (json) { return Array.isArray(json); };
312
+ var isJsonObject = function (json) {
313
+ return typeof json === 'object' && json !== null && !isJsonArray(json);
314
+ };
315
+ var typeString = function (json) {
316
+ switch (typeof json) {
317
+ case 'string':
318
+ return 'a string';
319
+ case 'number':
320
+ return 'a number';
321
+ case 'boolean':
322
+ return 'a boolean';
323
+ case 'undefined':
324
+ return 'undefined';
325
+ case 'object':
326
+ if (json instanceof Array) {
327
+ return 'an array';
328
+ }
329
+ else if (json === null) {
330
+ return 'null';
331
+ }
332
+ else {
333
+ return 'an object';
334
+ }
335
+ default:
336
+ return JSON.stringify(json);
337
+ }
338
+ };
339
+ var expectedGot = function (expected, got) {
340
+ return "expected " + expected + ", got " + typeString(got);
341
+ };
342
+ var printPath = function (paths) {
343
+ return paths.map(function (path) { return (typeof path === 'string' ? "." + path : "[" + path + "]"); }).join('');
344
+ };
345
+ var prependAt = function (newAt, _a) {
346
+ var at = _a.at, rest = __rest(_a, ["at"]);
347
+ return (__assign({ at: newAt + (at || '') }, rest));
348
+ };
349
+ /**
350
+ * Decoders transform json objects with unknown structure into known and
351
+ * verified forms. You can create objects of type `Decoder<A>` with either the
352
+ * primitive decoder functions, such as `boolean()` and `string()`, or by
353
+ * applying higher-order decoders to the primitives, such as `array(boolean())`
354
+ * or `dict(string())`.
355
+ *
356
+ * Each of the decoder functions are available both as a static method on
357
+ * `Decoder` and as a function alias -- for example the string decoder is
358
+ * defined at `Decoder.string()`, but is also aliased to `string()`. Using the
359
+ * function aliases exported with the library is recommended.
360
+ *
361
+ * `Decoder` exposes a number of 'run' methods, which all decode json in the
362
+ * same way, but communicate success and failure in different ways. The `map`
363
+ * and `andThen` methods modify decoders without having to call a 'run' method.
364
+ *
365
+ * Alternatively, the main decoder `run()` method returns an object of type
366
+ * `Result<A, DecoderError>`. This library provides a number of helper
367
+ * functions for dealing with the `Result` type, so you can do all the same
368
+ * things with a `Result` as with the decoder methods.
369
+ */
370
+ var Decoder = /** @class */ (function () {
371
+ /**
372
+ * The Decoder class constructor is kept private to separate the internal
373
+ * `decode` function from the external `run` function. The distinction
374
+ * between the two functions is that `decode` returns a
375
+ * `Partial<DecoderError>` on failure, which contains an unfinished error
376
+ * report. When `run` is called on a decoder, the relevant series of `decode`
377
+ * calls is made, and then on failure the resulting `Partial<DecoderError>`
378
+ * is turned into a `DecoderError` by filling in the missing information.
379
+ *
380
+ * While hiding the constructor may seem restrictive, leveraging the
381
+ * provided decoder combinators and helper functions such as
382
+ * `andThen` and `map` should be enough to build specialized decoders as
383
+ * needed.
384
+ */
385
+ function Decoder(decode) {
386
+ var _this = this;
387
+ this.decode = decode;
388
+ /**
389
+ * Run the decoder and return a `Result` with either the decoded value or a
390
+ * `DecoderError` containing the json input, the location of the error, and
391
+ * the error message.
392
+ *
393
+ * Examples:
394
+ * ```
395
+ * number().run(12)
396
+ * // => {ok: true, result: 12}
397
+ *
398
+ * string().run(9001)
399
+ * // =>
400
+ * // {
401
+ * // ok: false,
402
+ * // error: {
403
+ * // kind: 'DecoderError',
404
+ * // input: 9001,
405
+ * // at: 'input',
406
+ * // message: 'expected a string, got 9001'
407
+ * // }
408
+ * // }
409
+ * ```
410
+ */
411
+ this.run = function (json) {
412
+ return mapError(function (error) { return ({
413
+ kind: 'DecoderError',
414
+ input: json,
415
+ at: 'input' + (error.at || ''),
416
+ message: error.message || ''
417
+ }); }, _this.decode(json));
418
+ };
419
+ /**
420
+ * Run the decoder as a `Promise`.
421
+ */
422
+ this.runPromise = function (json) { return asPromise(_this.run(json)); };
423
+ /**
424
+ * Run the decoder and return the value on success, or throw an exception
425
+ * with a formatted error string.
426
+ */
427
+ this.runWithException = function (json) { return withException(_this.run(json)); };
428
+ /**
429
+ * Construct a new decoder that applies a transformation to the decoded
430
+ * result. If the decoder succeeds then `f` will be applied to the value. If
431
+ * it fails the error will propagated through.
432
+ *
433
+ * Example:
434
+ * ```
435
+ * number().map(x => x * 5).run(10)
436
+ * // => {ok: true, result: 50}
437
+ * ```
438
+ */
439
+ this.map = function (f) {
440
+ return new Decoder(function (json) { return map(f, _this.decode(json)); });
441
+ };
442
+ /**
443
+ * Chain together a sequence of decoders. The first decoder will run, and
444
+ * then the function will determine what decoder to run second. If the result
445
+ * of the first decoder succeeds then `f` will be applied to the decoded
446
+ * value. If it fails the error will propagate through.
447
+ *
448
+ * This is a very powerful method -- it can act as both the `map` and `where`
449
+ * methods, can improve error messages for edge cases, and can be used to
450
+ * make a decoder for custom types.
451
+ *
452
+ * Example of adding an error message:
453
+ * ```
454
+ * const versionDecoder = valueAt(['version'], number());
455
+ * const infoDecoder3 = object({a: boolean()});
456
+ *
457
+ * const decoder = versionDecoder.andThen(version => {
458
+ * switch (version) {
459
+ * case 3:
460
+ * return infoDecoder3;
461
+ * default:
462
+ * return fail(`Unable to decode info, version ${version} is not supported.`);
463
+ * }
464
+ * });
465
+ *
466
+ * decoder.run({version: 3, a: true})
467
+ * // => {ok: true, result: {a: true}}
468
+ *
469
+ * decoder.run({version: 5, x: 'abc'})
470
+ * // =>
471
+ * // {
472
+ * // ok: false,
473
+ * // error: {... message: 'Unable to decode info, version 5 is not supported.'}
474
+ * // }
475
+ * ```
476
+ *
477
+ * Example of decoding a custom type:
478
+ * ```
479
+ * // nominal type for arrays with a length of at least one
480
+ * type NonEmptyArray<T> = T[] & { __nonEmptyArrayBrand__: void };
481
+ *
482
+ * const nonEmptyArrayDecoder = <T>(values: Decoder<T>): Decoder<NonEmptyArray<T>> =>
483
+ * array(values).andThen(arr =>
484
+ * arr.length > 0
485
+ * ? succeed(createNonEmptyArray(arr))
486
+ * : fail(`expected a non-empty array, got an empty array`)
487
+ * );
488
+ * ```
489
+ */
490
+ this.andThen = function (f) {
491
+ return new Decoder(function (json) {
492
+ return andThen(function (value) { return f(value).decode(json); }, _this.decode(json));
493
+ });
494
+ };
495
+ /**
496
+ * Add constraints to a decoder _without_ changing the resulting type. The
497
+ * `test` argument is a predicate function which returns true for valid
498
+ * inputs. When `test` fails on an input, the decoder fails with the given
499
+ * `errorMessage`.
500
+ *
501
+ * ```
502
+ * const chars = (length: number): Decoder<string> =>
503
+ * string().where(
504
+ * (s: string) => s.length === length,
505
+ * `expected a string of length ${length}`
506
+ * );
507
+ *
508
+ * chars(5).run('12345')
509
+ * // => {ok: true, result: '12345'}
510
+ *
511
+ * chars(2).run('HELLO')
512
+ * // => {ok: false, error: {... message: 'expected a string of length 2'}}
513
+ *
514
+ * chars(12).run(true)
515
+ * // => {ok: false, error: {... message: 'expected a string, got a boolean'}}
516
+ * ```
517
+ */
518
+ this.where = function (test, errorMessage) {
519
+ return _this.andThen(function (value) { return (test(value) ? Decoder.succeed(value) : Decoder.fail(errorMessage)); });
520
+ };
521
+ }
522
+ /**
523
+ * Decoder primitive that validates strings, and fails on all other input.
524
+ */
525
+ Decoder.string = function () {
526
+ return new Decoder(function (json) {
527
+ return typeof json === 'string'
528
+ ? ok(json)
529
+ : err({ message: expectedGot('a string', json) });
530
+ });
531
+ };
532
+ /**
533
+ * Decoder primitive that validates numbers, and fails on all other input.
534
+ */
535
+ Decoder.number = function () {
536
+ return new Decoder(function (json) {
537
+ return typeof json === 'number'
538
+ ? ok(json)
539
+ : err({ message: expectedGot('a number', json) });
540
+ });
541
+ };
542
+ /**
543
+ * Decoder primitive that validates booleans, and fails on all other input.
544
+ */
545
+ Decoder.boolean = function () {
546
+ return new Decoder(function (json) {
547
+ return typeof json === 'boolean'
548
+ ? ok(json)
549
+ : err({ message: expectedGot('a boolean', json) });
550
+ });
551
+ };
552
+ Decoder.constant = function (value) {
553
+ return new Decoder(function (json) {
554
+ return isEqual(json, value)
555
+ ? ok(value)
556
+ : err({ message: "expected " + JSON.stringify(value) + ", got " + JSON.stringify(json) });
557
+ });
558
+ };
559
+ Decoder.object = function (decoders) {
560
+ return new Decoder(function (json) {
561
+ if (isJsonObject(json) && decoders) {
562
+ var obj = {};
563
+ for (var key in decoders) {
564
+ if (decoders.hasOwnProperty(key)) {
565
+ var r = decoders[key].decode(json[key]);
566
+ if (r.ok === true) {
567
+ // tslint:disable-next-line:strict-type-predicates
568
+ if (r.result !== undefined) {
569
+ obj[key] = r.result;
570
+ }
571
+ }
572
+ else if (json[key] === undefined) {
573
+ return err({ message: "the key '" + key + "' is required but was not present" });
574
+ }
575
+ else {
576
+ return err(prependAt("." + key, r.error));
577
+ }
578
+ }
579
+ }
580
+ return ok(obj);
581
+ }
582
+ else if (isJsonObject(json)) {
583
+ return ok(json);
584
+ }
585
+ else {
586
+ return err({ message: expectedGot('an object', json) });
587
+ }
588
+ });
589
+ };
590
+ Decoder.array = function (decoder) {
591
+ return new Decoder(function (json) {
592
+ if (isJsonArray(json) && decoder) {
593
+ var decodeValue_1 = function (v, i) {
594
+ return mapError(function (err$$1) { return prependAt("[" + i + "]", err$$1); }, decoder.decode(v));
595
+ };
596
+ return json.reduce(function (acc, v, i) {
597
+ return map2(function (arr, result) { return arr.concat([result]); }, acc, decodeValue_1(v, i));
598
+ }, ok([]));
599
+ }
600
+ else if (isJsonArray(json)) {
601
+ return ok(json);
602
+ }
603
+ else {
604
+ return err({ message: expectedGot('an array', json) });
605
+ }
606
+ });
607
+ };
608
+ Decoder.tuple = function (decoders) {
609
+ return new Decoder(function (json) {
610
+ if (isJsonArray(json)) {
611
+ if (json.length !== decoders.length) {
612
+ return err({
613
+ message: "expected a tuple of length " + decoders.length + ", got one of length " + json.length
614
+ });
615
+ }
616
+ var result = [];
617
+ for (var i = 0; i < decoders.length; i++) {
618
+ var nth = decoders[i].decode(json[i]);
619
+ if (nth.ok) {
620
+ result[i] = nth.result;
621
+ }
622
+ else {
623
+ return err(prependAt("[" + i + "]", nth.error));
624
+ }
625
+ }
626
+ return ok(result);
627
+ }
628
+ else {
629
+ return err({ message: expectedGot("a tuple of length " + decoders.length, json) });
630
+ }
631
+ });
632
+ };
633
+ Decoder.union = function (ad, bd) {
634
+ var decoders = [];
635
+ for (var _i = 2; _i < arguments.length; _i++) {
636
+ decoders[_i - 2] = arguments[_i];
637
+ }
638
+ return Decoder.oneOf.apply(Decoder, [ad, bd].concat(decoders));
639
+ };
640
+ Decoder.intersection = function (ad, bd) {
641
+ var ds = [];
642
+ for (var _i = 2; _i < arguments.length; _i++) {
643
+ ds[_i - 2] = arguments[_i];
644
+ }
645
+ return new Decoder(function (json) {
646
+ return [ad, bd].concat(ds).reduce(function (acc, decoder) { return map2(Object.assign, acc, decoder.decode(json)); }, ok({}));
647
+ });
648
+ };
649
+ /**
650
+ * Escape hatch to bypass validation. Always succeeds and types the result as
651
+ * `any`. Useful for defining decoders incrementally, particularly for
652
+ * complex objects.
653
+ *
654
+ * Example:
655
+ * ```
656
+ * interface User {
657
+ * name: string;
658
+ * complexUserData: ComplexType;
659
+ * }
660
+ *
661
+ * const userDecoder: Decoder<User> = object({
662
+ * name: string(),
663
+ * complexUserData: anyJson()
664
+ * });
665
+ * ```
666
+ */
667
+ Decoder.anyJson = function () { return new Decoder(function (json) { return ok(json); }); };
668
+ /**
669
+ * Decoder identity function which always succeeds and types the result as
670
+ * `unknown`.
671
+ */
672
+ Decoder.unknownJson = function () {
673
+ return new Decoder(function (json) { return ok(json); });
674
+ };
675
+ /**
676
+ * Decoder for json objects where the keys are unknown strings, but the values
677
+ * should all be of the same type.
678
+ *
679
+ * Example:
680
+ * ```
681
+ * dict(number()).run({chocolate: 12, vanilla: 10, mint: 37});
682
+ * // => {ok: true, result: {chocolate: 12, vanilla: 10, mint: 37}}
683
+ * ```
684
+ */
685
+ Decoder.dict = function (decoder) {
686
+ return new Decoder(function (json) {
687
+ if (isJsonObject(json)) {
688
+ var obj = {};
689
+ for (var key in json) {
690
+ if (json.hasOwnProperty(key)) {
691
+ var r = decoder.decode(json[key]);
692
+ if (r.ok === true) {
693
+ obj[key] = r.result;
694
+ }
695
+ else {
696
+ return err(prependAt("." + key, r.error));
697
+ }
698
+ }
699
+ }
700
+ return ok(obj);
701
+ }
702
+ else {
703
+ return err({ message: expectedGot('an object', json) });
704
+ }
705
+ });
706
+ };
707
+ /**
708
+ * Decoder for values that may be `undefined`. This is primarily helpful for
709
+ * decoding interfaces with optional fields.
710
+ *
711
+ * Example:
712
+ * ```
713
+ * interface User {
714
+ * id: number;
715
+ * isOwner?: boolean;
716
+ * }
717
+ *
718
+ * const decoder: Decoder<User> = object({
719
+ * id: number(),
720
+ * isOwner: optional(boolean())
721
+ * });
722
+ * ```
723
+ */
724
+ Decoder.optional = function (decoder) {
725
+ return new Decoder(function (json) { return (json === undefined || json === null ? ok(undefined) : decoder.decode(json)); });
726
+ };
727
+ /**
728
+ * Decoder that attempts to run each decoder in `decoders` and either succeeds
729
+ * with the first successful decoder, or fails after all decoders have failed.
730
+ *
731
+ * Note that `oneOf` expects the decoders to all have the same return type,
732
+ * while `union` creates a decoder for the union type of all the input
733
+ * decoders.
734
+ *
735
+ * Examples:
736
+ * ```
737
+ * oneOf(string(), number().map(String))
738
+ * oneOf(constant('start'), constant('stop'), succeed('unknown'))
739
+ * ```
740
+ */
741
+ Decoder.oneOf = function () {
742
+ var decoders = [];
743
+ for (var _i = 0; _i < arguments.length; _i++) {
744
+ decoders[_i] = arguments[_i];
745
+ }
746
+ return new Decoder(function (json) {
747
+ var errors = [];
748
+ for (var i = 0; i < decoders.length; i++) {
749
+ var r = decoders[i].decode(json);
750
+ if (r.ok === true) {
751
+ return r;
752
+ }
753
+ else {
754
+ errors[i] = r.error;
755
+ }
756
+ }
757
+ var errorsList = errors
758
+ .map(function (error) { return "at error" + (error.at || '') + ": " + error.message; })
759
+ .join('", "');
760
+ return err({
761
+ message: "expected a value matching one of the decoders, got the errors [\"" + errorsList + "\"]"
762
+ });
763
+ });
764
+ };
765
+ /**
766
+ * Decoder that always succeeds with either the decoded value, or a fallback
767
+ * default value.
768
+ */
769
+ Decoder.withDefault = function (defaultValue, decoder) {
770
+ return new Decoder(function (json) {
771
+ return ok(withDefault(defaultValue, decoder.decode(json)));
772
+ });
773
+ };
774
+ /**
775
+ * Decoder that pulls a specific field out of a json structure, instead of
776
+ * decoding and returning the full structure. The `paths` array describes the
777
+ * object keys and array indices to traverse, so that values can be pulled out
778
+ * of a nested structure.
779
+ *
780
+ * Example:
781
+ * ```
782
+ * const decoder = valueAt(['a', 'b', 0], string());
783
+ *
784
+ * decoder.run({a: {b: ['surprise!']}})
785
+ * // => {ok: true, result: 'surprise!'}
786
+ *
787
+ * decoder.run({a: {x: 'cats'}})
788
+ * // => {ok: false, error: {... at: 'input.a.b[0]' message: 'path does not exist'}}
789
+ * ```
790
+ *
791
+ * Note that the `decoder` is ran on the value found at the last key in the
792
+ * path, even if the last key is not found. This allows the `optional`
793
+ * decoder to succeed when appropriate.
794
+ * ```
795
+ * const optionalDecoder = valueAt(['a', 'b', 'c'], optional(string()));
796
+ *
797
+ * optionalDecoder.run({a: {b: {c: 'surprise!'}}})
798
+ * // => {ok: true, result: 'surprise!'}
799
+ *
800
+ * optionalDecoder.run({a: {b: 'cats'}})
801
+ * // => {ok: false, error: {... at: 'input.a.b.c' message: 'expected an object, got "cats"'}
802
+ *
803
+ * optionalDecoder.run({a: {b: {z: 1}}})
804
+ * // => {ok: true, result: undefined}
805
+ * ```
806
+ */
807
+ Decoder.valueAt = function (paths, decoder) {
808
+ return new Decoder(function (json) {
809
+ var jsonAtPath = json;
810
+ for (var i = 0; i < paths.length; i++) {
811
+ if (jsonAtPath === undefined) {
812
+ return err({
813
+ at: printPath(paths.slice(0, i + 1)),
814
+ message: 'path does not exist'
815
+ });
816
+ }
817
+ else if (typeof paths[i] === 'string' && !isJsonObject(jsonAtPath)) {
818
+ return err({
819
+ at: printPath(paths.slice(0, i + 1)),
820
+ message: expectedGot('an object', jsonAtPath)
821
+ });
822
+ }
823
+ else if (typeof paths[i] === 'number' && !isJsonArray(jsonAtPath)) {
824
+ return err({
825
+ at: printPath(paths.slice(0, i + 1)),
826
+ message: expectedGot('an array', jsonAtPath)
827
+ });
828
+ }
829
+ else {
830
+ jsonAtPath = jsonAtPath[paths[i]];
831
+ }
832
+ }
833
+ return mapError(function (error) {
834
+ return jsonAtPath === undefined
835
+ ? { at: printPath(paths), message: 'path does not exist' }
836
+ : prependAt(printPath(paths), error);
837
+ }, decoder.decode(jsonAtPath));
838
+ });
839
+ };
840
+ /**
841
+ * Decoder that ignores the input json and always succeeds with `fixedValue`.
842
+ */
843
+ Decoder.succeed = function (fixedValue) {
844
+ return new Decoder(function (json) { return ok(fixedValue); });
845
+ };
846
+ /**
847
+ * Decoder that ignores the input json and always fails with `errorMessage`.
848
+ */
849
+ Decoder.fail = function (errorMessage) {
850
+ return new Decoder(function (json) { return err({ message: errorMessage }); });
851
+ };
852
+ /**
853
+ * Decoder that allows for validating recursive data structures. Unlike with
854
+ * functions, decoders assigned to variables can't reference themselves
855
+ * before they are fully defined. We can avoid prematurely referencing the
856
+ * decoder by wrapping it in a function that won't be called until use, at
857
+ * which point the decoder has been defined.
858
+ *
859
+ * Example:
860
+ * ```
861
+ * interface Comment {
862
+ * msg: string;
863
+ * replies: Comment[];
864
+ * }
865
+ *
866
+ * const decoder: Decoder<Comment> = object({
867
+ * msg: string(),
868
+ * replies: lazy(() => array(decoder))
869
+ * });
870
+ * ```
871
+ */
872
+ Decoder.lazy = function (mkDecoder) {
873
+ return new Decoder(function (json) { return mkDecoder().decode(json); });
874
+ };
875
+ return Decoder;
876
+ }());
877
+
878
+ /* tslint:disable:variable-name */
879
+ /** See `Decoder.string` */
880
+ var string = Decoder.string;
881
+ /** See `Decoder.number` */
882
+ var number = Decoder.number;
883
+ /** See `Decoder.boolean` */
884
+ var boolean = Decoder.boolean;
885
+ /** See `Decoder.anyJson` */
886
+ var anyJson = Decoder.anyJson;
887
+ /** See `Decoder.unknownJson` */
888
+ Decoder.unknownJson;
889
+ /** See `Decoder.constant` */
890
+ var constant = Decoder.constant;
891
+ /** See `Decoder.object` */
892
+ var object = Decoder.object;
893
+ /** See `Decoder.array` */
894
+ var array = Decoder.array;
895
+ /** See `Decoder.tuple` */
896
+ Decoder.tuple;
897
+ /** See `Decoder.dict` */
898
+ Decoder.dict;
899
+ /** See `Decoder.optional` */
900
+ var optional = Decoder.optional;
901
+ /** See `Decoder.oneOf` */
902
+ var oneOf = Decoder.oneOf;
903
+ /** See `Decoder.union` */
904
+ Decoder.union;
905
+ /** See `Decoder.intersection` */
906
+ Decoder.intersection;
907
+ /** See `Decoder.withDefault` */
908
+ Decoder.withDefault;
909
+ /** See `Decoder.valueAt` */
910
+ Decoder.valueAt;
911
+ /** See `Decoder.succeed` */
912
+ Decoder.succeed;
913
+ /** See `Decoder.fail` */
914
+ Decoder.fail;
915
+ /** See `Decoder.lazy` */
916
+ Decoder.lazy;
917
+
918
+ const nonEmptyStringDecoder = string().where((s) => s.length > 0, "Expected a non-empty string");
919
+ number().where((num) => num >= 0, "Expected a non-negative number");
920
+ const iconDecoder = object({
921
+ src: nonEmptyStringDecoder,
922
+ size: optional(string()),
923
+ type: optional(string())
924
+ });
925
+ const imageDecoder = object({
926
+ src: nonEmptyStringDecoder,
927
+ size: optional(string()),
928
+ type: optional(string()),
929
+ label: optional(string())
930
+ });
931
+ object({
932
+ appId: nonEmptyStringDecoder,
933
+ instanceId: optional(string()),
934
+ name: optional(string()),
935
+ version: optional(string()),
936
+ title: optional(string()),
937
+ tooltip: optional(string()),
938
+ description: optional(string()),
939
+ icons: optional(array(iconDecoder)),
940
+ images: optional(array(imageDecoder)),
941
+ });
942
+ const appIdentifierDecoder = object({
943
+ appId: nonEmptyStringDecoder,
944
+ instanceId: optional(string())
945
+ });
946
+ const targetAppDecoder = oneOf(nonEmptyStringDecoder, appIdentifierDecoder);
947
+ const contextDecoder = object({
948
+ type: nonEmptyStringDecoder,
949
+ name: optional(nonEmptyStringDecoder),
950
+ id: optional(anyJson()),
951
+ });
952
+ const optionalContextDecoder = optional(contextDecoder);
953
+ const optionalTargetApp = optional(appIdentifierDecoder);
954
+ const optionalAppIdentifier = optional(targetAppDecoder);
955
+ const optionalNonEmptyStringDecoder = optional(nonEmptyStringDecoder);
956
+ const SystemMethodActionDecider = oneOf(constant(PrivateChannelEventMethods.OnAddContextListener), constant(PrivateChannelEventMethods.OnUnsubscribe), constant(PrivateChannelEventMethods.OnDisconnect));
957
+ const SystemMethodEventPayloadDecoder = object({
958
+ channelId: nonEmptyStringDecoder,
959
+ clientId: nonEmptyStringDecoder,
960
+ contextType: optional(string()),
961
+ replayContextTypes: optional(array(string()))
962
+ });
963
+ const SystemMethodInvocationArgumentDecoder = object({
964
+ action: SystemMethodActionDecider,
965
+ payload: SystemMethodEventPayloadDecoder
966
+ });
967
+ const ContextListenerResponseDecoder = object({
968
+ listenerInvoked: optional(boolean())
969
+ });
970
+ object({
971
+ meta: object({
972
+ responseMethodName: nonEmptyStringDecoder
973
+ }),
974
+ context: contextDecoder
975
+ });
976
+
977
+ class GlueController {
978
+ constructor(channelsParser) {
979
+ this.channelsParser = channelsParser;
980
+ this.defaultGluePromiseTimeout = 120000;
981
+ }
982
+ get gluePromise() {
983
+ return this.glueInitPromise.then(this.initializeLogger.bind(this));
984
+ }
985
+ initialize(glue) {
986
+ this.glue = glue;
987
+ this.resolveGluePromise();
988
+ }
989
+ initializeFailed(reason) {
990
+ this.rejectGluePromise(reason);
991
+ }
992
+ createGluePromise() {
993
+ this.glueInitPromise = promisePlus(() => {
994
+ return new Promise((resolve, reject) => {
995
+ this.resolveGluePromise = resolve;
996
+ this.rejectGluePromise = reject;
997
+ });
998
+ }, this.defaultGluePromiseTimeout, `Timeout of ${this.defaultGluePromiseTimeout}ms waiting for Glue to initialize`);
999
+ }
1000
+ get logger() {
1001
+ return this._logger;
1002
+ }
1003
+ validateGlue(glue) {
1004
+ if (typeof glue !== "object" || Array.isArray(glue)) {
1005
+ return { isValid: false, error: { message: "Glue is not a valid object" } };
1006
+ }
1007
+ const apisToValidate = Object.keys(glue);
1008
+ const missingApis = defaultGlue42APIs.filter((api) => !apisToValidate.includes(api));
1009
+ if (missingApis.length) {
1010
+ return { isValid: false, error: { message: `Fdc3 cannot initialize correctly - Glue is missing the following ${missingApis.length > 1 ? "properties" : "property"}: ${missingApis.join(", ")}` } };
1011
+ }
1012
+ return { isValid: true };
1013
+ }
1014
+ interopInstance() {
1015
+ return this.glue.interop.instance;
1016
+ }
1017
+ getApplication(name) {
1018
+ return this.glue.appManager.application(name);
1019
+ }
1020
+ getApplicationInstances(appName) {
1021
+ return this.glue.appManager.instances().filter(inst => inst.application.name === appName);
1022
+ }
1023
+ getAppInstanceById(id) {
1024
+ return this.glue.appManager.instances().find(inst => inst.id === id);
1025
+ }
1026
+ findIntents(intentFilter) {
1027
+ return __awaiter(this, void 0, void 0, function* () {
1028
+ return this.glue.intents.find(intentFilter);
1029
+ });
1030
+ }
1031
+ raiseIntent(request) {
1032
+ return __awaiter(this, void 0, void 0, function* () {
1033
+ return this.glue.intents.raise(request);
1034
+ });
1035
+ }
1036
+ addIntentListener(intent, handler) {
1037
+ const registerMethodExists = this.glue.intents.register;
1038
+ return registerMethodExists
1039
+ ? this.glue.intents.register(intent, handler)
1040
+ : this.glue.intents.addIntentListener(intent, handler);
1041
+ }
1042
+ getAllContexts() {
1043
+ return this.glue.contexts.all();
1044
+ }
1045
+ getContext(contextId) {
1046
+ return __awaiter(this, void 0, void 0, function* () {
1047
+ return this.glue.contexts.get(contextId);
1048
+ });
1049
+ }
1050
+ updateContext(contextId, data) {
1051
+ return __awaiter(this, void 0, void 0, function* () {
1052
+ return this.glue.contexts.update(contextId, data);
1053
+ });
1054
+ }
1055
+ updateContextWithLatestFdc3Type(contextId, context) {
1056
+ return __awaiter(this, void 0, void 0, function* () {
1057
+ const prevContextData = yield this.getContext(contextId);
1058
+ if (!isValidNonEmptyObject(prevContextData)) {
1059
+ return this.updateContext(contextId, {
1060
+ data: this.channelsParser.parseFDC3ContextToGlueContexts(context),
1061
+ latest_fdc3_type: this.channelsParser.mapFDC3TypeToChannelsDelimiter(context.type)
1062
+ });
1063
+ }
1064
+ return this.updateContext(contextId, Object.assign(Object.assign({}, prevContextData), { data: Object.assign(Object.assign({}, prevContextData.data), this.channelsParser.parseFDC3ContextToGlueContexts(context)), latest_fdc3_type: this.channelsParser.mapFDC3TypeToChannelsDelimiter(context.type) }));
1065
+ });
1066
+ }
1067
+ channelsUpdate(channelId, context) {
1068
+ return __awaiter(this, void 0, void 0, function* () {
1069
+ const parsedData = this.channelsParser.parseFDC3ContextToGlueContexts(context);
1070
+ return this.glue.channels.publish(parsedData, channelId);
1071
+ });
1072
+ }
1073
+ joinChannel(channelId) {
1074
+ return __awaiter(this, void 0, void 0, function* () {
1075
+ return this.glue.channels.join(channelId);
1076
+ });
1077
+ }
1078
+ leaveChannel() {
1079
+ return __awaiter(this, void 0, void 0, function* () {
1080
+ return this.glue.channels.leave();
1081
+ });
1082
+ }
1083
+ getCurrentChannel() {
1084
+ return this.glue.channels.my();
1085
+ }
1086
+ setOnChannelChanged(callback) {
1087
+ return this.glue.channels.changed(callback);
1088
+ }
1089
+ getAllChannels() {
1090
+ return __awaiter(this, void 0, void 0, function* () {
1091
+ return this.glue.channels.all();
1092
+ });
1093
+ }
1094
+ listAllChannels() {
1095
+ return __awaiter(this, void 0, void 0, function* () {
1096
+ return this.glue.channels.list();
1097
+ });
1098
+ }
1099
+ getChannel(channelId) {
1100
+ return __awaiter(this, void 0, void 0, function* () {
1101
+ return this.glue.channels.get(channelId);
1102
+ });
1103
+ }
1104
+ getMyWindow() {
1105
+ const win = this.glue.windows.my();
1106
+ return isValidNonEmptyObject(win) ? win : undefined;
1107
+ }
1108
+ getMyInteropInstanceId() {
1109
+ return this.glue.interop.instance.instance;
1110
+ }
1111
+ getGlueVersion() {
1112
+ var _a;
1113
+ return (_a = this.glue) === null || _a === void 0 ? void 0 : _a.version;
1114
+ }
1115
+ registerOnInstanceStopped(cb) {
1116
+ return this.glue.appManager.onInstanceStopped(cb);
1117
+ }
1118
+ invokeMethod(methodName, instance, argumentObj) {
1119
+ return __awaiter(this, void 0, void 0, function* () {
1120
+ const args = ContextListenerResponseDecoder.runWithException(argumentObj);
1121
+ return this.glue.interop.invoke(methodName, args, { instance });
1122
+ });
1123
+ }
1124
+ unregisterMethod(methodName) {
1125
+ return __awaiter(this, void 0, void 0, function* () {
1126
+ return this.glue.interop.unregister(methodName);
1127
+ });
1128
+ }
1129
+ invokeSystemMethod(argumentObj) {
1130
+ const args = SystemMethodInvocationArgumentDecoder.runWithException(argumentObj);
1131
+ const target = args.payload.clientId;
1132
+ return this.glue.interop.invoke(Glue42FDC3SystemMethod, args, { instance: target });
1133
+ }
1134
+ registerMethod(name, handler) {
1135
+ return this.glue.interop.register(name, handler);
1136
+ }
1137
+ getInteropMethods(filter) {
1138
+ return this.glue.interop.methods(filter);
1139
+ }
1140
+ channelsSubscribe(callback) {
1141
+ const didReplay = { replayed: false };
1142
+ return this.glue.channels.subscribe((_, context, updaterId) => __awaiter(this, void 0, void 0, function* () {
1143
+ if (this.isUpdateFromMe(updaterId) || !context) {
1144
+ return;
1145
+ }
1146
+ const contextData = yield this.glue.contexts.get(`${glueChannelNamePrefix}${context.name}`);
1147
+ if (!contextData.latest_fdc3_type) {
1148
+ return;
1149
+ }
1150
+ if (!didReplay.replayed) {
1151
+ this.invokePreviouslyBroadcastedData(callback, contextData, this.getContextMetadata(updaterId));
1152
+ didReplay.replayed = true;
1153
+ return;
1154
+ }
1155
+ this.parseDataAndInvokeSubscribeCallback(callback, contextData, this.getContextMetadata(updaterId));
1156
+ }));
1157
+ }
1158
+ contextsSubscribe(contextName, callback) {
1159
+ const didReplay = { replayed: false };
1160
+ return this.glue.contexts.subscribe(contextName, (contextData, addedData, removed, _, extraData) => {
1161
+ if (this.isUpdateFromMe(extraData === null || extraData === void 0 ? void 0 : extraData.updaterId)) {
1162
+ return;
1163
+ }
1164
+ if (!this.checkIfAppChannelShouldInvokeInitialReplay(didReplay, contextData)) {
1165
+ return;
1166
+ }
1167
+ this.parseDataAndInvokeSubscribeCallback(callback, contextData, this.getContextMetadata(extraData === null || extraData === void 0 ? void 0 : extraData.updaterId));
1168
+ });
1169
+ }
1170
+ getInteropServers(methodFilter) {
1171
+ return this.glue.interop.servers(methodFilter);
1172
+ }
1173
+ initSubLogger(name) {
1174
+ return this.logger.subLogger(name);
1175
+ }
1176
+ invokePreviouslyBroadcastedData(callback, contextData, metadata) {
1177
+ Object.entries(contextData.data).forEach(([key, value]) => {
1178
+ if (!this.channelsParser.isFdc3DataKey(key)) {
1179
+ return;
1180
+ }
1181
+ const parsedData = Object.assign({ type: this.channelsParser.revertGlueParsedTypeToInitialFDC3Type(key) }, value);
1182
+ callback(parsedData, metadata);
1183
+ });
1184
+ }
1185
+ isUpdateFromMe(updaterId) {
1186
+ return this.glue.interop.instance.peerId === updaterId;
1187
+ }
1188
+ getContextMetadata(updaterId) {
1189
+ const instanceServer = this.glue.interop.servers().find((server) => server.peerId === updaterId);
1190
+ if (!instanceServer) {
1191
+ return;
1192
+ }
1193
+ return {
1194
+ source: {
1195
+ appId: instanceServer.applicationName,
1196
+ instanceId: instanceServer.instance
1197
+ }
1198
+ };
1199
+ }
1200
+ initializeLogger() {
1201
+ this._logger = this.glue.logger;
1202
+ }
1203
+ parseDataAndInvokeSubscribeCallback(callback, data, metadata) {
1204
+ const parsedData = this.channelsParser.parseContextsDataToInitialFDC3Data(data);
1205
+ callback(parsedData, metadata);
1206
+ }
1207
+ checkIfAppChannelShouldInvokeInitialReplay(didReplay, contextData) {
1208
+ if (!didReplay.replayed) {
1209
+ didReplay.replayed = true;
1210
+ return false;
1211
+ }
1212
+ if (!contextData.latest_fdc3_type) {
1213
+ return false;
1214
+ }
1215
+ return true;
1216
+ }
1217
+ }
1218
+
1219
+ const GLUE42_EVENT_NAME = "Glue42";
1220
+ const START = "start";
1221
+ const NOTIFY_STARTED = "notifyStarted";
1222
+ const REQUEST_GLUE = "requestGlue";
1223
+ const REQUEST_GLUE_RESPONSE = "requestGlueResponse";
1224
+ const FDC3_READY = "fdc3Ready";
1225
+
1226
+ class EventDispatcher {
1227
+ fireFdc3Ready() {
1228
+ const event = new Event(FDC3_READY);
1229
+ window.dispatchEvent(event);
1230
+ }
1231
+ fireNotifyStarted() {
1232
+ this.send(NOTIFY_STARTED);
1233
+ }
1234
+ fireRequestGlue() {
1235
+ this.send(REQUEST_GLUE);
1236
+ }
1237
+ send(eventName, message) {
1238
+ const payload = { glue42: { event: eventName, message } };
1239
+ const event = new CustomEvent(GLUE42_EVENT_NAME, { detail: payload });
1240
+ window.dispatchEvent(event);
1241
+ }
1242
+ }
1243
+
1244
+ class DesktopAgent {
1245
+ constructor(intentsController, applicationController, channelsController) {
1246
+ this.intentsController = intentsController;
1247
+ this.applicationController = applicationController;
1248
+ this.channelsController = channelsController;
1249
+ }
1250
+ toApi() {
1251
+ const api = {
1252
+ addContextListener: this.addContextListener.bind(this),
1253
+ addIntentListener: this.addIntentListener.bind(this),
1254
+ broadcast: this.broadcast.bind(this),
1255
+ createPrivateChannel: this.createPrivateChannel.bind(this),
1256
+ findInstances: this.findInstances.bind(this),
1257
+ findIntent: this.findIntent.bind(this),
1258
+ findIntentsByContext: this.findIntentsByContext.bind(this),
1259
+ getAppMetadata: this.getAppMetadata.bind(this),
1260
+ getCurrentChannel: this.getCurrentChannel.bind(this),
1261
+ getInfo: this.getInfo.bind(this),
1262
+ getOrCreateChannel: this.getOrCreateChannel.bind(this),
1263
+ getSystemChannels: this.getSystemChannels.bind(this),
1264
+ getUserChannels: this.getSystemChannels.bind(this),
1265
+ joinChannel: this.joinChannel.bind(this),
1266
+ joinUserChannel: this.joinUserChannel.bind(this),
1267
+ leaveCurrentChannel: this.leaveCurrentChannel.bind(this),
1268
+ open: this.open.bind(this),
1269
+ raiseIntent: this.raiseIntent.bind(this),
1270
+ raiseIntentForContext: this.raiseIntentForContext.bind(this),
1271
+ };
1272
+ return Object.freeze(api);
1273
+ }
1274
+ open(target, context) {
1275
+ return __awaiter(this, void 0, void 0, function* () {
1276
+ targetAppDecoder.runWithException(target);
1277
+ optionalContextDecoder.runWithException(context);
1278
+ return this.applicationController.open({ commandId: generateCommandId(), target, context });
1279
+ });
1280
+ }
1281
+ findInstances(app) {
1282
+ return __awaiter(this, void 0, void 0, function* () {
1283
+ appIdentifierDecoder.runWithException(app);
1284
+ return this.applicationController.findInstances({ commandId: generateCommandId(), appIdentifier: app });
1285
+ });
1286
+ }
1287
+ getAppMetadata(app) {
1288
+ return __awaiter(this, void 0, void 0, function* () {
1289
+ appIdentifierDecoder.runWithException(app);
1290
+ return this.applicationController.getAppMetadata({ commandId: generateCommandId(), appIdentifier: app });
1291
+ });
1292
+ }
1293
+ getInfo() {
1294
+ return __awaiter(this, void 0, void 0, function* () {
1295
+ return this.applicationController.getInfo({ commandId: generateCommandId() });
1296
+ });
1297
+ }
1298
+ broadcast(context) {
1299
+ return __awaiter(this, void 0, void 0, function* () {
1300
+ contextDecoder.runWithException(context);
1301
+ return this.channelsController.broadcast(generateCommandId(), context);
1302
+ });
1303
+ }
1304
+ addContextListener(contextType, handler) {
1305
+ return __awaiter(this, arguments, void 0, function* () {
1306
+ if (arguments.length === 1) {
1307
+ if (typeof contextType !== "function") {
1308
+ throw new Error("Please provide the handler as a function!");
1309
+ }
1310
+ return this.channelsController.addContextListener({ commandId: generateCommandId(), handler: contextType });
1311
+ }
1312
+ const contextTypeDecoder = optionalNonEmptyStringDecoder.runWithException(contextType);
1313
+ if (typeof handler !== "function") {
1314
+ throw new Error("Please provide the handler as a function!");
1315
+ }
1316
+ return this.channelsController.addContextListener({ commandId: generateCommandId(), handler, contextType: contextTypeDecoder });
1317
+ });
1318
+ }
1319
+ findIntent(intent, context, resultType) {
1320
+ return __awaiter(this, void 0, void 0, function* () {
1321
+ nonEmptyStringDecoder.runWithException(intent);
1322
+ const contextDecoderResult = optionalContextDecoder.run(context);
1323
+ if (!contextDecoderResult.ok) {
1324
+ throw new Error(`Invalid Context: ${contextDecoderResult.error}`);
1325
+ }
1326
+ optionalNonEmptyStringDecoder.runWithException(resultType);
1327
+ return this.intentsController.findIntent({ commandId: generateCommandId(), intent, context: contextDecoderResult.result, resultType });
1328
+ });
1329
+ }
1330
+ findIntentsByContext(context, resultType) {
1331
+ return __awaiter(this, void 0, void 0, function* () {
1332
+ const contextDecoderResult = contextDecoder.run(context);
1333
+ if (!contextDecoderResult.ok) {
1334
+ throw new Error(`Invalid Context: ${contextDecoderResult.error}`);
1335
+ }
1336
+ optionalNonEmptyStringDecoder.runWithException(resultType);
1337
+ return this.intentsController.findIntentsByContext({ commandId: generateCommandId(), context: contextDecoderResult.result, resultType });
1338
+ });
1339
+ }
1340
+ raiseIntent(intent, context, app) {
1341
+ return __awaiter(this, void 0, void 0, function* () {
1342
+ nonEmptyStringDecoder.runWithException(intent);
1343
+ contextDecoder.runWithException(context);
1344
+ optionalAppIdentifier.runWithException(app);
1345
+ return this.intentsController.raiseIntent({ commandId: generateCommandId(), intent, context, target: app });
1346
+ });
1347
+ }
1348
+ raiseIntentForContext(context, app) {
1349
+ return __awaiter(this, void 0, void 0, function* () {
1350
+ contextDecoder.runWithException(context);
1351
+ optionalTargetApp.runWithException(app);
1352
+ return this.intentsController.raiseIntentForContext({ commandId: generateCommandId(), context, target: app });
1353
+ });
1354
+ }
1355
+ addIntentListener(intent, handler) {
1356
+ return __awaiter(this, void 0, void 0, function* () {
1357
+ nonEmptyStringDecoder.runWithException(intent);
1358
+ if (typeof handler !== "function") {
1359
+ throw new Error("Please provide the handler as a function!");
1360
+ }
1361
+ return this.intentsController.addIntentListener({ commandId: generateCommandId(), intent, handler });
1362
+ });
1363
+ }
1364
+ getOrCreateChannel(channelId) {
1365
+ return __awaiter(this, void 0, void 0, function* () {
1366
+ nonEmptyStringDecoder.runWithException(channelId);
1367
+ return this.channelsController.getOrCreateChannel({ commandId: generateCommandId(), channelId });
1368
+ });
1369
+ }
1370
+ getSystemChannels() {
1371
+ return __awaiter(this, void 0, void 0, function* () {
1372
+ return this.channelsController.getUserChannels(generateCommandId());
1373
+ });
1374
+ }
1375
+ joinChannel(channelId) {
1376
+ return __awaiter(this, void 0, void 0, function* () {
1377
+ nonEmptyStringDecoder.runWithException(channelId);
1378
+ return this.channelsController.joinUserChannel({ commandId: generateCommandId(), channelId });
1379
+ });
1380
+ }
1381
+ joinUserChannel(channelId) {
1382
+ return __awaiter(this, void 0, void 0, function* () {
1383
+ nonEmptyStringDecoder.runWithException(channelId);
1384
+ return this.channelsController.joinUserChannel({ commandId: generateCommandId(), channelId });
1385
+ });
1386
+ }
1387
+ getCurrentChannel() {
1388
+ return __awaiter(this, void 0, void 0, function* () {
1389
+ return this.channelsController.getCurrentChannel(generateCommandId());
1390
+ });
1391
+ }
1392
+ leaveCurrentChannel() {
1393
+ return __awaiter(this, void 0, void 0, function* () {
1394
+ return this.channelsController.leaveCurrentChannel(generateCommandId());
1395
+ });
1396
+ }
1397
+ createPrivateChannel() {
1398
+ return __awaiter(this, void 0, void 0, function* () {
1399
+ return this.channelsController.createPrivateChannel(generateCommandId());
1400
+ });
1401
+ }
1402
+ }
1403
+
1404
+ class AppChannel {
1405
+ constructor(channelsController, id) {
1406
+ this.channelsController = channelsController;
1407
+ this.id = id;
1408
+ this.type = ChannelTypes.App;
1409
+ }
1410
+ toApi() {
1411
+ const api = {
1412
+ id: this.id,
1413
+ type: this.type,
1414
+ broadcast: this.broadcast.bind(this),
1415
+ getCurrentContext: this.getCurrentContext.bind(this),
1416
+ addContextListener: this.addContextListener.bind(this),
1417
+ };
1418
+ return api;
1419
+ }
1420
+ broadcast(context) {
1421
+ return __awaiter(this, void 0, void 0, function* () {
1422
+ contextDecoder.runWithException(context);
1423
+ return this.channelsController.broadcast(generateCommandId(), context, this.id);
1424
+ });
1425
+ }
1426
+ getCurrentContext(contextType) {
1427
+ return __awaiter(this, void 0, void 0, function* () {
1428
+ optionalNonEmptyStringDecoder.runWithException(contextType);
1429
+ return this.channelsController.getContextForChannel({ commandId: generateCommandId(), channelId: this.id, contextType });
1430
+ });
1431
+ }
1432
+ addContextListener(contextType, handler) {
1433
+ return __awaiter(this, arguments, void 0, function* () {
1434
+ if (arguments.length === 1) {
1435
+ if (typeof contextType !== "function") {
1436
+ throw new Error("Please provide the handler as a function!");
1437
+ }
1438
+ return this.channelsController.addContextListener({ commandId: generateCommandId(), handler: contextType, channelId: this.id });
1439
+ }
1440
+ const contextTypeDecoder = optionalNonEmptyStringDecoder.runWithException(contextType);
1441
+ if (typeof handler !== "function") {
1442
+ throw new Error("Please provide the handler as a function!");
1443
+ }
1444
+ return this.channelsController.addContextListener({ commandId: generateCommandId(), handler, contextType: contextTypeDecoder, channelId: this.id });
1445
+ });
1446
+ }
1447
+ }
1448
+
1449
+ class ChannelsParser {
1450
+ constructor() {
1451
+ this.fdc3Delimiter = "&";
1452
+ this.channelsFdc3DataPrefix = "fdc3_";
1453
+ }
1454
+ mapChannelNameToContextName(channelName) {
1455
+ return `${glueChannelNamePrefix}${channelName}`;
1456
+ }
1457
+ parseContextsDataToInitialFDC3Data(context) {
1458
+ const { data, latest_fdc3_type } = context;
1459
+ const parsedType = this.mapChannelsDelimiterToFDC3Type(latest_fdc3_type);
1460
+ return Object.assign({ type: parsedType }, data[`${this.channelsFdc3DataPrefix}${latest_fdc3_type}`]);
1461
+ }
1462
+ revertGlueParsedTypeToInitialFDC3Type(string) {
1463
+ const withoutPrefix = string.replace(this.channelsFdc3DataPrefix, "");
1464
+ return this.mapChannelsDelimiterToFDC3Type(withoutPrefix);
1465
+ }
1466
+ parseFDC3ContextToGlueContexts(context) {
1467
+ const { type } = context, rest = __rest$1(context, ["type"]);
1468
+ const parsedType = this.mapFDC3TypeToChannelsDelimiter(type);
1469
+ return { [`${this.channelsFdc3DataPrefix}${parsedType}`]: rest };
1470
+ }
1471
+ mapFDC3TypeToChannelsDelimiter(type) {
1472
+ return type.split(".").join(this.fdc3Delimiter);
1473
+ }
1474
+ isFdc3DataKey(key) {
1475
+ return !!key.startsWith(this.channelsFdc3DataPrefix);
1476
+ }
1477
+ mapChannelsDelimiterToFDC3Type(type) {
1478
+ return type.split(this.fdc3Delimiter).join(".");
1479
+ }
1480
+ }
1481
+
1482
+ /**
1483
+ * SPDX-License-Identifier: Apache-2.0
1484
+ * Copyright FINOS FDC3 contributors - see NOTICE file
1485
+ */
1486
+
1487
+ /** Constants representing the errors that can be encountered when calling the `open` method on the DesktopAgent object (`fdc3`). */
1488
+ var OpenError;
1489
+
1490
+ (function (OpenError) {
1491
+ /** Returned if the specified application is not found.*/
1492
+ OpenError["AppNotFound"] = "AppNotFound";
1493
+ /** Returned if the specified application fails to launch correctly.*/
1494
+
1495
+ OpenError["ErrorOnLaunch"] = "ErrorOnLaunch";
1496
+ /** Returned if the specified application launches but fails to add a context listener in order to receive the context passed to the `fdc3.open` call.*/
1497
+
1498
+ OpenError["AppTimeout"] = "AppTimeout";
1499
+ /** Returned if the FDC3 desktop agent implementation is not currently able to handle the request.*/
1500
+
1501
+ OpenError["ResolverUnavailable"] = "ResolverUnavailable";
1502
+ })(OpenError || (OpenError = {}));
1503
+ /** Constants representing the errors that can be encountered when calling the `findIntent`, `findIntentsByContext`, `raiseIntent` or `raiseIntentForContext` methods on the DesktopAgent (`fdc3`). */
1504
+
1505
+
1506
+ var ResolveError;
1507
+
1508
+ (function (ResolveError) {
1509
+ /** SHOULD be returned if no apps are available that can resolve the intent and context combination.*/
1510
+ ResolveError["NoAppsFound"] = "NoAppsFound";
1511
+ /** Returned if the FDC3 desktop agent implementation is not currently able to handle the request.*/
1512
+
1513
+ ResolveError["ResolverUnavailable"] = "ResolverUnavailable";
1514
+ /** Returned if the user cancelled the resolution request, for example by closing or cancelling a resolver UI.*/
1515
+
1516
+ ResolveError["UserCancelled"] = "UserCancelledResolution";
1517
+ /** SHOULD be returned if a timeout cancels an intent resolution that required user interaction. Please use `ResolverUnavailable` instead for situations where a resolver UI or similar fails.*/
1518
+
1519
+ ResolveError["ResolverTimeout"] = "ResolverTimeout";
1520
+ /** Returned if a specified target application is not available or a new instance of it cannot be opened. */
1521
+
1522
+ ResolveError["TargetAppUnavailable"] = "TargetAppUnavailable";
1523
+ /** Returned if a specified target application instance is not available, for example because it has been closed. */
1524
+
1525
+ ResolveError["TargetInstanceUnavailable"] = "TargetInstanceUnavailable";
1526
+ /** Returned if the intent and context could not be delivered to the selected application or instance, for example because it has not added an intent handler within a timeout.*/
1527
+
1528
+ ResolveError["IntentDeliveryFailed"] = "IntentDeliveryFailed";
1529
+ })(ResolveError || (ResolveError = {}));
1530
+
1531
+ var ResultError;
1532
+
1533
+ (function (ResultError) {
1534
+ /** Returned if the intent handler exited without returning a Promise or that Promise was not resolved with a Context or Channel object. */
1535
+ ResultError["NoResultReturned"] = "NoResultReturned";
1536
+ /** Returned if the Intent handler function processing the raised intent throws an error or rejects the Promise it returned. */
1537
+
1538
+ ResultError["IntentHandlerRejected"] = "IntentHandlerRejected";
1539
+ })(ResultError || (ResultError = {}));
1540
+
1541
+ var ChannelError;
1542
+
1543
+ (function (ChannelError) {
1544
+ /** Returned if the specified channel is not found when attempting to join a channel via the `joinUserChannel` function of the DesktopAgent (`fdc3`).*/
1545
+ ChannelError["NoChannelFound"] = "NoChannelFound";
1546
+ /** SHOULD be returned when a request to join a user channel or to a retrieve a Channel object via the `joinUserChannel` or `getOrCreateChannel` methods of the DesktopAgent (`fdc3`) object is denied. */
1547
+
1548
+ ChannelError["AccessDenied"] = "AccessDenied";
1549
+ /** SHOULD be returned when a channel cannot be created or retrieved via the `getOrCreateChannel` method of the DesktopAgent (`fdc3`).*/
1550
+
1551
+ ChannelError["CreationFailed"] = "CreationFailed";
1552
+ })(ChannelError || (ChannelError = {}));
1553
+
1554
+ var ContextTypes;
1555
+
1556
+ (function (ContextTypes) {
1557
+ ContextTypes["Chart"] = "fdc3.chart";
1558
+ ContextTypes["ChatInitSettings"] = "fdc3.chat.initSettings";
1559
+ ContextTypes["Contact"] = "fdc3.contact";
1560
+ ContextTypes["ContactList"] = "fdc3.contactList";
1561
+ ContextTypes["Country"] = "fdc3.country";
1562
+ ContextTypes["Currency"] = "fdc3.currency";
1563
+ ContextTypes["Email"] = "fdc3.email";
1564
+ ContextTypes["Instrument"] = "fdc3.instrument";
1565
+ ContextTypes["InstrumentList"] = "fdc3.instrumentList";
1566
+ ContextTypes["Organization"] = "fdc3.organization";
1567
+ ContextTypes["Portfolio"] = "fdc3.portfolio";
1568
+ ContextTypes["Position"] = "fdc3.position";
1569
+ ContextTypes["Nothing"] = "fdc3.nothing";
1570
+ ContextTypes["TimeRange"] = "fdc3.timerange";
1571
+ ContextTypes["Valuation"] = "fdc3.valuation";
1572
+ })(ContextTypes || (ContextTypes = {}));
1573
+
1574
+ // To parse this data:
1575
+ //
1576
+ // import { Convert, Context, Chart, ChatInitSettings, Contact, ContactList, Country, Currency, Email, Instrument, InstrumentList, Nothing, Organization, Portfolio, Position, TimeRange, Valuation } from "./file";
1577
+ //
1578
+ // const context = Convert.toContext(json);
1579
+ // const chart = Convert.toChart(json);
1580
+ // const chatInitSettings = Convert.toChatInitSettings(json);
1581
+ // const contact = Convert.toContact(json);
1582
+ // const contactList = Convert.toContactList(json);
1583
+ // const country = Convert.toCountry(json);
1584
+ // const currency = Convert.toCurrency(json);
1585
+ // const email = Convert.toEmail(json);
1586
+ // const instrument = Convert.toInstrument(json);
1587
+ // const instrumentList = Convert.toInstrumentList(json);
1588
+ // const nothing = Convert.toNothing(json);
1589
+ // const organization = Convert.toOrganization(json);
1590
+ // const portfolio = Convert.toPortfolio(json);
1591
+ // const position = Convert.toPosition(json);
1592
+ // const timeRange = Convert.toTimeRange(json);
1593
+ // const valuation = Convert.toValuation(json);
1594
+ //
1595
+ // These functions will throw an error if the JSON doesn't
1596
+ // match the expected interface, even if the JSON is valid.
1597
+ var Style;
1598
+
1599
+ (function (Style) {
1600
+ Style["Bar"] = "bar";
1601
+ Style["Candle"] = "candle";
1602
+ Style["Custom"] = "custom";
1603
+ Style["Heatmap"] = "heatmap";
1604
+ Style["Histogram"] = "histogram";
1605
+ Style["Line"] = "line";
1606
+ Style["Mountain"] = "mountain";
1607
+ Style["Pie"] = "pie";
1608
+ Style["Scatter"] = "scatter";
1609
+ Style["StackedBar"] = "stacked-bar";
1610
+ })(Style || (Style = {})); // Converts JSON strings to/from your types
1611
+
1612
+ var Intents;
1613
+
1614
+ (function (Intents) {
1615
+ Intents["StartCall"] = "StartCall";
1616
+ Intents["StartChat"] = "StartChat";
1617
+ Intents["StartEmail"] = "StartEmail";
1618
+ Intents["ViewAnalysis"] = "ViewAnalysis";
1619
+ Intents["ViewChart"] = "ViewChart";
1620
+ Intents["ViewContact"] = "ViewContact";
1621
+ Intents["ViewHoldings"] = "ViewHoldings";
1622
+ Intents["ViewInstrument"] = "ViewInstrument";
1623
+ Intents["ViewInteractions"] = "ViewInteractions";
1624
+ Intents["ViewNews"] = "ViewNews";
1625
+ Intents["ViewOrders"] = "ViewOrders";
1626
+ Intents["ViewProfile"] = "ViewProfile";
1627
+ Intents["ViewQuote"] = "ViewQuote";
1628
+ Intents["ViewResearch"] = "ViewResearch";
1629
+ })(Intents || (Intents = {}));
1630
+
1631
+ class UserChannel {
1632
+ constructor(channelsController, glueChannel) {
1633
+ this.channelsController = channelsController;
1634
+ this.type = ChannelTypes.User;
1635
+ this.id = glueChannel.meta.fdc3
1636
+ ? glueChannel.meta.fdc3.id
1637
+ : glueChannel.name;
1638
+ this.displayMetadata = {
1639
+ name: glueChannel.name,
1640
+ color: glueChannel.meta.color
1641
+ };
1642
+ }
1643
+ toApi() {
1644
+ const api = {
1645
+ id: this.id,
1646
+ type: this.type,
1647
+ displayMetadata: this.displayMetadata,
1648
+ broadcast: this.broadcast.bind(this),
1649
+ getCurrentContext: this.getCurrentContext.bind(this),
1650
+ addContextListener: this.addContextListener.bind(this),
1651
+ };
1652
+ return api;
1653
+ }
1654
+ broadcast(context) {
1655
+ return __awaiter(this, void 0, void 0, function* () {
1656
+ contextDecoder.runWithException(context);
1657
+ return this.channelsController.broadcast(generateCommandId(), context, this.id);
1658
+ });
1659
+ }
1660
+ getCurrentContext(contextType) {
1661
+ return __awaiter(this, void 0, void 0, function* () {
1662
+ nonEmptyStringDecoder.run(contextType);
1663
+ return this.channelsController.getContextForChannel({ commandId: generateCommandId(), channelId: this.id, contextType });
1664
+ });
1665
+ }
1666
+ addContextListener(contextType, handler) {
1667
+ return __awaiter(this, arguments, void 0, function* () {
1668
+ if (arguments.length === 1) {
1669
+ if (typeof contextType !== "function") {
1670
+ throw { message: ChannelError.AccessDenied, reason: `Expected function as an argument, got ${typeof contextType}` };
1671
+ }
1672
+ return this.channelsController.addContextListener({ commandId: generateCommandId(), handler: contextType, channelId: this.id });
1673
+ }
1674
+ const contextTypeDecoder = optionalNonEmptyStringDecoder.runWithException(contextType);
1675
+ if (typeof handler !== "function") {
1676
+ throw { message: ChannelError.AccessDenied, reason: `Expected function as an argument, got ${typeof handler}` };
1677
+ }
1678
+ return this.channelsController.addContextListener({ commandId: generateCommandId(), handler, contextType: contextTypeDecoder, channelId: this.id });
1679
+ });
1680
+ }
1681
+ }
1682
+
1683
+ const isChannel = (data) => {
1684
+ return defaultChannelsProps.every(prop => Object.keys(data).includes(prop));
1685
+ };
1686
+ const isContext = (data) => {
1687
+ return defaultContextProps.every(prop => Object.keys(data).includes(prop));
1688
+ };
1689
+ const isChannelMetadata = (data) => {
1690
+ return typeof data === "object" && data.isChannel;
1691
+ };
1692
+ const extractChannelMetadata = (channel) => {
1693
+ return {
1694
+ id: channel.id,
1695
+ type: channel.type,
1696
+ displayMetadata: channel.displayMetadata,
1697
+ isChannel: true
1698
+ };
1699
+ };
1700
+ const parseContextHandler = (handler, contextType) => {
1701
+ const subHandler = (data, metadata) => {
1702
+ if (contextType) {
1703
+ if (data.type === contextType) {
1704
+ handler(data, metadata);
1705
+ }
1706
+ return;
1707
+ }
1708
+ handler(data, metadata);
1709
+ };
1710
+ return subHandler;
1711
+ };
1712
+
1713
+ class IntentsController {
1714
+ constructor(glueController, channelsController, channelsFactory) {
1715
+ this.glueController = glueController;
1716
+ this.channelsController = channelsController;
1717
+ this.channelsFactory = channelsFactory;
1718
+ }
1719
+ get logger() {
1720
+ if (!this._logger) {
1721
+ this._logger = this.glueController.initSubLogger("fdc3.intents.controller");
1722
+ }
1723
+ return this._logger;
1724
+ }
1725
+ findIntent({ commandId, intent, context, resultType }) {
1726
+ return __awaiter(this, void 0, void 0, function* () {
1727
+ yield this.glueController.gluePromise;
1728
+ this.logger.info(`[${commandId}] - findIntent() invoked for intent ${intent} with contextType ${context === null || context === void 0 ? void 0 : context.type} and resultType ${resultType}`);
1729
+ const glueIntents = yield this.glueController.findIntents({ name: intent });
1730
+ if (!glueIntents.length) {
1731
+ throw { message: ResolveError.NoAppsFound, reason: `There are no apps handling the passed intent ${intent}` };
1732
+ }
1733
+ const searchedGlueIntent = glueIntents.find((glueIntent) => glueIntent.name === intent);
1734
+ if (!searchedGlueIntent) {
1735
+ throw { message: ResolveError.NoAppsFound, reason: `There are no apps handling the passed intent ${intent}` };
1736
+ }
1737
+ if (!context && !resultType) {
1738
+ return this.convertGlue42IntentToFDC3Intent(searchedGlueIntent);
1739
+ }
1740
+ const contextType = (context && context.type === fdc3NothingContextType) ? undefined : context === null || context === void 0 ? void 0 : context.type;
1741
+ const filteredIntent = this.getGlueIntentWithFilteredHandlers(searchedGlueIntent, { contextType, resultType });
1742
+ if (!filteredIntent.handlers.length) {
1743
+ throw { message: ResolveError.NoAppsFound, reason: `No apps handling intent ${intent} with contextType ${context === null || context === void 0 ? void 0 : context.type} and resultType ${resultType}` };
1744
+ }
1745
+ return this.convertGlue42IntentToFDC3Intent(filteredIntent);
1746
+ });
1747
+ }
1748
+ findIntentsByContext({ commandId, context, resultType }) {
1749
+ return __awaiter(this, void 0, void 0, function* () {
1750
+ yield this.glueController.gluePromise;
1751
+ this.logger.info(`[${commandId}] - findIntentsByContext() invoked for context type ${context.type} and resultType ${resultType}`);
1752
+ const glueIntents = yield this.glueController.findIntents({ contextType: context.type, resultType });
1753
+ if (!glueIntents.length) {
1754
+ throw { message: ResolveError.NoAppsFound, reason: `No apps registering intent with contextType ${context.type} ${resultType ? `and resultType ${resultType}` : ""}` };
1755
+ }
1756
+ this.logger.info(`[${commandId}] - parsing glue intents to fdc3 intents and returning`);
1757
+ return glueIntents.map((glueIntent) => {
1758
+ const intentWithFilteredHandlers = this.getGlueIntentWithFilteredHandlers(glueIntent, { contextType: context.type, resultType });
1759
+ return this.convertGlue42IntentToFDC3Intent(intentWithFilteredHandlers);
1760
+ });
1761
+ });
1762
+ }
1763
+ raiseIntent({ commandId, intent, context, target }) {
1764
+ var _a;
1765
+ return __awaiter(this, void 0, void 0, function* () {
1766
+ yield this.glueController.gluePromise;
1767
+ this.logger.info(`[${commandId}] - raiseIntent() invoked for intent ${intent} with contextType: ${context.type} and target: ${target}`);
1768
+ const glueContext = { type: context.type, data: Object.assign({}, context) };
1769
+ const searchedGlueIntent = (yield this.glueController.findIntents({ name: intent })).find(glueIntent => glueIntent.name === intent);
1770
+ if (!searchedGlueIntent) {
1771
+ throw { message: ResolveError.NoAppsFound, reason: `There's no app registering an intent '${intent}'` };
1772
+ }
1773
+ const filteredGlueIntent = this.filterGlueIntentHandlers({ commandId, intent: searchedGlueIntent, context, target });
1774
+ if (!target) {
1775
+ this.logger.info(`[${commandId}] - raising intent ${intent} with contextType ${context.type} and handlers ${filteredGlueIntent.handlers.map(h => h.applicationName && h.instanceId)}`);
1776
+ return this.invokeRaiseIntent(commandId, { intent, context: glueContext, handlers: filteredGlueIntent.handlers });
1777
+ }
1778
+ if (typeof target === "string" || !target.instanceId) {
1779
+ this.logger.info(`[${commandId}] - target app ${target.appId} is a valid handler. Raising intent ${intent} with contextType ${context.type} and handlers ${filteredGlueIntent.handlers}`);
1780
+ return this.invokeRaiseIntent(commandId, {
1781
+ intent,
1782
+ context: glueContext,
1783
+ target: { app: target.appId, instance: (_a = filteredGlueIntent.handlers.find((h) => h.instanceId)) === null || _a === void 0 ? void 0 : _a.instanceId }
1784
+ });
1785
+ }
1786
+ this.logger.info(`[${commandId}] - raising intent ${intent} with contextType ${context.type} to target instance of app ${target.appId} and id ${target.instanceId}`);
1787
+ return this.invokeRaiseIntent(commandId, {
1788
+ intent,
1789
+ context: glueContext,
1790
+ target: { instance: target.instanceId }
1791
+ });
1792
+ });
1793
+ }
1794
+ raiseIntentForContext({ commandId, context, target }) {
1795
+ return __awaiter(this, void 0, void 0, function* () {
1796
+ yield this.glueController.gluePromise;
1797
+ this.logger.info(`[${commandId}] - raiseIntentForContext() invoked with contextType ${context.type} and target ${target}`);
1798
+ const appIntents = yield this.findIntentsByContext({ commandId, context });
1799
+ if (!appIntents || appIntents.length === 0) {
1800
+ throw {
1801
+ message: ResolveError.NoAppsFound,
1802
+ reason: `No apps registering intent with contextType ${context.type} ${target ? `and target ${JSON.stringify(target)}` : ""}`
1803
+ };
1804
+ }
1805
+ return this.raiseIntent({ commandId, intent: appIntents[0].intent.name, context, target });
1806
+ });
1807
+ }
1808
+ addIntentListener({ commandId, intent, handler }) {
1809
+ return __awaiter(this, void 0, void 0, function* () {
1810
+ yield this.glueController.gluePromise;
1811
+ this.logger.info(`[${commandId}] - addIntentListener() invoked for intent ${intent}`);
1812
+ const wrappedHandler = this.getWrappedIntentHandler(handler);
1813
+ return this.glueController.addIntentListener(intent, wrappedHandler);
1814
+ });
1815
+ }
1816
+ filterGlueIntentHandlers({ commandId, intent, context, target }) {
1817
+ let filteredGlueIntent;
1818
+ filteredGlueIntent = this.filterIntentHandlersByContext(intent, context);
1819
+ if (!target) {
1820
+ this.logger.info(`[${commandId}] - There's no passed target, intent handlers are filtered only by context type`);
1821
+ return filteredGlueIntent;
1822
+ }
1823
+ this.logger.log(`[${commandId}] - filtering handlers by target (${JSON.stringify(target)}) for intent ${intent.name}`);
1824
+ filteredGlueIntent = this.filterIntentHandlersByTarget({ intent, target, commandId });
1825
+ return filteredGlueIntent;
1826
+ }
1827
+ filterIntentHandlersByTarget({ intent, target, commandId }) {
1828
+ const appName = typeof target === "string" ? target : target.appId;
1829
+ const instanceId = typeof target === "string" ? undefined : target.instanceId;
1830
+ this.logger.info(`[${commandId}] - Checking if application with name ${appName} exists`);
1831
+ const app = this.glueController.getApplication(appName);
1832
+ const serverInstances = this.serverInstanceAsIntentHandler(intent.name);
1833
+ if (!app && (typeof target === "string" || !serverInstances.length)) {
1834
+ throw { message: ResolveError.TargetAppUnavailable, reason: `There's no app with appId ${appName}` };
1835
+ }
1836
+ this.logger.info(`[${commandId}] - target app ${appName} found. Filtering handlers by applicationName: ${appName}`);
1837
+ const validHandlersByApplicationName = intent.handlers.filter((handler) => handler.applicationName === appName);
1838
+ if (!validHandlersByApplicationName.length) {
1839
+ throw { message: ResolveError.NoAppsFound, reason: `Intent ${intent.name} exists but there's no app with appId ${appName} registering it` };
1840
+ }
1841
+ if (!instanceId) {
1842
+ this.logger.log(`[${commandId}] - returning all handlers for intent ${intent.name} and target: ${JSON.stringify(target)}`);
1843
+ return { name: intent.name, handlers: validHandlersByApplicationName };
1844
+ }
1845
+ const isValidInstanceOfTheApp = app
1846
+ ? app.instances.find((inst) => inst.id === instanceId)
1847
+ : serverInstances.find((inst) => inst.instance === instanceId);
1848
+ if (!isValidInstanceOfTheApp) {
1849
+ throw { message: ResolveError.TargetInstanceUnavailable, reason: `There's no instance with id ${instanceId} of the passed app ${appName}` };
1850
+ }
1851
+ this.logger.info(`[${commandId}] - Filtering handlers by instanceId: ${instanceId}`);
1852
+ const validHandlersByInstanceId = validHandlersByApplicationName.filter((handler) => handler.instanceId === instanceId);
1853
+ if (!validHandlersByInstanceId.length) {
1854
+ throw { message: ResolveError.IntentDeliveryFailed, reason: `There's no instance with id ${instanceId} of app ${appName} registering intent ${intent.name}` };
1855
+ }
1856
+ return { name: intent.name, handlers: validHandlersByInstanceId };
1857
+ }
1858
+ serverInstanceAsIntentHandler(intentName) {
1859
+ const interopMethodName = `${IntentsMethodPrefix}${intentName}`;
1860
+ const servers = this.glueController.getInteropServers({ name: interopMethodName });
1861
+ return servers;
1862
+ }
1863
+ filterIntentHandlersByContext(intent, context) {
1864
+ const filteredGlueIntent = context.type === fdc3NothingContextType
1865
+ ? intent
1866
+ : this.getGlueIntentWithFilteredHandlers(intent, { contextType: context.type });
1867
+ if (!filteredGlueIntent.handlers.length) {
1868
+ throw { message: ResolveError.NoAppsFound, reason: `There's no app registering an intent with the passed context type ${context.type}` };
1869
+ }
1870
+ return filteredGlueIntent;
1871
+ }
1872
+ getResult(commandId, glueIntentResult) {
1873
+ return __awaiter(this, void 0, void 0, function* () {
1874
+ this.logger.info(`[${commandId}] - getResult() of IntentResolution invoked`);
1875
+ const { result } = glueIntentResult;
1876
+ if (!isValidNonEmptyObject(result)) {
1877
+ return;
1878
+ }
1879
+ const isResultChannelMetadata = isChannelMetadata(result);
1880
+ if (!isResultChannelMetadata) {
1881
+ return result;
1882
+ }
1883
+ const { clientId, creatorId } = yield this.glueController.getContext(result.id);
1884
+ this.logger.info(`[${commandId}] - result is a private channel with creatorId ${creatorId} and clientId ${clientId}`);
1885
+ const myInteropInstanceId = this.glueController.getMyInteropInstanceId();
1886
+ if ((creatorId && creatorId !== myInteropInstanceId) && (clientId && clientId !== myInteropInstanceId)) {
1887
+ throw { message: ResultError.NoResultReturned, reason: "There are already two parties on this private channel" };
1888
+ }
1889
+ const channel = this.channelsFactory.buildModel(result);
1890
+ if (myInteropInstanceId && myInteropInstanceId !== creatorId) {
1891
+ this.logger.info(`[${commandId}] - the current user is the second party of the private channel. Adding my id ${myInteropInstanceId} as a clientId`);
1892
+ yield this.channelsController.addClientToPrivateChannel(commandId, channel.id, myInteropInstanceId);
1893
+ }
1894
+ this.logger.info(`[${commandId}] - returning private channel`);
1895
+ return channel;
1896
+ });
1897
+ }
1898
+ convertGlue42IntentToFDC3Intent(glueIntent) {
1899
+ const { name, handlers } = glueIntent;
1900
+ const appIntent = {
1901
+ intent: { name, displayName: handlers[0].displayName || "" },
1902
+ apps: handlers.map((handler) => {
1903
+ const appName = handler.applicationName;
1904
+ const app = this.glueController.getApplication(appName);
1905
+ return {
1906
+ appId: appName,
1907
+ instanceId: handler.instanceId,
1908
+ name: appName,
1909
+ title: handler.applicationTitle || handler.instanceTitle || appName,
1910
+ tooltip: (app === null || app === void 0 ? void 0 : app.userProperties.tooltip) || `${appName} (${handler.type})`,
1911
+ description: handler.applicationDescription,
1912
+ icons: handler.applicationIcon ? [handler.applicationIcon, ...((app === null || app === void 0 ? void 0 : app.userProperties.icons) || [])] : app === null || app === void 0 ? void 0 : app.userProperties.icons,
1913
+ images: app === null || app === void 0 ? void 0 : app.userProperties.images,
1914
+ resultType: handler.resultType
1915
+ };
1916
+ })
1917
+ };
1918
+ return appIntent;
1919
+ }
1920
+ getResultType(data) {
1921
+ if (isChannel(data)) {
1922
+ return IntentHandlerResultTypes.Channel;
1923
+ }
1924
+ if (isContext(data)) {
1925
+ return IntentHandlerResultTypes.Context;
1926
+ }
1927
+ throw new Error("Async handler function should return a promise that resolves to a Context or Channel");
1928
+ }
1929
+ getWrappedIntentHandler(handler) {
1930
+ const wrappedHandler = (glue42Context) => __awaiter(this, void 0, void 0, function* () {
1931
+ const handlerResult = yield handler(Object.assign(Object.assign({}, glue42Context.data), { type: glue42Context.type || "" }));
1932
+ if (!handlerResult) {
1933
+ return;
1934
+ }
1935
+ const handlerResultType = this.getResultType(handlerResult);
1936
+ return handlerResultType === IntentHandlerResultTypes.Channel
1937
+ ? extractChannelMetadata(handlerResult)
1938
+ : handlerResult;
1939
+ });
1940
+ return wrappedHandler;
1941
+ }
1942
+ getGlueIntentWithFilteredHandlers(glueIntent, filter) {
1943
+ const { name, handlers } = glueIntent;
1944
+ const desktopGlobal = window.glue42gd || window.iodesktop;
1945
+ let filteredHandlers = handlers;
1946
+ if (filter.contextType) {
1947
+ filteredHandlers = handlers.filter((handler) => {
1948
+ var _a, _b;
1949
+ if (handler.instanceId) {
1950
+ const appExists = desktopGlobal && handler.applicationName === Glue42EnterpriseNoAppWindow
1951
+ ? false
1952
+ : !!(this.glueController.getApplication(handler.applicationName));
1953
+ return appExists
1954
+ ? (_a = handler.contextTypes) === null || _a === void 0 ? void 0 : _a.includes(filter.contextType)
1955
+ : handler;
1956
+ }
1957
+ return (_b = handler.contextTypes) === null || _b === void 0 ? void 0 : _b.includes(filter.contextType);
1958
+ });
1959
+ }
1960
+ if (filter.resultType) {
1961
+ filteredHandlers = handlers.filter((handler) => { var _a; return (_a = handler.resultType) === null || _a === void 0 ? void 0 : _a.includes(filter.resultType); });
1962
+ }
1963
+ return { name, handlers: filteredHandlers };
1964
+ }
1965
+ invokeRaiseIntent(commandId, request) {
1966
+ return __awaiter(this, void 0, void 0, function* () {
1967
+ try {
1968
+ const glueIntentResult = yield this.glueController.raiseIntent(Object.assign(Object.assign({}, request), { timeout: RaiseTimeoutMs }));
1969
+ return {
1970
+ source: {
1971
+ appId: glueIntentResult.handler.applicationName,
1972
+ instanceId: glueIntentResult.handler.instanceId
1973
+ },
1974
+ intent: request.intent,
1975
+ getResult: (() => this.getResult(commandId, glueIntentResult)).bind(this)
1976
+ };
1977
+ }
1978
+ catch (error) {
1979
+ throw { message: ResolveError.IntentDeliveryFailed, reason: typeof error === "string" ? error : JSON.stringify(error) };
1980
+ }
1981
+ });
1982
+ }
1983
+ }
1984
+
1985
+ var version = "2.0.1";
1986
+
1987
+ class ApplicationsController {
1988
+ constructor(glueController) {
1989
+ this.glueController = glueController;
1990
+ this.defaultContextListenerInvokedPromiseTimeout = 60000;
1991
+ this.contextListenerInvokedPromises = {};
1992
+ }
1993
+ get logger() {
1994
+ if (!this._logger) {
1995
+ this._logger = this.glueController.initSubLogger("fdc3.application.controller");
1996
+ }
1997
+ return this._logger;
1998
+ }
1999
+ open({ commandId, target, context }) {
2000
+ return __awaiter(this, void 0, void 0, function* () {
2001
+ yield this.glueController.gluePromise;
2002
+ this.logger.log(`[${commandId}] - open() invoked with target ${target} ${context ? `and contextType ${context.type}` : ""}`);
2003
+ const name = typeof target === "object" ? target.appId : target;
2004
+ const app = this.glueController.getApplication(name);
2005
+ if (!app) {
2006
+ throw { message: OpenError.AppNotFound, reason: `Cannot find targeted ${name} application` };
2007
+ }
2008
+ if (context) {
2009
+ this.logger.info(`[${commandId}] - opening app ${app} with startup context`);
2010
+ return this.openAppWithContext(app, context);
2011
+ }
2012
+ try {
2013
+ this.logger.info(`[${commandId}] - opening app ${app}`);
2014
+ const glueInst = yield app.start();
2015
+ this.logger.info(`[${commandId}] - instance with id ${glueInst.id} started`);
2016
+ return this.parseGlueInstToAppIdentifier(glueInst);
2017
+ }
2018
+ catch (error) {
2019
+ throw { message: OpenError.ErrorOnLaunch, reason: typeof error === "string" ? error : JSON.stringify(error) };
2020
+ }
2021
+ });
2022
+ }
2023
+ findInstances({ commandId, appIdentifier }) {
2024
+ return __awaiter(this, void 0, void 0, function* () {
2025
+ yield this.glueController.gluePromise;
2026
+ this.logger.info(`[${commandId}] - findInstances() invoked with appIdentifier ${appIdentifier}`);
2027
+ const { appId } = appIdentifier;
2028
+ const app = this.glueController.getApplication(appId);
2029
+ if (!app) {
2030
+ throw { message: ResolveError.NoAppsFound, reason: `App with appId: ${appId} does not exist` };
2031
+ }
2032
+ const glueInstances = this.glueController.getApplicationInstances(appId);
2033
+ const fdc3Instances = glueInstances.map(glueInst => this.parseGlueInstToAppIdentifier(glueInst));
2034
+ this.logger.info(`[${commandId}] - ids of opened instances for appIdentifier ${appIdentifier}: ${JSON.stringify(fdc3Instances.map(inst => inst.instanceId))}`);
2035
+ return fdc3Instances;
2036
+ });
2037
+ }
2038
+ getAppMetadata({ commandId, appIdentifier }) {
2039
+ return __awaiter(this, void 0, void 0, function* () {
2040
+ yield this.glueController.gluePromise;
2041
+ this.logger.info(`[${commandId}] - getAppMetadata() invoked with appIdentifier ${appIdentifier}`);
2042
+ const { appId, instanceId } = appIdentifier;
2043
+ const app = this.glueController.getApplication(appId);
2044
+ if (!app) {
2045
+ throw { message: OpenError.AppNotFound, reason: `Cannot find application with appId: ${appId}` };
2046
+ }
2047
+ if (!instanceId) {
2048
+ this.logger.info(`[${commandId}] - no opened instances found. Parsing app ${app}`);
2049
+ return this.parseGlueAppToAppMetadata(app);
2050
+ }
2051
+ const instance = this.glueController.getAppInstanceById(instanceId);
2052
+ const appMetadata = this.parseGlueAppToAppMetadata(app, instance);
2053
+ this.logger.info(`[${commandId}] - found app metadata: ${appMetadata}`);
2054
+ return appMetadata;
2055
+ });
2056
+ }
2057
+ getInfo({ commandId }) {
2058
+ return __awaiter(this, void 0, void 0, function* () {
2059
+ yield this.glueController.gluePromise;
2060
+ this.logger.info(`${commandId} - getInfo() invoked`);
2061
+ const appMetadata = yield this.getCurrentAppMetadata();
2062
+ return {
2063
+ provider: "Glue42",
2064
+ providerVersion: version,
2065
+ fdc3Version: "2.0.0",
2066
+ optionalFeatures: {
2067
+ OriginatingAppMetadata: true,
2068
+ UserChannelMembershipAPIs: true
2069
+ },
2070
+ appMetadata
2071
+ };
2072
+ });
2073
+ }
2074
+ getCurrentAppMetadata() {
2075
+ const myInstance = this.glueController.interopInstance();
2076
+ return Promise.resolve({
2077
+ appId: myInstance.applicationName,
2078
+ instanceId: myInstance.instance
2079
+ });
2080
+ }
2081
+ parseGlueInstToAppIdentifier(glueInst) {
2082
+ return {
2083
+ appId: glueInst.application.name,
2084
+ instanceId: glueInst.id
2085
+ };
2086
+ }
2087
+ parseGlueAppToAppMetadata(app, instance) {
2088
+ return __awaiter(this, void 0, void 0, function* () {
2089
+ const appMetadata = yield this.getBaseGlueAppToAppMetadata(app);
2090
+ if (!instance) {
2091
+ return appMetadata;
2092
+ }
2093
+ return this.addInstanceMetadataToAppMetadata(appMetadata, instance);
2094
+ });
2095
+ }
2096
+ getBaseGlueAppToAppMetadata(app) {
2097
+ return __awaiter(this, void 0, void 0, function* () {
2098
+ const desktopGlobal = window.glue42gd || window.iodesktop;
2099
+ const appConfiguration = desktopGlobal
2100
+ ? yield app.getConfiguration()
2101
+ : app.userProperties;
2102
+ const icon = desktopGlobal
2103
+ ? (yield app.getConfiguration()).icon
2104
+ : app.icon;
2105
+ return {
2106
+ appId: app.name,
2107
+ name: app.name,
2108
+ version: app.version,
2109
+ description: appConfiguration.description,
2110
+ title: app.title,
2111
+ icons: icon ? [{ src: icon }] : [],
2112
+ tooltip: appConfiguration.tooltip,
2113
+ screenshots: desktopGlobal
2114
+ ? appConfiguration.customProperties.screenshots
2115
+ : appConfiguration.screenshots
2116
+ };
2117
+ });
2118
+ }
2119
+ addInstanceMetadataToAppMetadata(appMetadata, instance) {
2120
+ return Object.assign(Object.assign({}, appMetadata), { instanceId: instance.id, instanceMetadata: instance.agm });
2121
+ }
2122
+ openAppWithContext(app, context) {
2123
+ return __awaiter(this, void 0, void 0, function* () {
2124
+ const methodName = yield this.registerContextListenerInteropMethod();
2125
+ const startContext = this.buildGlueStartContext(context, methodName);
2126
+ const glueInst = yield app.start(startContext);
2127
+ this.createContextListenerResponsePromise(glueInst, methodName);
2128
+ try {
2129
+ yield this.contextListenerInvokedPromises[glueInst.id].promise;
2130
+ yield this.unregisterContextListenerPromise(glueInst.id);
2131
+ return this.parseGlueInstToAppIdentifier(glueInst);
2132
+ }
2133
+ catch (error) {
2134
+ yield this.unregisterContextListenerPromise(glueInst.id);
2135
+ throw { message: OpenError.AppTimeout, reason: typeof error === "string" ? error : JSON.stringify(error) };
2136
+ }
2137
+ });
2138
+ }
2139
+ buildGlueStartContext(fdc3Context, responseMethodName) {
2140
+ return {
2141
+ meta: {
2142
+ responseMethodName,
2143
+ instance: this.glueController.interopInstance().instance
2144
+ },
2145
+ context: fdc3Context
2146
+ };
2147
+ }
2148
+ registerContextListenerInteropMethod() {
2149
+ return __awaiter(this, void 0, void 0, function* () {
2150
+ const methodName = this.buildInteropMethodName();
2151
+ yield this.glueController.registerMethod(methodName, this.contextListenerResponseHandler.bind(this));
2152
+ return methodName;
2153
+ });
2154
+ }
2155
+ buildInteropMethodName() {
2156
+ return `${responseInteropMethodPrefix}.${nanoid()}`;
2157
+ }
2158
+ createContextListenerResponsePromise(instance, methodName) {
2159
+ let resolve = () => { };
2160
+ let reject = () => { };
2161
+ const promise = promisePlus(() => {
2162
+ return new Promise((res, rej) => {
2163
+ resolve = res;
2164
+ reject = rej;
2165
+ });
2166
+ }, this.defaultContextListenerInvokedPromiseTimeout, `Timeout of ${this.defaultContextListenerInvokedPromiseTimeout}ms hit waiting for application with appId: ${instance.application.name} and instanceId: ${instance.id} to register context listener`);
2167
+ this.contextListenerInvokedPromises[instance.id] = { promise, resolve, reject, methodName };
2168
+ }
2169
+ contextListenerResponseHandler(args, callerId) {
2170
+ const result = ContextListenerResponseDecoder.run(args);
2171
+ if (!result.ok) {
2172
+ const contextListenerPromise = this.contextListenerInvokedPromises[callerId.instance];
2173
+ if (!contextListenerPromise) {
2174
+ return;
2175
+ }
2176
+ contextListenerPromise.reject(`Method invoked with invalid argument - ${result.error.message}`);
2177
+ return;
2178
+ }
2179
+ const contextListenerPromise = this.contextListenerInvokedPromises[callerId.instance];
2180
+ if (!contextListenerPromise) {
2181
+ return;
2182
+ }
2183
+ contextListenerPromise.resolve();
2184
+ }
2185
+ unregisterContextListenerPromise(instanceId) {
2186
+ return __awaiter(this, void 0, void 0, function* () {
2187
+ const { methodName } = this.contextListenerInvokedPromises[instanceId];
2188
+ yield this.glueController.unregisterMethod(methodName);
2189
+ delete this.contextListenerInvokedPromises[instanceId];
2190
+ });
2191
+ }
2192
+ }
2193
+
2194
+ class ChannelsController {
2195
+ constructor(glueController, channelsStateStore, channelsParser, channelsFactory, channelsCallbackRegistry, channelsPendingListenersStore) {
2196
+ this.glueController = glueController;
2197
+ this.channelsStateStore = channelsStateStore;
2198
+ this.channelsParser = channelsParser;
2199
+ this.channelsFactory = channelsFactory;
2200
+ this.channelsCallbackRegistry = channelsCallbackRegistry;
2201
+ this.channelsPendingListenersStore = channelsPendingListenersStore;
2202
+ this.invokeContextHandlerWithStartupContext = true;
2203
+ this.initDonePromise = this.initialize();
2204
+ this.initDonePromise.catch(() => { });
2205
+ }
2206
+ get logger() {
2207
+ if (!this._logger) {
2208
+ this._logger = this.glueController.initSubLogger("fdc3.channels.controller");
2209
+ }
2210
+ return this._logger;
2211
+ }
2212
+ addContextListener({ commandId, handler, contextType, channelId }) {
2213
+ var _a;
2214
+ return __awaiter(this, void 0, void 0, function* () {
2215
+ yield this.initDonePromise;
2216
+ this.logger.info(`[${commandId}] - addContextListener() invoked for contextType ${contextType} and channelId ${channelId}`);
2217
+ if (this.invokeContextHandlerWithStartupContext) {
2218
+ this.logger.info(`[${commandId}] - trying to invoke context handler with window context`);
2219
+ this.handleWindowContextOnOpening(commandId, handler, contextType).catch((err) => this.logger.warn(`[${commandId}] - ${err}`));
2220
+ }
2221
+ const channelIdToSubscribeTo = channelId || ((_a = this.channelsStateStore.currentChannel) === null || _a === void 0 ? void 0 : _a.id);
2222
+ return this.addContextListenerByChannelId(commandId, handler, channelIdToSubscribeTo, contextType);
2223
+ });
2224
+ }
2225
+ broadcast(commandId, context, channelId) {
2226
+ return __awaiter(this, void 0, void 0, function* () {
2227
+ yield this.initDonePromise;
2228
+ this.logger.info(`[${commandId}] - broadcast() invoked with contextType ${context.type} and channelId ${channelId}`);
2229
+ const canBroadcast = this.isBroadcastPermitted(commandId, channelId);
2230
+ if (!canBroadcast) {
2231
+ return;
2232
+ }
2233
+ const channelIdToBroadcastTo = channelId || this.channelsStateStore.currentChannel.id;
2234
+ return this.broadcastByChannelId(commandId, channelIdToBroadcastTo, context);
2235
+ });
2236
+ }
2237
+ getUserChannels(commandId) {
2238
+ return __awaiter(this, void 0, void 0, function* () {
2239
+ yield this.initDonePromise;
2240
+ this.logger.info(`[${commandId}] - getUserChannels() invoked`);
2241
+ return Object.values(this.channelsStateStore.userChannels);
2242
+ });
2243
+ }
2244
+ getOrCreateChannel({ commandId, channelId }) {
2245
+ return __awaiter(this, void 0, void 0, function* () {
2246
+ yield this.initDonePromise;
2247
+ this.logger.info(`[${commandId}] - getOrCreateChannel() invoked for channel with id ${channelId}`);
2248
+ const isPrivateChannel = this.isPrivateChannel(channelId);
2249
+ if (isPrivateChannel) {
2250
+ throw { message: ChannelError.AccessDenied, reason: "Cannot retrieve a private channel" };
2251
+ }
2252
+ const isUserChannel = this.isUserChannel(channelId);
2253
+ if (isUserChannel) {
2254
+ throw { message: ChannelError.AccessDenied, reason: "There's an already existing system channel with passed id. Retrieve it using fdc3.getSystemChannels() or create a new app channel with a different id" };
2255
+ }
2256
+ return this.getOrCreateAppChannel(commandId, channelId);
2257
+ });
2258
+ }
2259
+ joinUserChannel({ commandId, channelId }) {
2260
+ return __awaiter(this, void 0, void 0, function* () {
2261
+ yield this.initDonePromise;
2262
+ this.logger.info(`[${commandId}] - joinUserChannel() invoked for channel with id ${channelId}`);
2263
+ const isAppChannel = this.doesAppChannelExist(channelId);
2264
+ if (isAppChannel) {
2265
+ throw { message: ChannelError.AccessDenied, reason: "Cannot join an app channel" };
2266
+ }
2267
+ const channelToJoin = this.channelsStateStore.userChannels[channelId];
2268
+ if (!channelToJoin) {
2269
+ throw { message: ChannelError.NoChannelFound, reason: `Cannot find user channel with id ${channelId}` };
2270
+ }
2271
+ const glueChannelName = this.channelsStateStore.getGlueChannelNameByFdc3ChannelId(channelId);
2272
+ this.channelsStateStore.currentChannel = channelToJoin;
2273
+ this.logger.info(`[${commandId}] - joining fdc3 user channel with id ${channelId} (underlying glue channel: ${glueChannelName})`);
2274
+ yield this.glueController.joinChannel(glueChannelName);
2275
+ });
2276
+ }
2277
+ getCurrentChannel(commandId) {
2278
+ return __awaiter(this, void 0, void 0, function* () {
2279
+ yield this.initDonePromise;
2280
+ this.logger.info(`[${commandId}] - getCurrentChannel() invoked`);
2281
+ return this.channelsStateStore.currentChannel;
2282
+ });
2283
+ }
2284
+ leaveCurrentChannel(commandId) {
2285
+ return __awaiter(this, void 0, void 0, function* () {
2286
+ yield this.initDonePromise;
2287
+ this.logger.info(`[${commandId}] - leaveCurrentChannel() invoked`);
2288
+ if (!this.channelsStateStore.currentChannel) {
2289
+ this.logger.info(`[${commandId}] - no channel to leave`);
2290
+ return;
2291
+ }
2292
+ yield this.glueController.leaveChannel();
2293
+ this.channelsStateStore.currentChannel = null;
2294
+ this.logger.info(`[${commandId}] - current channel is left. unsubscribing from all listeners`);
2295
+ this.channelsPendingListenersStore.unsubscribePendingListeners();
2296
+ });
2297
+ }
2298
+ getContextForChannel({ commandId, channelId, contextType }) {
2299
+ return __awaiter(this, void 0, void 0, function* () {
2300
+ yield this.initDonePromise;
2301
+ this.logger.info(`[${commandId}] - getContextForChannel() invoked for channel with id ${channelId}`);
2302
+ const isUserChannel = this.isUserChannel(channelId);
2303
+ if (!contextType) {
2304
+ this.logger.info(`[${commandId}] - retrieving latest context broadcasted on channel with id ${channelId}`);
2305
+ let context;
2306
+ if (isUserChannel) {
2307
+ const glueChannelName = this.channelsStateStore.getGlueChannelNameByFdc3ChannelId(channelId);
2308
+ const glueChannelWithPrefix = this.channelsParser.mapChannelNameToContextName(glueChannelName);
2309
+ this.logger.info(`[${commandId}] - getting context for user channel with id ${channelId} (underlying glue channel ${glueChannelName})`);
2310
+ context = yield this.glueController.getContext(glueChannelWithPrefix);
2311
+ }
2312
+ else {
2313
+ this.logger.info(`[${commandId}] - getting context for app channel with id ${channelId}`);
2314
+ context = yield this.glueController.getContext(channelId);
2315
+ }
2316
+ return context.latest_fdc3_type
2317
+ ? this.channelsParser.parseContextsDataToInitialFDC3Data(context)
2318
+ : null;
2319
+ }
2320
+ this.logger.info(`[${commandId}] Retrieving latest context of type ${contextType} broadcasted on ${isUserChannel ? "user" : "app"} channel with id ${channelId}`);
2321
+ const parsedType = this.channelsParser.mapFDC3TypeToChannelsDelimiter(contextType);
2322
+ const { data } = isUserChannel
2323
+ ? yield this.glueController.getChannel(this.channelsStateStore.getGlueChannelNameByFdc3ChannelId(channelId))
2324
+ : yield this.glueController.getContext(channelId);
2325
+ return data && data[`fdc3_${parsedType}`]
2326
+ ? this.channelsParser.parseContextsDataToInitialFDC3Data({ data, latest_fdc3_type: parsedType })
2327
+ : null;
2328
+ });
2329
+ }
2330
+ createPrivateChannel(commandId) {
2331
+ return __awaiter(this, void 0, void 0, function* () {
2332
+ yield this.initDonePromise;
2333
+ this.logger.info(`[${commandId}] - createPrivateChannel() invoked`);
2334
+ const creatorId = this.glueController.getMyInteropInstanceId();
2335
+ const channel = this.buildChannel(ChannelTypes.Private);
2336
+ yield this.glueController.updateContext(channel.id, { creatorId });
2337
+ this.logger.info(`[${commandId}] - private channel with id ${channel.id} created`);
2338
+ return channel;
2339
+ });
2340
+ }
2341
+ announceDisconnect(commandId, channelId, instanceId) {
2342
+ return __awaiter(this, void 0, void 0, function* () {
2343
+ yield this.initDonePromise;
2344
+ this.logger.info(`[${commandId}] - disconnect() invoked on channel with id ${channelId}`);
2345
+ yield this.glueController.updateContext(channelId, { disconnected: true });
2346
+ this.logger.info(`[${commandId}] - glue context for ${channelId} updated with disconnected flag`);
2347
+ const closedInstanceId = instanceId || this.glueController.getMyInteropInstanceId();
2348
+ const targetInstance = yield this.getOtherInstanceIdFromClosedOne(channelId, closedInstanceId);
2349
+ const replayContextTypes = yield this.getContextTypesForPrivateChannel(channelId);
2350
+ this.logger.info(`[${commandId}] - invoking onDisconnect callback for instance ${targetInstance}`);
2351
+ this.invokeSystemMethod(targetInstance, PrivateChannelEventMethods.OnDisconnect, { clientId: targetInstance, channelId, replayContextTypes });
2352
+ });
2353
+ }
2354
+ addClientToPrivateChannel(commandId, channelId, clientId) {
2355
+ return __awaiter(this, void 0, void 0, function* () {
2356
+ this.logger.info(`[${commandId}] - client with id ${clientId} added to private channel with id ${channelId}`);
2357
+ yield this.glueController.updateContext(channelId, { clientId });
2358
+ });
2359
+ }
2360
+ isPrivateChannelDisconnected({ commandId, channelId }) {
2361
+ return __awaiter(this, void 0, void 0, function* () {
2362
+ this.logger.info(`[${commandId}] - checking if private channel with id ${channelId} is disconnected`);
2363
+ const context = yield this.glueController.getContext(channelId);
2364
+ return !!context.disconnected;
2365
+ });
2366
+ }
2367
+ registerOnInstanceStopped({ commandId, channelId }) {
2368
+ this.logger.info(`[${commandId}] - registering onInstanceStopped callback for channel with id ${channelId}`);
2369
+ const handler = (instance) => __awaiter(this, void 0, void 0, function* () {
2370
+ const { clientId, creatorId } = yield this.glueController.getContext(channelId);
2371
+ if (instance.id !== clientId && instance.id !== creatorId) {
2372
+ return;
2373
+ }
2374
+ this.logger.info(`[${commandId}] - calling onDisconnect callback for channel with id ${channelId}`);
2375
+ yield this.announceDisconnect(commandId, channelId, instance.id);
2376
+ });
2377
+ return this.glueController.registerOnInstanceStopped(handler.bind(this));
2378
+ }
2379
+ addPrivateChannelEvent({ commandId, action, channelId, handler }) {
2380
+ return __awaiter(this, void 0, void 0, function* () {
2381
+ this.logger.info(`[${commandId}] - registering callback for ${action} event in channel with id ${channelId}`);
2382
+ let replayArgs;
2383
+ const targetInstanceId = yield this.getTargetedInstanceId(channelId);
2384
+ if (action === PrivateChannelEventMethods.OnAddContextListener && targetInstanceId) {
2385
+ replayArgs = yield this.getContextTypesForPrivateChannel(channelId);
2386
+ }
2387
+ return this.channelsCallbackRegistry.add({ action, channelId, handler, replayArgs });
2388
+ });
2389
+ }
2390
+ initialize() {
2391
+ return __awaiter(this, void 0, void 0, function* () {
2392
+ yield this.glueController.gluePromise;
2393
+ const current = this.glueController.getCurrentChannel();
2394
+ const glueChannels = yield this.glueController.listAllChannels();
2395
+ const glueChannelsWithFdc3Meta = glueChannels.filter((glueChannel) => glueChannel.meta.fdc3);
2396
+ glueChannelsWithFdc3Meta.forEach((glueChannel) => {
2397
+ const userChannel = this.buildChannel(ChannelTypes.User, { displayMetadata: { glueChannel } });
2398
+ this.channelsStateStore.addFdc3IdToGlueChannelName(userChannel.id, glueChannel.name);
2399
+ this.channelsStateStore.addUserChannel(userChannel);
2400
+ if (current && glueChannel.name === current) {
2401
+ this.channelsStateStore.currentChannel = userChannel;
2402
+ }
2403
+ });
2404
+ this.glueController.setOnChannelChanged(this.handleOnChannelChanged.bind(this));
2405
+ });
2406
+ }
2407
+ handleOnChannelChanged(channelId) {
2408
+ return __awaiter(this, void 0, void 0, function* () {
2409
+ if (!channelId) {
2410
+ this.channelsPendingListenersStore.unsubscribePendingListeners();
2411
+ return;
2412
+ }
2413
+ const isFdc3ChannelName = fdc3ChannelNames.includes(channelId);
2414
+ const userChannelId = isFdc3ChannelName ? channelId : this.channelsStateStore.getFdc3ChannelIdByGlueChannelName(channelId);
2415
+ const commandId = nanoid();
2416
+ yield this.channelsPendingListenersStore.subscribePendingListeners(commandId, this.addContextListener.bind(this), userChannelId);
2417
+ this.channelsStateStore.currentChannel = this.channelsStateStore.userChannels[userChannelId];
2418
+ });
2419
+ }
2420
+ isBroadcastPermitted(commandId, channelId) {
2421
+ if (channelId) {
2422
+ return true;
2423
+ }
2424
+ if (!this.channelsStateStore.currentChannel) {
2425
+ this.logger.info(`[${commandId}] - invocation of broadcast ignored - no channel to broadcast to`);
2426
+ console.error("You need to join a user channel in order to broadcast");
2427
+ return false;
2428
+ }
2429
+ if (this.channelsStateStore.currentChannel.type === ChannelTypes.App) {
2430
+ this.logger.info(`[${commandId}] - invocation of broadcast ignored - cannot broadcast on app channel directly`);
2431
+ console.error("You can't broadcast to an app channel directly - use channel's broadcast method instead");
2432
+ return false;
2433
+ }
2434
+ return true;
2435
+ }
2436
+ handleWindowContextOnOpening(commandId, handler, contextType) {
2437
+ return __awaiter(this, void 0, void 0, function* () {
2438
+ const myWindow = this.glueController.getMyWindow();
2439
+ if (!myWindow) {
2440
+ this.logger.log(`[${commandId}] - Cannot get window context because this is not a Glue window, it's probably an iframe`);
2441
+ this.invokeContextHandlerWithStartupContext = false;
2442
+ return;
2443
+ }
2444
+ const windowContext = yield myWindow.getContext();
2445
+ if (!isValidNonEmptyObject(windowContext)) {
2446
+ this.logger.info(`[${commandId}] - addContextListener handler won't be invoked - startup context is empty`);
2447
+ this.invokeContextHandlerWithStartupContext = false;
2448
+ return;
2449
+ }
2450
+ const { context, meta } = windowContext;
2451
+ const isSameContextType = contextType ? (context === null || context === void 0 ? void 0 : context.type) === contextType : true;
2452
+ if (!isSameContextType || !meta) {
2453
+ this.logger.info(`[${commandId}] - addContextListener handler won't be invoked`);
2454
+ return;
2455
+ }
2456
+ this.logger.info(`[${commandId}] - invoking addContextListener handler with startup context`);
2457
+ handler(context);
2458
+ this.invokeContextHandlerWithStartupContext = false;
2459
+ const { responseMethodName, instance } = meta;
2460
+ const responseMethodExists = this.doesServerMethodExist(responseMethodName, instance);
2461
+ if (!responseMethodExists) {
2462
+ this.logger.info(`[${commandId}] - response method for instance ${instance} does not exist anymore. returning`);
2463
+ return;
2464
+ }
2465
+ this.logger.info(`[${commandId}] - invoking response method for instance ${instance}`);
2466
+ yield this.glueController.invokeMethod(responseMethodName, instance, { listenerInvoked: true });
2467
+ });
2468
+ }
2469
+ doesServerMethodExist(methodName, instance) {
2470
+ const serversForMethodName = this.glueController.getInteropServers({ name: methodName });
2471
+ return !!serversForMethodName.find(server => server.instance === instance);
2472
+ }
2473
+ getOrCreateAppChannel(commandId, channelId) {
2474
+ return __awaiter(this, void 0, void 0, function* () {
2475
+ const exists = this.doesAppChannelExist(channelId);
2476
+ if (!exists) {
2477
+ this.logger.info(`[${commandId}] - app channel with id ${channelId} does not exist. Creating one`);
2478
+ yield this.glueController.updateContext(channelId, {});
2479
+ }
2480
+ this.logger.info(`[${commandId}] - returning app channel with id ${channelId}`);
2481
+ return this.buildChannel(ChannelTypes.App, { id: channelId });
2482
+ });
2483
+ }
2484
+ doesAppChannelExist(name) {
2485
+ return !name.includes(PrivateChannelPrefix) && this.glueController.getAllContexts().some((ctxName) => ctxName === name);
2486
+ }
2487
+ isUserChannel(channelId) {
2488
+ if (!channelId) {
2489
+ return false;
2490
+ }
2491
+ return !!this.channelsStateStore.userChannels[channelId];
2492
+ }
2493
+ isPrivateChannel(channelId) {
2494
+ return channelId.includes(PrivateChannelPrefix) && this.glueController.getAllContexts().some((ctxName) => ctxName === channelId);
2495
+ }
2496
+ buildChannel(type, data) {
2497
+ return this.channelsFactory.buildModel(Object.assign(Object.assign({ type }, data), { isChannel: true }));
2498
+ }
2499
+ broadcastByChannelId(commandId, channelId, context) {
2500
+ return __awaiter(this, void 0, void 0, function* () {
2501
+ const isUserChannel = this.isUserChannel(channelId);
2502
+ if (!isUserChannel) {
2503
+ this.logger.info(`[${commandId}] - broadcasting on app channel with id ${channelId}`);
2504
+ return this.glueController.updateContextWithLatestFdc3Type(channelId, context);
2505
+ }
2506
+ const glueChannelName = this.channelsStateStore.getGlueChannelNameByFdc3ChannelId(channelId);
2507
+ this.logger.info(`[${commandId}] - broadcasting on fdc3 user channel with id ${channelId} (underlying glue channel: ${glueChannelName})`);
2508
+ return this.glueController.channelsUpdate(glueChannelName, context);
2509
+ });
2510
+ }
2511
+ addContextListenerByChannelId(commandId, handler, channelId, contextType) {
2512
+ return __awaiter(this, void 0, void 0, function* () {
2513
+ const subHandler = parseContextHandler(handler, contextType);
2514
+ if (!channelId) {
2515
+ this.logger.info(`[${commandId}] - no channel to subscribe for. Creating a pending listener`);
2516
+ return this.channelsPendingListenersStore.createPendingListener(subHandler, contextType);
2517
+ }
2518
+ const channelType = this.getChannelTypeById(channelId);
2519
+ if (channelType === ChannelTypes.User) {
2520
+ this.logger.info(`[${commandId}] - subscribing for fdc3 user channel with id ${channelId}`);
2521
+ const unsubscribe = this.glueController.channelsSubscribe(subHandler);
2522
+ return {
2523
+ unsubscribe: () => {
2524
+ this.logger.info(`[${commandId}] - invoking unsubscribe for fdc3 user channel with id ${channelId}`);
2525
+ unsubscribe();
2526
+ }
2527
+ };
2528
+ }
2529
+ if (channelType === ChannelTypes.App) {
2530
+ this.logger.info(`[${commandId}] - subscribing for fdc3 app channel with id ${channelId} (underlying glue context with same name)`);
2531
+ const unsubscribe = yield this.glueController.contextsSubscribe(channelId, subHandler);
2532
+ return {
2533
+ unsubscribe: () => {
2534
+ this.logger.info(`[${commandId}] - invoking unsubscribe for app channel with id ${channelId}`);
2535
+ unsubscribe();
2536
+ }
2537
+ };
2538
+ }
2539
+ if (channelType === ChannelTypes.Private) {
2540
+ this.logger.info(`[${commandId}] - subscribing for fdc3 private channel with id ${channelId} (underlying glue context with same name)`);
2541
+ const contextsUnsubscribe = yield this.glueController.contextsSubscribe(channelId, subHandler);
2542
+ yield this.addContextTypeInPrivateChannelContext(channelId, contextType);
2543
+ const targetInstance = yield this.getTargetedInstanceId(channelId);
2544
+ const unsubscribe = () => {
2545
+ this.logger.info(`[${commandId}] - unsubscribe invoked for private channel with id ${channelId}`);
2546
+ contextsUnsubscribe();
2547
+ this.logger.info(`[${commandId}] - invoking onUnsubscribe handler for private channel with id ${channelId}`);
2548
+ this.invokeSystemMethod(targetInstance, PrivateChannelEventMethods.OnUnsubscribe, { channelId, clientId: targetInstance, contextType });
2549
+ };
2550
+ this.logger.info(`[${commandId}] - invoking onAddContextListener handler for private channel with id ${channelId}`);
2551
+ this.invokeSystemMethod(targetInstance, PrivateChannelEventMethods.OnAddContextListener, { channelId: channelId, clientId: targetInstance, contextType });
2552
+ return { unsubscribe };
2553
+ }
2554
+ throw { message: ChannelError.AccessDenied, reason: "Cannot add a context listener on an invalid channel" };
2555
+ });
2556
+ }
2557
+ getChannelTypeById(channelId) {
2558
+ const isUser = this.isUserChannel(channelId);
2559
+ if (isUser) {
2560
+ return ChannelTypes.User;
2561
+ }
2562
+ const isPrivate = this.isPrivateChannel(channelId);
2563
+ if (isPrivate) {
2564
+ return ChannelTypes.Private;
2565
+ }
2566
+ const isApp = this.doesAppChannelExist(channelId);
2567
+ if (isApp) {
2568
+ return ChannelTypes.App;
2569
+ }
2570
+ throw { message: ChannelError.NoChannelFound, reason: `Channel with id: ${channelId} does not exist` };
2571
+ }
2572
+ getTargetedInstanceId(channelId) {
2573
+ return __awaiter(this, void 0, void 0, function* () {
2574
+ const { clientId, creatorId } = yield this.glueController.getContext(channelId);
2575
+ const myId = this.glueController.getMyInteropInstanceId();
2576
+ return myId === clientId ? creatorId : clientId;
2577
+ });
2578
+ }
2579
+ getOtherInstanceIdFromClosedOne(channelId, closedInstanceId) {
2580
+ return __awaiter(this, void 0, void 0, function* () {
2581
+ const { clientId, creatorId } = yield this.glueController.getContext(channelId);
2582
+ return closedInstanceId === clientId
2583
+ ? creatorId
2584
+ : clientId;
2585
+ });
2586
+ }
2587
+ invokeSystemMethod(clientId, action, payload) {
2588
+ if (clientId) {
2589
+ this.glueController.invokeSystemMethod({ action, payload });
2590
+ }
2591
+ }
2592
+ addContextTypeInPrivateChannelContext(channelId, contextType) {
2593
+ return __awaiter(this, void 0, void 0, function* () {
2594
+ const currentContext = yield this.glueController.getContext(channelId);
2595
+ const updatedTypes = currentContext.contextListenerTypes ? [...currentContext.contextListenerTypes, contextType] : [contextType];
2596
+ return this.glueController.updateContext(channelId, Object.assign(Object.assign({}, currentContext), { contextListenerTypes: updatedTypes }));
2597
+ });
2598
+ }
2599
+ getContextTypesForPrivateChannel(channelId) {
2600
+ return __awaiter(this, void 0, void 0, function* () {
2601
+ const ctx = yield this.glueController.getContext(channelId);
2602
+ return ctx.contextListenerTypes;
2603
+ });
2604
+ }
2605
+ }
2606
+
2607
+ class EventReceiver {
2608
+ constructor(glueController, eventDispatcher, eventsController) {
2609
+ this.glueController = glueController;
2610
+ this.eventDispatcher = eventDispatcher;
2611
+ this.eventsController = eventsController;
2612
+ this.glueResponseReceived = false;
2613
+ this.glueInitialized = false;
2614
+ this.events = {
2615
+ "start": { name: START, handle: this.handleStart.bind(this) },
2616
+ "requestGlueResponse": { name: REQUEST_GLUE_RESPONSE, handle: this.handleRequestGlueResponse.bind(this) }
2617
+ };
2618
+ }
2619
+ start() {
2620
+ this.wireCustomEventListener();
2621
+ this.eventDispatcher.fireNotifyStarted();
2622
+ }
2623
+ wireCustomEventListener() {
2624
+ window.addEventListener(GLUE42_EVENT_NAME, (event) => {
2625
+ const data = event.detail;
2626
+ if (!data || !data.glue42) {
2627
+ return;
2628
+ }
2629
+ const glue42Event = data.glue42.event;
2630
+ const foundHandler = this.events[glue42Event];
2631
+ if (!foundHandler) {
2632
+ return;
2633
+ }
2634
+ foundHandler.handle(data.glue42.message);
2635
+ });
2636
+ }
2637
+ handleStart() {
2638
+ this.eventDispatcher.fireRequestGlue();
2639
+ }
2640
+ handleRequestGlueResponse(data) {
2641
+ return __awaiter(this, void 0, void 0, function* () {
2642
+ if (this.glueResponseReceived && this.glueInitialized) {
2643
+ return;
2644
+ }
2645
+ this.glueResponseReceived = true;
2646
+ const { glue } = data;
2647
+ const glueValidator = this.glueController.validateGlue(glue);
2648
+ if (!glueValidator.isValid) {
2649
+ return this.glueController.initializeFailed(glueValidator.error);
2650
+ }
2651
+ this.glueController.initialize(glue);
2652
+ yield this.eventsController.initialize();
2653
+ this.eventDispatcher.fireFdc3Ready();
2654
+ this.glueInitialized = true;
2655
+ });
2656
+ }
2657
+ }
2658
+
2659
+ class ChannelsStateStore {
2660
+ constructor() {
2661
+ this._currentChannel = null;
2662
+ this._userChannels = {};
2663
+ this._fdc3ChannelIdsToGlueChannelNames = {};
2664
+ }
2665
+ get currentChannel() {
2666
+ return this._currentChannel;
2667
+ }
2668
+ get userChannels() {
2669
+ return this._userChannels;
2670
+ }
2671
+ set currentChannel(newChannelValue) {
2672
+ this._currentChannel = newChannelValue;
2673
+ }
2674
+ addUserChannel(channel) {
2675
+ this._userChannels[channel.id] = channel;
2676
+ }
2677
+ addFdc3IdToGlueChannelName(fdc3Id, glueChannelName) {
2678
+ this._fdc3ChannelIdsToGlueChannelNames[fdc3Id] = glueChannelName;
2679
+ }
2680
+ getGlueChannelNameByFdc3ChannelId(fdc3Id) {
2681
+ return this._fdc3ChannelIdsToGlueChannelNames[fdc3Id];
2682
+ }
2683
+ getFdc3ChannelIdByGlueChannelName(glueChannelName) {
2684
+ const [key] = Object.entries(this._fdc3ChannelIdsToGlueChannelNames).find(([_, value]) => value === glueChannelName);
2685
+ return key;
2686
+ }
2687
+ }
2688
+
2689
+ class PrivateChannel {
2690
+ constructor(channelsController, channelId) {
2691
+ this.channelsController = channelsController;
2692
+ this.type = ChannelTypes.Private;
2693
+ this.id = channelId || `${PrivateChannelPrefix}${nanoid()}`;
2694
+ this.unsubFromInstanceStopped = this.channelsController.registerOnInstanceStopped({ commandId: generateCommandId(), channelId: this.id });
2695
+ }
2696
+ toApi() {
2697
+ const api = {
2698
+ id: this.id,
2699
+ type: this.type,
2700
+ displayMetadata: this.displayMetadata,
2701
+ broadcast: this.broadcast.bind(this),
2702
+ getCurrentContext: this.getCurrentContext.bind(this),
2703
+ addContextListener: this.addContextListener.bind(this),
2704
+ onAddContextListener: this.onAddContextListener.bind(this),
2705
+ onUnsubscribe: this.onUnsubscribe.bind(this),
2706
+ onDisconnect: this.onDisconnect.bind(this),
2707
+ disconnect: this.disconnect.bind(this),
2708
+ };
2709
+ return api;
2710
+ }
2711
+ broadcast(context) {
2712
+ return __awaiter(this, void 0, void 0, function* () {
2713
+ const commandId = generateCommandId();
2714
+ const isDisconnected = yield this.channelsController.isPrivateChannelDisconnected({ commandId, channelId: this.id });
2715
+ if (isDisconnected) {
2716
+ throw { message: ChannelError.AccessDenied, reason: "Channel has disconnected - broadcast is no longer available" };
2717
+ }
2718
+ contextDecoder.runWithException(context);
2719
+ return this.channelsController.broadcast(commandId, context, this.id);
2720
+ });
2721
+ }
2722
+ getCurrentContext(contextType) {
2723
+ return __awaiter(this, void 0, void 0, function* () {
2724
+ optionalNonEmptyStringDecoder.runWithException(contextType);
2725
+ return this.channelsController.getContextForChannel({ commandId: generateCommandId(), channelId: this.id, contextType });
2726
+ });
2727
+ }
2728
+ addContextListener(contextType, handler) {
2729
+ return __awaiter(this, arguments, void 0, function* () {
2730
+ if (arguments.length === 1) {
2731
+ if (typeof contextType !== "function") {
2732
+ throw { message: ChannelError.AccessDenied, reason: `Expected function as an argument, got ${typeof contextType}` };
2733
+ }
2734
+ return this.channelsController.addContextListener({ commandId: generateCommandId(), handler: contextType, channelId: this.id });
2735
+ }
2736
+ const contextTypeDecoder = optionalNonEmptyStringDecoder.runWithException(contextType);
2737
+ if (typeof handler !== "function") {
2738
+ throw { message: ChannelError.AccessDenied, reason: `Expected function as an argument, got ${typeof contextType}` };
2739
+ }
2740
+ return this.channelsController.addContextListener({
2741
+ commandId: generateCommandId(),
2742
+ contextType: contextTypeDecoder,
2743
+ channelId: this.id,
2744
+ handler,
2745
+ });
2746
+ });
2747
+ }
2748
+ onAddContextListener(handler) {
2749
+ if (typeof handler !== "function") {
2750
+ throw { message: ChannelError.AccessDenied, reason: `Expected function as an argument, got ${typeof handler}` };
2751
+ }
2752
+ const unsub = this.channelsController.addPrivateChannelEvent({
2753
+ commandId: generateCommandId(),
2754
+ action: PrivateChannelEventMethods.OnAddContextListener,
2755
+ channelId: this.id,
2756
+ handler
2757
+ });
2758
+ return AsyncListener(unsub);
2759
+ }
2760
+ onUnsubscribe(handler) {
2761
+ if (typeof handler !== "function") {
2762
+ throw { message: ChannelError.AccessDenied, reason: `Expected function as an argument, got ${typeof handler}` };
2763
+ }
2764
+ const unsub = this.channelsController.addPrivateChannelEvent({
2765
+ commandId: generateCommandId(),
2766
+ action: PrivateChannelEventMethods.OnUnsubscribe,
2767
+ channelId: this.id,
2768
+ handler
2769
+ });
2770
+ return AsyncListener(unsub);
2771
+ }
2772
+ onDisconnect(handler) {
2773
+ if (typeof handler !== "function") {
2774
+ throw { message: ChannelError.AccessDenied, reason: `Expected function as an argument, got ${typeof handler}` };
2775
+ }
2776
+ const unsub = this.channelsController.addPrivateChannelEvent({
2777
+ commandId: generateCommandId(),
2778
+ action: PrivateChannelEventMethods.OnDisconnect,
2779
+ channelId: this.id,
2780
+ handler
2781
+ });
2782
+ return AsyncListener(unsub);
2783
+ }
2784
+ disconnect() {
2785
+ return __awaiter(this, void 0, void 0, function* () {
2786
+ yield this.channelsController.announceDisconnect(generateCommandId(), this.id);
2787
+ this.unsubFromInstanceStopped();
2788
+ });
2789
+ }
2790
+ }
2791
+
2792
+ class ChannelsFactory {
2793
+ constructor(createUserChannelFn, createAppChannel, createPrivateChannel) {
2794
+ this.createUserChannelFn = createUserChannelFn;
2795
+ this.createAppChannel = createAppChannel;
2796
+ this.createPrivateChannel = createPrivateChannel;
2797
+ }
2798
+ buildModel(data) {
2799
+ const { type } = data;
2800
+ if (type === ChannelTypes.User) {
2801
+ return this.buildUserChannel(data.displayMetadata.glueChannel);
2802
+ }
2803
+ else if (type === ChannelTypes.App) {
2804
+ return this.buildAppChannel(data.id);
2805
+ }
2806
+ else if (type === ChannelTypes.Private) {
2807
+ return this.buildPrivateChannel(data.id);
2808
+ }
2809
+ else {
2810
+ throw new Error("Pass one of the supported channel types: user, app, private");
2811
+ }
2812
+ }
2813
+ buildUserChannel(data) {
2814
+ return this.createUserChannelFn(data);
2815
+ }
2816
+ buildAppChannel(channelId) {
2817
+ return this.createAppChannel(channelId);
2818
+ }
2819
+ buildPrivateChannel(channelId) {
2820
+ return this.createPrivateChannel(channelId);
2821
+ }
2822
+ }
2823
+
2824
+ function createRegistry(options) {
2825
+ if (options && options.errorHandling
2826
+ && typeof options.errorHandling !== "function"
2827
+ && options.errorHandling !== "log"
2828
+ && options.errorHandling !== "silent"
2829
+ && options.errorHandling !== "throw") {
2830
+ throw new Error("Invalid options passed to createRegistry. Prop errorHandling should be [\"log\" | \"silent\" | \"throw\" | (err) => void], but " + typeof options.errorHandling + " was passed");
2831
+ }
2832
+ var _userErrorHandler = options && typeof options.errorHandling === "function" && options.errorHandling;
2833
+ var callbacks = {};
2834
+ function add(key, callback, replayArgumentsArr) {
2835
+ var callbacksForKey = callbacks[key];
2836
+ if (!callbacksForKey) {
2837
+ callbacksForKey = [];
2838
+ callbacks[key] = callbacksForKey;
2839
+ }
2840
+ callbacksForKey.push(callback);
2841
+ if (replayArgumentsArr) {
2842
+ setTimeout(function () {
2843
+ replayArgumentsArr.forEach(function (replayArgument) {
2844
+ var _a;
2845
+ if ((_a = callbacks[key]) === null || _a === void 0 ? void 0 : _a.includes(callback)) {
2846
+ try {
2847
+ if (Array.isArray(replayArgument)) {
2848
+ callback.apply(undefined, replayArgument);
2849
+ }
2850
+ else {
2851
+ callback.apply(undefined, [replayArgument]);
2852
+ }
2853
+ }
2854
+ catch (err) {
2855
+ _handleError(err, key);
2856
+ }
2857
+ }
2858
+ });
2859
+ }, 0);
2860
+ }
2861
+ return function () {
2862
+ var allForKey = callbacks[key];
2863
+ if (!allForKey) {
2864
+ return;
2865
+ }
2866
+ allForKey = allForKey.reduce(function (acc, element, index) {
2867
+ if (!(element === callback && acc.length === index)) {
2868
+ acc.push(element);
2869
+ }
2870
+ return acc;
2871
+ }, []);
2872
+ if (allForKey.length === 0) {
2873
+ delete callbacks[key];
2874
+ }
2875
+ else {
2876
+ callbacks[key] = allForKey;
2877
+ }
2878
+ };
2879
+ }
2880
+ function execute(key) {
2881
+ var argumentsArr = [];
2882
+ for (var _i = 1; _i < arguments.length; _i++) {
2883
+ argumentsArr[_i - 1] = arguments[_i];
2884
+ }
2885
+ var callbacksForKey = callbacks[key];
2886
+ if (!callbacksForKey || callbacksForKey.length === 0) {
2887
+ return [];
2888
+ }
2889
+ var results = [];
2890
+ callbacksForKey.forEach(function (callback) {
2891
+ try {
2892
+ var result = callback.apply(undefined, argumentsArr);
2893
+ results.push(result);
2894
+ }
2895
+ catch (err) {
2896
+ results.push(undefined);
2897
+ _handleError(err, key);
2898
+ }
2899
+ });
2900
+ return results;
2901
+ }
2902
+ function _handleError(exceptionArtifact, key) {
2903
+ var errParam = exceptionArtifact instanceof Error ? exceptionArtifact : new Error(exceptionArtifact);
2904
+ if (_userErrorHandler) {
2905
+ _userErrorHandler(errParam);
2906
+ return;
2907
+ }
2908
+ var msg = "[ERROR] callback-registry: User callback for key \"" + key + "\" failed: " + errParam.stack;
2909
+ if (options) {
2910
+ switch (options.errorHandling) {
2911
+ case "log":
2912
+ return console.error(msg);
2913
+ case "silent":
2914
+ return;
2915
+ case "throw":
2916
+ throw new Error(msg);
2917
+ }
2918
+ }
2919
+ console.error(msg);
2920
+ }
2921
+ function clear() {
2922
+ callbacks = {};
2923
+ }
2924
+ function clearKey(key) {
2925
+ var callbacksForKey = callbacks[key];
2926
+ if (!callbacksForKey) {
2927
+ return;
2928
+ }
2929
+ delete callbacks[key];
2930
+ }
2931
+ return {
2932
+ add: add,
2933
+ execute: execute,
2934
+ clear: clear,
2935
+ clearKey: clearKey
2936
+ };
2937
+ }
2938
+ createRegistry.default = createRegistry;
2939
+ var lib = createRegistry;
2940
+
2941
+ class ChannelsCallbackRegistry {
2942
+ constructor() {
2943
+ this.registry = lib();
2944
+ }
2945
+ add({ action, channelId, handler, replayArgs }) {
2946
+ return this.registry.add(`${action}-${channelId}`, handler, replayArgs);
2947
+ }
2948
+ invoke(action, argumentObj) {
2949
+ const { channelId, contextType } = argumentObj;
2950
+ this.registry.execute(`${action}-${channelId}`, contextType);
2951
+ }
2952
+ }
2953
+
2954
+ class GlueEventsController {
2955
+ constructor(glueController, channelsCallbackRegistry) {
2956
+ this.glueController = glueController;
2957
+ this.channelsCallbackRegistry = channelsCallbackRegistry;
2958
+ }
2959
+ initialize() {
2960
+ return __awaiter(this, void 0, void 0, function* () {
2961
+ const isMethodRegisteredByThisApp = this.isSysMethodRegisteredByCurrentApp();
2962
+ if (isMethodRegisteredByThisApp) {
2963
+ return;
2964
+ }
2965
+ yield this.glueController.registerMethod(Glue42FDC3SystemMethod, this.handleSystemMethodInvocation.bind(this));
2966
+ });
2967
+ }
2968
+ isSysMethodRegisteredByCurrentApp() {
2969
+ const methods = this.glueController.getInteropMethods(Glue42FDC3SystemMethod);
2970
+ const myId = this.glueController.getMyInteropInstanceId();
2971
+ const methodsByThisInstance = methods.filter(method => {
2972
+ return method.getServers().find(server => server.instance === myId)
2973
+ ? method
2974
+ : undefined;
2975
+ });
2976
+ return !!methodsByThisInstance.length;
2977
+ }
2978
+ handleSystemMethodInvocation(argumentObj) {
2979
+ const argsDecodeResult = SystemMethodInvocationArgumentDecoder.run(argumentObj);
2980
+ if (!argsDecodeResult.ok) {
2981
+ throw new Error(`Interop Method ${Glue42FDC3SystemMethod} invoked with invalid argument object - ${argsDecodeResult.error}.\n Expected ${JSON.stringify({ action: string, payload: { channelId: string, clientId: string } })}`);
2982
+ }
2983
+ const { action, payload } = argsDecodeResult.result;
2984
+ if (action === PrivateChannelEventMethods.OnDisconnect) {
2985
+ return this.handleOnDisconnect(payload);
2986
+ }
2987
+ if (action === PrivateChannelEventMethods.OnAddContextListener || action === PrivateChannelEventMethods.OnUnsubscribe) {
2988
+ return this.channelsCallbackRegistry.invoke(action, payload);
2989
+ }
2990
+ }
2991
+ handleOnDisconnect(payload) {
2992
+ if (payload.replayContextTypes) {
2993
+ this.invokeOnUnsubscribeHandlerMultipleTimes(payload);
2994
+ }
2995
+ this.channelsCallbackRegistry.invoke(PrivateChannelEventMethods.OnDisconnect, payload);
2996
+ }
2997
+ invokeOnUnsubscribeHandlerMultipleTimes(payload) {
2998
+ payload.replayContextTypes.forEach(contextType => {
2999
+ this.channelsCallbackRegistry.invoke(PrivateChannelEventMethods.OnUnsubscribe, { channelId: payload.channelId, clientId: payload.clientId, contextType });
3000
+ });
3001
+ }
3002
+ }
3003
+
3004
+ class ChannelsPendingListenersStore {
3005
+ constructor() {
3006
+ this.pendingListeners = [];
3007
+ }
3008
+ createPendingListener(handler, contextType) {
3009
+ const id = nanoid();
3010
+ const unsubscribe = () => this.filterPendingListenersById(id);
3011
+ const listener = { unsubscribe };
3012
+ const setActualUnsub = (actualUnsub) => {
3013
+ listener.unsubscribe = actualUnsub;
3014
+ };
3015
+ this.pendingListeners.push({ id, handler, contextType, setActualUnsub, listener, unsubWithoutFilter: () => { } });
3016
+ return listener;
3017
+ }
3018
+ subscribePendingListeners(commandId, addContextListenerFn, channelId) {
3019
+ return __awaiter(this, void 0, void 0, function* () {
3020
+ const listeners = yield Promise.all(this.pendingListeners.map(pendingListener => {
3021
+ const { handler, contextType } = pendingListener;
3022
+ return addContextListenerFn({ commandId, handler, contextType, channelId });
3023
+ }));
3024
+ Object.values(this.pendingListeners).forEach(({ id, setActualUnsub, unsubWithoutFilter }, index) => {
3025
+ unsubWithoutFilter = listeners[index].unsubscribe;
3026
+ const un = () => {
3027
+ this.filterPendingListenersById(id);
3028
+ unsubWithoutFilter();
3029
+ };
3030
+ setActualUnsub(un);
3031
+ });
3032
+ });
3033
+ }
3034
+ unsubscribePendingListeners() {
3035
+ this.pendingListeners.forEach(({ id, setActualUnsub, unsubWithoutFilter }) => {
3036
+ unsubWithoutFilter();
3037
+ const newUnsub = () => this.filterPendingListenersById(id);
3038
+ setActualUnsub(newUnsub);
3039
+ });
3040
+ }
3041
+ filterPendingListenersById(id) {
3042
+ this.pendingListeners = this.pendingListeners.filter((listener) => listener.id !== id);
3043
+ }
3044
+ }
3045
+
3046
+ class IoC {
3047
+ get ioc() {
3048
+ return this;
3049
+ }
3050
+ get eventReceiver() {
3051
+ if (!this._eventReceiver) {
3052
+ this._eventReceiver = new EventReceiver(this.glueController, this.eventDispatcher, this.eventsController);
3053
+ }
3054
+ return this._eventReceiver;
3055
+ }
3056
+ get glueController() {
3057
+ if (!this._glueController) {
3058
+ this._glueController = new GlueController(this.channelsParser);
3059
+ }
3060
+ return this._glueController;
3061
+ }
3062
+ get fdc3() {
3063
+ if (!this._fdc3) {
3064
+ this._fdc3 = this.desktopAgent.toApi();
3065
+ }
3066
+ return this._fdc3;
3067
+ }
3068
+ get eventDispatcher() {
3069
+ if (!this._eventDispatcher) {
3070
+ this._eventDispatcher = new EventDispatcher();
3071
+ }
3072
+ return this._eventDispatcher;
3073
+ }
3074
+ get channelsFactory() {
3075
+ if (!this._channelsFactory) {
3076
+ this._channelsFactory = new ChannelsFactory(this.createUserChannel.bind(this), this.createAppChannel.bind(this), this.createPrivateChannel.bind(this));
3077
+ }
3078
+ return this._channelsFactory;
3079
+ }
3080
+ createUserChannel(glueChannel) {
3081
+ return new UserChannel(this.channelsController, glueChannel).toApi();
3082
+ }
3083
+ createAppChannel(id) {
3084
+ return new AppChannel(this.channelsController, id).toApi();
3085
+ }
3086
+ createPrivateChannel(channelId) {
3087
+ return new PrivateChannel(this.channelsController, channelId).toApi();
3088
+ }
3089
+ get desktopAgent() {
3090
+ if (!this._desktopAgent) {
3091
+ this._desktopAgent = new DesktopAgent(this.intentsController, this.applicationController, this.channelsController);
3092
+ }
3093
+ return this._desktopAgent;
3094
+ }
3095
+ get channelsParser() {
3096
+ if (!this._channelsParser) {
3097
+ this._channelsParser = new ChannelsParser();
3098
+ }
3099
+ return this._channelsParser;
3100
+ }
3101
+ get intentsController() {
3102
+ if (!this._intentsController) {
3103
+ this._intentsController = new IntentsController(this.glueController, this.channelsController, this.channelsFactory);
3104
+ }
3105
+ return this._intentsController;
3106
+ }
3107
+ get applicationController() {
3108
+ if (!this._applicationController) {
3109
+ this._applicationController = new ApplicationsController(this.glueController);
3110
+ }
3111
+ return this._applicationController;
3112
+ }
3113
+ get channelsController() {
3114
+ if (!this._channelsController) {
3115
+ this._channelsController = new ChannelsController(this.glueController, this.channelsStateStore, this.channelsParser, this.channelsFactory, this.channelsCallbackRegistry, this.channelsPendingListenersStore);
3116
+ }
3117
+ return this._channelsController;
3118
+ }
3119
+ get channelsStateStore() {
3120
+ if (!this._channelsStateStore) {
3121
+ this._channelsStateStore = new ChannelsStateStore();
3122
+ }
3123
+ return this._channelsStateStore;
3124
+ }
3125
+ get channelsPendingListenersStore() {
3126
+ if (!this._channelsPendingListenersStore) {
3127
+ this._channelsPendingListenersStore = new ChannelsPendingListenersStore();
3128
+ }
3129
+ return this._channelsPendingListenersStore;
3130
+ }
3131
+ get channelsCallbackRegistry() {
3132
+ if (!this._channelsCallbackRegistry) {
3133
+ this._channelsCallbackRegistry = new ChannelsCallbackRegistry();
3134
+ }
3135
+ return this._channelsCallbackRegistry;
3136
+ }
3137
+ get eventsController() {
3138
+ if (!this._eventsController) {
3139
+ this._eventsController = new GlueEventsController(this.glueController, this.channelsCallbackRegistry);
3140
+ }
3141
+ return this._eventsController;
3142
+ }
3143
+ }
3144
+
3145
+ const fdc3Factory = () => {
3146
+ const ioc = new IoC();
3147
+ ioc.glueController.createGluePromise();
3148
+ ioc.eventReceiver.start();
3149
+ return ioc.fdc3;
3150
+ };
3151
+
3152
+ let globalFdc3 = window.fdc3;
3153
+ if (typeof globalFdc3 === "undefined") {
3154
+ globalFdc3 = fdc3Factory();
3155
+ checkIfInElectron(globalFdc3);
3156
+ window.fdc3 = globalFdc3;
3157
+ }
3158
+ else {
3159
+ console.warn("Defaulting to using the auto-injected fdc3.");
3160
+ }
3161
+ var globalFdc3$1 = globalFdc3;
3162
+
3163
+ export { globalFdc3$1 as default };
3164
+ //# sourceMappingURL=fdc3.es.js.map