@interopio/fdc3-web-bridge 1.0.0

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,3656 @@
1
+ (function (factory) {
2
+ typeof define === 'function' && define.amd ? define(factory) :
3
+ factory();
4
+ })((function () { 'use strict';
5
+
6
+ /* @ts-self-types="./index.d.ts" */
7
+ let urlAlphabet =
8
+ 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict';
9
+ let nanoid = (size = 21) => {
10
+ let id = '';
11
+ let i = size | 0;
12
+ while (i--) {
13
+ id += urlAlphabet[(Math.random() * 64) | 0];
14
+ }
15
+ return id
16
+ };
17
+
18
+ /**
19
+ * Wraps values in an `Ok` type.
20
+ *
21
+ * Example: `ok(5) // => {ok: true, result: 5}`
22
+ */
23
+ var ok$1 = function (result) { return ({ ok: true, result: result }); };
24
+ /**
25
+ * Wraps errors in an `Err` type.
26
+ *
27
+ * Example: `err('on fire') // => {ok: false, error: 'on fire'}`
28
+ */
29
+ var err$1 = function (error) { return ({ ok: false, error: error }); };
30
+ /**
31
+ * Create a `Promise` that either resolves with the result of `Ok` or rejects
32
+ * with the error of `Err`.
33
+ */
34
+ var asPromise$1 = function (r) {
35
+ return r.ok === true ? Promise.resolve(r.result) : Promise.reject(r.error);
36
+ };
37
+ /**
38
+ * Unwraps a `Result` and returns either the result of an `Ok`, or
39
+ * `defaultValue`.
40
+ *
41
+ * Example:
42
+ * ```
43
+ * Result.withDefault(5, number().run(json))
44
+ * ```
45
+ *
46
+ * It would be nice if `Decoder` had an instance method that mirrored this
47
+ * function. Such a method would look something like this:
48
+ * ```
49
+ * class Decoder<A> {
50
+ * runWithDefault = (defaultValue: A, json: any): A =>
51
+ * Result.withDefault(defaultValue, this.run(json));
52
+ * }
53
+ *
54
+ * number().runWithDefault(5, json)
55
+ * ```
56
+ * Unfortunately, the type of `defaultValue: A` on the method causes issues
57
+ * with type inference on the `object` decoder in some situations. While these
58
+ * inference issues can be solved by providing the optional type argument for
59
+ * `object`s, the extra trouble and confusion doesn't seem worth it.
60
+ */
61
+ var withDefault$1 = function (defaultValue, r) {
62
+ return r.ok === true ? r.result : defaultValue;
63
+ };
64
+ /**
65
+ * Return the successful result, or throw an error.
66
+ */
67
+ var withException$1 = function (r) {
68
+ if (r.ok === true) {
69
+ return r.result;
70
+ }
71
+ else {
72
+ throw r.error;
73
+ }
74
+ };
75
+ /**
76
+ * Apply `f` to the result of an `Ok`, or pass the error through.
77
+ */
78
+ var map$1 = function (f, r) {
79
+ return r.ok === true ? ok$1(f(r.result)) : r;
80
+ };
81
+ /**
82
+ * Apply `f` to the result of two `Ok`s, or pass an error through. If both
83
+ * `Result`s are errors then the first one is returned.
84
+ */
85
+ var map2$1 = function (f, ar, br) {
86
+ return ar.ok === false ? ar :
87
+ br.ok === false ? br :
88
+ ok$1(f(ar.result, br.result));
89
+ };
90
+ /**
91
+ * Apply `f` to the error of an `Err`, or pass the success through.
92
+ */
93
+ var mapError$1 = function (f, r) {
94
+ return r.ok === true ? r : err$1(f(r.error));
95
+ };
96
+ /**
97
+ * Chain together a sequence of computations that may fail, similar to a
98
+ * `Promise`. If the first computation fails then the error will propagate
99
+ * through. If it succeeds, then `f` will be applied to the value, returning a
100
+ * new `Result`.
101
+ */
102
+ var andThen$1 = function (f, r) {
103
+ return r.ok === true ? f(r.result) : r;
104
+ };
105
+
106
+ /*! *****************************************************************************
107
+ Copyright (c) Microsoft Corporation.
108
+
109
+ Permission to use, copy, modify, and/or distribute this software for any
110
+ purpose with or without fee is hereby granted.
111
+
112
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
113
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
114
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
115
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
116
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
117
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
118
+ PERFORMANCE OF THIS SOFTWARE.
119
+ ***************************************************************************** */
120
+ /* global Reflect, Promise */
121
+
122
+
123
+
124
+ var __assign$1 = function() {
125
+ __assign$1 = Object.assign || function __assign(t) {
126
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
127
+ s = arguments[i];
128
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
129
+ }
130
+ return t;
131
+ };
132
+ return __assign$1.apply(this, arguments);
133
+ };
134
+
135
+ function __rest$1(s, e) {
136
+ var t = {};
137
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
138
+ t[p] = s[p];
139
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
140
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
141
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
142
+ t[p[i]] = s[p[i]];
143
+ }
144
+ return t;
145
+ }
146
+
147
+ function isEqual$1(a, b) {
148
+ if (a === b) {
149
+ return true;
150
+ }
151
+ if (a === null && b === null) {
152
+ return true;
153
+ }
154
+ if (typeof (a) !== typeof (b)) {
155
+ return false;
156
+ }
157
+ if (typeof (a) === 'object') {
158
+ // Array
159
+ if (Array.isArray(a)) {
160
+ if (!Array.isArray(b)) {
161
+ return false;
162
+ }
163
+ if (a.length !== b.length) {
164
+ return false;
165
+ }
166
+ for (var i = 0; i < a.length; i++) {
167
+ if (!isEqual$1(a[i], b[i])) {
168
+ return false;
169
+ }
170
+ }
171
+ return true;
172
+ }
173
+ // Hash table
174
+ var keys = Object.keys(a);
175
+ if (keys.length !== Object.keys(b).length) {
176
+ return false;
177
+ }
178
+ for (var i = 0; i < keys.length; i++) {
179
+ if (!b.hasOwnProperty(keys[i])) {
180
+ return false;
181
+ }
182
+ if (!isEqual$1(a[keys[i]], b[keys[i]])) {
183
+ return false;
184
+ }
185
+ }
186
+ return true;
187
+ }
188
+ }
189
+ /*
190
+ * Helpers
191
+ */
192
+ var isJsonArray$1 = function (json) { return Array.isArray(json); };
193
+ var isJsonObject$1 = function (json) {
194
+ return typeof json === 'object' && json !== null && !isJsonArray$1(json);
195
+ };
196
+ var typeString$1 = function (json) {
197
+ switch (typeof json) {
198
+ case 'string':
199
+ return 'a string';
200
+ case 'number':
201
+ return 'a number';
202
+ case 'boolean':
203
+ return 'a boolean';
204
+ case 'undefined':
205
+ return 'undefined';
206
+ case 'object':
207
+ if (json instanceof Array) {
208
+ return 'an array';
209
+ }
210
+ else if (json === null) {
211
+ return 'null';
212
+ }
213
+ else {
214
+ return 'an object';
215
+ }
216
+ default:
217
+ return JSON.stringify(json);
218
+ }
219
+ };
220
+ var expectedGot$1 = function (expected, got) {
221
+ return "expected " + expected + ", got " + typeString$1(got);
222
+ };
223
+ var printPath$1 = function (paths) {
224
+ return paths.map(function (path) { return (typeof path === 'string' ? "." + path : "[" + path + "]"); }).join('');
225
+ };
226
+ var prependAt$1 = function (newAt, _a) {
227
+ var at = _a.at, rest = __rest$1(_a, ["at"]);
228
+ return (__assign$1({ at: newAt + (at || '') }, rest));
229
+ };
230
+ /**
231
+ * Decoders transform json objects with unknown structure into known and
232
+ * verified forms. You can create objects of type `Decoder<A>` with either the
233
+ * primitive decoder functions, such as `boolean()` and `string()`, or by
234
+ * applying higher-order decoders to the primitives, such as `array(boolean())`
235
+ * or `dict(string())`.
236
+ *
237
+ * Each of the decoder functions are available both as a static method on
238
+ * `Decoder` and as a function alias -- for example the string decoder is
239
+ * defined at `Decoder.string()`, but is also aliased to `string()`. Using the
240
+ * function aliases exported with the library is recommended.
241
+ *
242
+ * `Decoder` exposes a number of 'run' methods, which all decode json in the
243
+ * same way, but communicate success and failure in different ways. The `map`
244
+ * and `andThen` methods modify decoders without having to call a 'run' method.
245
+ *
246
+ * Alternatively, the main decoder `run()` method returns an object of type
247
+ * `Result<A, DecoderError>`. This library provides a number of helper
248
+ * functions for dealing with the `Result` type, so you can do all the same
249
+ * things with a `Result` as with the decoder methods.
250
+ */
251
+ var Decoder$1 = /** @class */ (function () {
252
+ /**
253
+ * The Decoder class constructor is kept private to separate the internal
254
+ * `decode` function from the external `run` function. The distinction
255
+ * between the two functions is that `decode` returns a
256
+ * `Partial<DecoderError>` on failure, which contains an unfinished error
257
+ * report. When `run` is called on a decoder, the relevant series of `decode`
258
+ * calls is made, and then on failure the resulting `Partial<DecoderError>`
259
+ * is turned into a `DecoderError` by filling in the missing information.
260
+ *
261
+ * While hiding the constructor may seem restrictive, leveraging the
262
+ * provided decoder combinators and helper functions such as
263
+ * `andThen` and `map` should be enough to build specialized decoders as
264
+ * needed.
265
+ */
266
+ function Decoder(decode) {
267
+ var _this = this;
268
+ this.decode = decode;
269
+ /**
270
+ * Run the decoder and return a `Result` with either the decoded value or a
271
+ * `DecoderError` containing the json input, the location of the error, and
272
+ * the error message.
273
+ *
274
+ * Examples:
275
+ * ```
276
+ * number().run(12)
277
+ * // => {ok: true, result: 12}
278
+ *
279
+ * string().run(9001)
280
+ * // =>
281
+ * // {
282
+ * // ok: false,
283
+ * // error: {
284
+ * // kind: 'DecoderError',
285
+ * // input: 9001,
286
+ * // at: 'input',
287
+ * // message: 'expected a string, got 9001'
288
+ * // }
289
+ * // }
290
+ * ```
291
+ */
292
+ this.run = function (json) {
293
+ return mapError$1(function (error) { return ({
294
+ kind: 'DecoderError',
295
+ input: json,
296
+ at: 'input' + (error.at || ''),
297
+ message: error.message || ''
298
+ }); }, _this.decode(json));
299
+ };
300
+ /**
301
+ * Run the decoder as a `Promise`.
302
+ */
303
+ this.runPromise = function (json) { return asPromise$1(_this.run(json)); };
304
+ /**
305
+ * Run the decoder and return the value on success, or throw an exception
306
+ * with a formatted error string.
307
+ */
308
+ this.runWithException = function (json) { return withException$1(_this.run(json)); };
309
+ /**
310
+ * Construct a new decoder that applies a transformation to the decoded
311
+ * result. If the decoder succeeds then `f` will be applied to the value. If
312
+ * it fails the error will propagated through.
313
+ *
314
+ * Example:
315
+ * ```
316
+ * number().map(x => x * 5).run(10)
317
+ * // => {ok: true, result: 50}
318
+ * ```
319
+ */
320
+ this.map = function (f) {
321
+ return new Decoder(function (json) { return map$1(f, _this.decode(json)); });
322
+ };
323
+ /**
324
+ * Chain together a sequence of decoders. The first decoder will run, and
325
+ * then the function will determine what decoder to run second. If the result
326
+ * of the first decoder succeeds then `f` will be applied to the decoded
327
+ * value. If it fails the error will propagate through.
328
+ *
329
+ * This is a very powerful method -- it can act as both the `map` and `where`
330
+ * methods, can improve error messages for edge cases, and can be used to
331
+ * make a decoder for custom types.
332
+ *
333
+ * Example of adding an error message:
334
+ * ```
335
+ * const versionDecoder = valueAt(['version'], number());
336
+ * const infoDecoder3 = object({a: boolean()});
337
+ *
338
+ * const decoder = versionDecoder.andThen(version => {
339
+ * switch (version) {
340
+ * case 3:
341
+ * return infoDecoder3;
342
+ * default:
343
+ * return fail(`Unable to decode info, version ${version} is not supported.`);
344
+ * }
345
+ * });
346
+ *
347
+ * decoder.run({version: 3, a: true})
348
+ * // => {ok: true, result: {a: true}}
349
+ *
350
+ * decoder.run({version: 5, x: 'abc'})
351
+ * // =>
352
+ * // {
353
+ * // ok: false,
354
+ * // error: {... message: 'Unable to decode info, version 5 is not supported.'}
355
+ * // }
356
+ * ```
357
+ *
358
+ * Example of decoding a custom type:
359
+ * ```
360
+ * // nominal type for arrays with a length of at least one
361
+ * type NonEmptyArray<T> = T[] & { __nonEmptyArrayBrand__: void };
362
+ *
363
+ * const nonEmptyArrayDecoder = <T>(values: Decoder<T>): Decoder<NonEmptyArray<T>> =>
364
+ * array(values).andThen(arr =>
365
+ * arr.length > 0
366
+ * ? succeed(createNonEmptyArray(arr))
367
+ * : fail(`expected a non-empty array, got an empty array`)
368
+ * );
369
+ * ```
370
+ */
371
+ this.andThen = function (f) {
372
+ return new Decoder(function (json) {
373
+ return andThen$1(function (value) { return f(value).decode(json); }, _this.decode(json));
374
+ });
375
+ };
376
+ /**
377
+ * Add constraints to a decoder _without_ changing the resulting type. The
378
+ * `test` argument is a predicate function which returns true for valid
379
+ * inputs. When `test` fails on an input, the decoder fails with the given
380
+ * `errorMessage`.
381
+ *
382
+ * ```
383
+ * const chars = (length: number): Decoder<string> =>
384
+ * string().where(
385
+ * (s: string) => s.length === length,
386
+ * `expected a string of length ${length}`
387
+ * );
388
+ *
389
+ * chars(5).run('12345')
390
+ * // => {ok: true, result: '12345'}
391
+ *
392
+ * chars(2).run('HELLO')
393
+ * // => {ok: false, error: {... message: 'expected a string of length 2'}}
394
+ *
395
+ * chars(12).run(true)
396
+ * // => {ok: false, error: {... message: 'expected a string, got a boolean'}}
397
+ * ```
398
+ */
399
+ this.where = function (test, errorMessage) {
400
+ return _this.andThen(function (value) { return (test(value) ? Decoder.succeed(value) : Decoder.fail(errorMessage)); });
401
+ };
402
+ }
403
+ /**
404
+ * Decoder primitive that validates strings, and fails on all other input.
405
+ */
406
+ Decoder.string = function () {
407
+ return new Decoder(function (json) {
408
+ return typeof json === 'string'
409
+ ? ok$1(json)
410
+ : err$1({ message: expectedGot$1('a string', json) });
411
+ });
412
+ };
413
+ /**
414
+ * Decoder primitive that validates numbers, and fails on all other input.
415
+ */
416
+ Decoder.number = function () {
417
+ return new Decoder(function (json) {
418
+ return typeof json === 'number'
419
+ ? ok$1(json)
420
+ : err$1({ message: expectedGot$1('a number', json) });
421
+ });
422
+ };
423
+ /**
424
+ * Decoder primitive that validates booleans, and fails on all other input.
425
+ */
426
+ Decoder.boolean = function () {
427
+ return new Decoder(function (json) {
428
+ return typeof json === 'boolean'
429
+ ? ok$1(json)
430
+ : err$1({ message: expectedGot$1('a boolean', json) });
431
+ });
432
+ };
433
+ Decoder.constant = function (value) {
434
+ return new Decoder(function (json) {
435
+ return isEqual$1(json, value)
436
+ ? ok$1(value)
437
+ : err$1({ message: "expected " + JSON.stringify(value) + ", got " + JSON.stringify(json) });
438
+ });
439
+ };
440
+ Decoder.object = function (decoders) {
441
+ return new Decoder(function (json) {
442
+ if (isJsonObject$1(json) && decoders) {
443
+ var obj = {};
444
+ for (var key in decoders) {
445
+ if (decoders.hasOwnProperty(key)) {
446
+ var r = decoders[key].decode(json[key]);
447
+ if (r.ok === true) {
448
+ // tslint:disable-next-line:strict-type-predicates
449
+ if (r.result !== undefined) {
450
+ obj[key] = r.result;
451
+ }
452
+ }
453
+ else if (json[key] === undefined) {
454
+ return err$1({ message: "the key '" + key + "' is required but was not present" });
455
+ }
456
+ else {
457
+ return err$1(prependAt$1("." + key, r.error));
458
+ }
459
+ }
460
+ }
461
+ return ok$1(obj);
462
+ }
463
+ else if (isJsonObject$1(json)) {
464
+ return ok$1(json);
465
+ }
466
+ else {
467
+ return err$1({ message: expectedGot$1('an object', json) });
468
+ }
469
+ });
470
+ };
471
+ Decoder.array = function (decoder) {
472
+ return new Decoder(function (json) {
473
+ if (isJsonArray$1(json) && decoder) {
474
+ var decodeValue_1 = function (v, i) {
475
+ return mapError$1(function (err$$1) { return prependAt$1("[" + i + "]", err$$1); }, decoder.decode(v));
476
+ };
477
+ return json.reduce(function (acc, v, i) {
478
+ return map2$1(function (arr, result) { return arr.concat([result]); }, acc, decodeValue_1(v, i));
479
+ }, ok$1([]));
480
+ }
481
+ else if (isJsonArray$1(json)) {
482
+ return ok$1(json);
483
+ }
484
+ else {
485
+ return err$1({ message: expectedGot$1('an array', json) });
486
+ }
487
+ });
488
+ };
489
+ Decoder.tuple = function (decoders) {
490
+ return new Decoder(function (json) {
491
+ if (isJsonArray$1(json)) {
492
+ if (json.length !== decoders.length) {
493
+ return err$1({
494
+ message: "expected a tuple of length " + decoders.length + ", got one of length " + json.length
495
+ });
496
+ }
497
+ var result = [];
498
+ for (var i = 0; i < decoders.length; i++) {
499
+ var nth = decoders[i].decode(json[i]);
500
+ if (nth.ok) {
501
+ result[i] = nth.result;
502
+ }
503
+ else {
504
+ return err$1(prependAt$1("[" + i + "]", nth.error));
505
+ }
506
+ }
507
+ return ok$1(result);
508
+ }
509
+ else {
510
+ return err$1({ message: expectedGot$1("a tuple of length " + decoders.length, json) });
511
+ }
512
+ });
513
+ };
514
+ Decoder.union = function (ad, bd) {
515
+ var decoders = [];
516
+ for (var _i = 2; _i < arguments.length; _i++) {
517
+ decoders[_i - 2] = arguments[_i];
518
+ }
519
+ return Decoder.oneOf.apply(Decoder, [ad, bd].concat(decoders));
520
+ };
521
+ Decoder.intersection = function (ad, bd) {
522
+ var ds = [];
523
+ for (var _i = 2; _i < arguments.length; _i++) {
524
+ ds[_i - 2] = arguments[_i];
525
+ }
526
+ return new Decoder(function (json) {
527
+ return [ad, bd].concat(ds).reduce(function (acc, decoder) { return map2$1(Object.assign, acc, decoder.decode(json)); }, ok$1({}));
528
+ });
529
+ };
530
+ /**
531
+ * Escape hatch to bypass validation. Always succeeds and types the result as
532
+ * `any`. Useful for defining decoders incrementally, particularly for
533
+ * complex objects.
534
+ *
535
+ * Example:
536
+ * ```
537
+ * interface User {
538
+ * name: string;
539
+ * complexUserData: ComplexType;
540
+ * }
541
+ *
542
+ * const userDecoder: Decoder<User> = object({
543
+ * name: string(),
544
+ * complexUserData: anyJson()
545
+ * });
546
+ * ```
547
+ */
548
+ Decoder.anyJson = function () { return new Decoder(function (json) { return ok$1(json); }); };
549
+ /**
550
+ * Decoder identity function which always succeeds and types the result as
551
+ * `unknown`.
552
+ */
553
+ Decoder.unknownJson = function () {
554
+ return new Decoder(function (json) { return ok$1(json); });
555
+ };
556
+ /**
557
+ * Decoder for json objects where the keys are unknown strings, but the values
558
+ * should all be of the same type.
559
+ *
560
+ * Example:
561
+ * ```
562
+ * dict(number()).run({chocolate: 12, vanilla: 10, mint: 37});
563
+ * // => {ok: true, result: {chocolate: 12, vanilla: 10, mint: 37}}
564
+ * ```
565
+ */
566
+ Decoder.dict = function (decoder) {
567
+ return new Decoder(function (json) {
568
+ if (isJsonObject$1(json)) {
569
+ var obj = {};
570
+ for (var key in json) {
571
+ if (json.hasOwnProperty(key)) {
572
+ var r = decoder.decode(json[key]);
573
+ if (r.ok === true) {
574
+ obj[key] = r.result;
575
+ }
576
+ else {
577
+ return err$1(prependAt$1("." + key, r.error));
578
+ }
579
+ }
580
+ }
581
+ return ok$1(obj);
582
+ }
583
+ else {
584
+ return err$1({ message: expectedGot$1('an object', json) });
585
+ }
586
+ });
587
+ };
588
+ /**
589
+ * Decoder for values that may be `undefined`. This is primarily helpful for
590
+ * decoding interfaces with optional fields.
591
+ *
592
+ * Example:
593
+ * ```
594
+ * interface User {
595
+ * id: number;
596
+ * isOwner?: boolean;
597
+ * }
598
+ *
599
+ * const decoder: Decoder<User> = object({
600
+ * id: number(),
601
+ * isOwner: optional(boolean())
602
+ * });
603
+ * ```
604
+ */
605
+ Decoder.optional = function (decoder) {
606
+ return new Decoder(function (json) { return (json === undefined || json === null ? ok$1(undefined) : decoder.decode(json)); });
607
+ };
608
+ /**
609
+ * Decoder that attempts to run each decoder in `decoders` and either succeeds
610
+ * with the first successful decoder, or fails after all decoders have failed.
611
+ *
612
+ * Note that `oneOf` expects the decoders to all have the same return type,
613
+ * while `union` creates a decoder for the union type of all the input
614
+ * decoders.
615
+ *
616
+ * Examples:
617
+ * ```
618
+ * oneOf(string(), number().map(String))
619
+ * oneOf(constant('start'), constant('stop'), succeed('unknown'))
620
+ * ```
621
+ */
622
+ Decoder.oneOf = function () {
623
+ var decoders = [];
624
+ for (var _i = 0; _i < arguments.length; _i++) {
625
+ decoders[_i] = arguments[_i];
626
+ }
627
+ return new Decoder(function (json) {
628
+ var errors = [];
629
+ for (var i = 0; i < decoders.length; i++) {
630
+ var r = decoders[i].decode(json);
631
+ if (r.ok === true) {
632
+ return r;
633
+ }
634
+ else {
635
+ errors[i] = r.error;
636
+ }
637
+ }
638
+ var errorsList = errors
639
+ .map(function (error) { return "at error" + (error.at || '') + ": " + error.message; })
640
+ .join('", "');
641
+ return err$1({
642
+ message: "expected a value matching one of the decoders, got the errors [\"" + errorsList + "\"]"
643
+ });
644
+ });
645
+ };
646
+ /**
647
+ * Decoder that always succeeds with either the decoded value, or a fallback
648
+ * default value.
649
+ */
650
+ Decoder.withDefault = function (defaultValue, decoder) {
651
+ return new Decoder(function (json) {
652
+ return ok$1(withDefault$1(defaultValue, decoder.decode(json)));
653
+ });
654
+ };
655
+ /**
656
+ * Decoder that pulls a specific field out of a json structure, instead of
657
+ * decoding and returning the full structure. The `paths` array describes the
658
+ * object keys and array indices to traverse, so that values can be pulled out
659
+ * of a nested structure.
660
+ *
661
+ * Example:
662
+ * ```
663
+ * const decoder = valueAt(['a', 'b', 0], string());
664
+ *
665
+ * decoder.run({a: {b: ['surprise!']}})
666
+ * // => {ok: true, result: 'surprise!'}
667
+ *
668
+ * decoder.run({a: {x: 'cats'}})
669
+ * // => {ok: false, error: {... at: 'input.a.b[0]' message: 'path does not exist'}}
670
+ * ```
671
+ *
672
+ * Note that the `decoder` is ran on the value found at the last key in the
673
+ * path, even if the last key is not found. This allows the `optional`
674
+ * decoder to succeed when appropriate.
675
+ * ```
676
+ * const optionalDecoder = valueAt(['a', 'b', 'c'], optional(string()));
677
+ *
678
+ * optionalDecoder.run({a: {b: {c: 'surprise!'}}})
679
+ * // => {ok: true, result: 'surprise!'}
680
+ *
681
+ * optionalDecoder.run({a: {b: 'cats'}})
682
+ * // => {ok: false, error: {... at: 'input.a.b.c' message: 'expected an object, got "cats"'}
683
+ *
684
+ * optionalDecoder.run({a: {b: {z: 1}}})
685
+ * // => {ok: true, result: undefined}
686
+ * ```
687
+ */
688
+ Decoder.valueAt = function (paths, decoder) {
689
+ return new Decoder(function (json) {
690
+ var jsonAtPath = json;
691
+ for (var i = 0; i < paths.length; i++) {
692
+ if (jsonAtPath === undefined) {
693
+ return err$1({
694
+ at: printPath$1(paths.slice(0, i + 1)),
695
+ message: 'path does not exist'
696
+ });
697
+ }
698
+ else if (typeof paths[i] === 'string' && !isJsonObject$1(jsonAtPath)) {
699
+ return err$1({
700
+ at: printPath$1(paths.slice(0, i + 1)),
701
+ message: expectedGot$1('an object', jsonAtPath)
702
+ });
703
+ }
704
+ else if (typeof paths[i] === 'number' && !isJsonArray$1(jsonAtPath)) {
705
+ return err$1({
706
+ at: printPath$1(paths.slice(0, i + 1)),
707
+ message: expectedGot$1('an array', jsonAtPath)
708
+ });
709
+ }
710
+ else {
711
+ jsonAtPath = jsonAtPath[paths[i]];
712
+ }
713
+ }
714
+ return mapError$1(function (error) {
715
+ return jsonAtPath === undefined
716
+ ? { at: printPath$1(paths), message: 'path does not exist' }
717
+ : prependAt$1(printPath$1(paths), error);
718
+ }, decoder.decode(jsonAtPath));
719
+ });
720
+ };
721
+ /**
722
+ * Decoder that ignores the input json and always succeeds with `fixedValue`.
723
+ */
724
+ Decoder.succeed = function (fixedValue) {
725
+ return new Decoder(function (json) { return ok$1(fixedValue); });
726
+ };
727
+ /**
728
+ * Decoder that ignores the input json and always fails with `errorMessage`.
729
+ */
730
+ Decoder.fail = function (errorMessage) {
731
+ return new Decoder(function (json) { return err$1({ message: errorMessage }); });
732
+ };
733
+ /**
734
+ * Decoder that allows for validating recursive data structures. Unlike with
735
+ * functions, decoders assigned to variables can't reference themselves
736
+ * before they are fully defined. We can avoid prematurely referencing the
737
+ * decoder by wrapping it in a function that won't be called until use, at
738
+ * which point the decoder has been defined.
739
+ *
740
+ * Example:
741
+ * ```
742
+ * interface Comment {
743
+ * msg: string;
744
+ * replies: Comment[];
745
+ * }
746
+ *
747
+ * const decoder: Decoder<Comment> = object({
748
+ * msg: string(),
749
+ * replies: lazy(() => array(decoder))
750
+ * });
751
+ * ```
752
+ */
753
+ Decoder.lazy = function (mkDecoder) {
754
+ return new Decoder(function (json) { return mkDecoder().decode(json); });
755
+ };
756
+ return Decoder;
757
+ }());
758
+
759
+ /* tslint:disable:variable-name */
760
+ /** See `Decoder.string` */
761
+ var string$1 = Decoder$1.string;
762
+ /** See `Decoder.number` */
763
+ Decoder$1.number;
764
+ /** See `Decoder.boolean` */
765
+ var boolean$1 = Decoder$1.boolean;
766
+ /** See `Decoder.anyJson` */
767
+ var anyJson$1 = Decoder$1.anyJson;
768
+ /** See `Decoder.unknownJson` */
769
+ Decoder$1.unknownJson;
770
+ /** See `Decoder.constant` */
771
+ var constant$1 = Decoder$1.constant;
772
+ /** See `Decoder.object` */
773
+ var object$1 = Decoder$1.object;
774
+ /** See `Decoder.array` */
775
+ var array$1 = Decoder$1.array;
776
+ /** See `Decoder.tuple` */
777
+ Decoder$1.tuple;
778
+ /** See `Decoder.dict` */
779
+ Decoder$1.dict;
780
+ /** See `Decoder.optional` */
781
+ var optional$1 = Decoder$1.optional;
782
+ /** See `Decoder.oneOf` */
783
+ var oneOf$1 = Decoder$1.oneOf;
784
+ /** See `Decoder.union` */
785
+ Decoder$1.union;
786
+ /** See `Decoder.intersection` */
787
+ Decoder$1.intersection;
788
+ /** See `Decoder.withDefault` */
789
+ Decoder$1.withDefault;
790
+ /** See `Decoder.valueAt` */
791
+ Decoder$1.valueAt;
792
+ /** See `Decoder.succeed` */
793
+ Decoder$1.succeed;
794
+ /** See `Decoder.fail` */
795
+ Decoder$1.fail;
796
+ /** See `Decoder.lazy` */
797
+ Decoder$1.lazy;
798
+
799
+ const connectBrowserAppProps = ["name", "title", "version", "customProperties", "icon", "caption", "type"];
800
+ const fdc3v2AppProps = ["appId", "name", "type", "details", "version", "title", "tooltip", "lang", "description", "categories", "icons", "screenshots", "contactEmail", "moreInfo", "publisher", "customConfig", "hostManifests", "interop", "localizedVersions"];
801
+
802
+ /**
803
+ * Wraps values in an `Ok` type.
804
+ *
805
+ * Example: `ok(5) // => {ok: true, result: 5}`
806
+ */
807
+ var ok = function (result) { return ({ ok: true, result: result }); };
808
+ /**
809
+ * Wraps errors in an `Err` type.
810
+ *
811
+ * Example: `err('on fire') // => {ok: false, error: 'on fire'}`
812
+ */
813
+ var err = function (error) { return ({ ok: false, error: error }); };
814
+ /**
815
+ * Create a `Promise` that either resolves with the result of `Ok` or rejects
816
+ * with the error of `Err`.
817
+ */
818
+ var asPromise = function (r) {
819
+ return r.ok === true ? Promise.resolve(r.result) : Promise.reject(r.error);
820
+ };
821
+ /**
822
+ * Unwraps a `Result` and returns either the result of an `Ok`, or
823
+ * `defaultValue`.
824
+ *
825
+ * Example:
826
+ * ```
827
+ * Result.withDefault(5, number().run(json))
828
+ * ```
829
+ *
830
+ * It would be nice if `Decoder` had an instance method that mirrored this
831
+ * function. Such a method would look something like this:
832
+ * ```
833
+ * class Decoder<A> {
834
+ * runWithDefault = (defaultValue: A, json: any): A =>
835
+ * Result.withDefault(defaultValue, this.run(json));
836
+ * }
837
+ *
838
+ * number().runWithDefault(5, json)
839
+ * ```
840
+ * Unfortunately, the type of `defaultValue: A` on the method causes issues
841
+ * with type inference on the `object` decoder in some situations. While these
842
+ * inference issues can be solved by providing the optional type argument for
843
+ * `object`s, the extra trouble and confusion doesn't seem worth it.
844
+ */
845
+ var withDefault = function (defaultValue, r) {
846
+ return r.ok === true ? r.result : defaultValue;
847
+ };
848
+ /**
849
+ * Return the successful result, or throw an error.
850
+ */
851
+ var withException = function (r) {
852
+ if (r.ok === true) {
853
+ return r.result;
854
+ }
855
+ else {
856
+ throw r.error;
857
+ }
858
+ };
859
+ /**
860
+ * Apply `f` to the result of an `Ok`, or pass the error through.
861
+ */
862
+ var map = function (f, r) {
863
+ return r.ok === true ? ok(f(r.result)) : r;
864
+ };
865
+ /**
866
+ * Apply `f` to the result of two `Ok`s, or pass an error through. If both
867
+ * `Result`s are errors then the first one is returned.
868
+ */
869
+ var map2 = function (f, ar, br) {
870
+ return ar.ok === false ? ar :
871
+ br.ok === false ? br :
872
+ ok(f(ar.result, br.result));
873
+ };
874
+ /**
875
+ * Apply `f` to the error of an `Err`, or pass the success through.
876
+ */
877
+ var mapError = function (f, r) {
878
+ return r.ok === true ? r : err(f(r.error));
879
+ };
880
+ /**
881
+ * Chain together a sequence of computations that may fail, similar to a
882
+ * `Promise`. If the first computation fails then the error will propagate
883
+ * through. If it succeeds, then `f` will be applied to the value, returning a
884
+ * new `Result`.
885
+ */
886
+ var andThen = function (f, r) {
887
+ return r.ok === true ? f(r.result) : r;
888
+ };
889
+
890
+ /*! *****************************************************************************
891
+ Copyright (c) Microsoft Corporation.
892
+
893
+ Permission to use, copy, modify, and/or distribute this software for any
894
+ purpose with or without fee is hereby granted.
895
+
896
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
897
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
898
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
899
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
900
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
901
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
902
+ PERFORMANCE OF THIS SOFTWARE.
903
+ ***************************************************************************** */
904
+ /* global Reflect, Promise */
905
+
906
+
907
+
908
+ var __assign = function() {
909
+ __assign = Object.assign || function __assign(t) {
910
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
911
+ s = arguments[i];
912
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
913
+ }
914
+ return t;
915
+ };
916
+ return __assign.apply(this, arguments);
917
+ };
918
+
919
+ function __rest(s, e) {
920
+ var t = {};
921
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
922
+ t[p] = s[p];
923
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
924
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
925
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
926
+ t[p[i]] = s[p[i]];
927
+ }
928
+ return t;
929
+ }
930
+
931
+ function isEqual(a, b) {
932
+ if (a === b) {
933
+ return true;
934
+ }
935
+ if (a === null && b === null) {
936
+ return true;
937
+ }
938
+ if (typeof (a) !== typeof (b)) {
939
+ return false;
940
+ }
941
+ if (typeof (a) === 'object') {
942
+ // Array
943
+ if (Array.isArray(a)) {
944
+ if (!Array.isArray(b)) {
945
+ return false;
946
+ }
947
+ if (a.length !== b.length) {
948
+ return false;
949
+ }
950
+ for (var i = 0; i < a.length; i++) {
951
+ if (!isEqual(a[i], b[i])) {
952
+ return false;
953
+ }
954
+ }
955
+ return true;
956
+ }
957
+ // Hash table
958
+ var keys = Object.keys(a);
959
+ if (keys.length !== Object.keys(b).length) {
960
+ return false;
961
+ }
962
+ for (var i = 0; i < keys.length; i++) {
963
+ if (!b.hasOwnProperty(keys[i])) {
964
+ return false;
965
+ }
966
+ if (!isEqual(a[keys[i]], b[keys[i]])) {
967
+ return false;
968
+ }
969
+ }
970
+ return true;
971
+ }
972
+ }
973
+ /*
974
+ * Helpers
975
+ */
976
+ var isJsonArray = function (json) { return Array.isArray(json); };
977
+ var isJsonObject = function (json) {
978
+ return typeof json === 'object' && json !== null && !isJsonArray(json);
979
+ };
980
+ var typeString = function (json) {
981
+ switch (typeof json) {
982
+ case 'string':
983
+ return 'a string';
984
+ case 'number':
985
+ return 'a number';
986
+ case 'boolean':
987
+ return 'a boolean';
988
+ case 'undefined':
989
+ return 'undefined';
990
+ case 'object':
991
+ if (json instanceof Array) {
992
+ return 'an array';
993
+ }
994
+ else if (json === null) {
995
+ return 'null';
996
+ }
997
+ else {
998
+ return 'an object';
999
+ }
1000
+ default:
1001
+ return JSON.stringify(json);
1002
+ }
1003
+ };
1004
+ var expectedGot = function (expected, got) {
1005
+ return "expected " + expected + ", got " + typeString(got);
1006
+ };
1007
+ var printPath = function (paths) {
1008
+ return paths.map(function (path) { return (typeof path === 'string' ? "." + path : "[" + path + "]"); }).join('');
1009
+ };
1010
+ var prependAt = function (newAt, _a) {
1011
+ var at = _a.at, rest = __rest(_a, ["at"]);
1012
+ return (__assign({ at: newAt + (at || '') }, rest));
1013
+ };
1014
+ /**
1015
+ * Decoders transform json objects with unknown structure into known and
1016
+ * verified forms. You can create objects of type `Decoder<A>` with either the
1017
+ * primitive decoder functions, such as `boolean()` and `string()`, or by
1018
+ * applying higher-order decoders to the primitives, such as `array(boolean())`
1019
+ * or `dict(string())`.
1020
+ *
1021
+ * Each of the decoder functions are available both as a static method on
1022
+ * `Decoder` and as a function alias -- for example the string decoder is
1023
+ * defined at `Decoder.string()`, but is also aliased to `string()`. Using the
1024
+ * function aliases exported with the library is recommended.
1025
+ *
1026
+ * `Decoder` exposes a number of 'run' methods, which all decode json in the
1027
+ * same way, but communicate success and failure in different ways. The `map`
1028
+ * and `andThen` methods modify decoders without having to call a 'run' method.
1029
+ *
1030
+ * Alternatively, the main decoder `run()` method returns an object of type
1031
+ * `Result<A, DecoderError>`. This library provides a number of helper
1032
+ * functions for dealing with the `Result` type, so you can do all the same
1033
+ * things with a `Result` as with the decoder methods.
1034
+ */
1035
+ var Decoder = /** @class */ (function () {
1036
+ /**
1037
+ * The Decoder class constructor is kept private to separate the internal
1038
+ * `decode` function from the external `run` function. The distinction
1039
+ * between the two functions is that `decode` returns a
1040
+ * `Partial<DecoderError>` on failure, which contains an unfinished error
1041
+ * report. When `run` is called on a decoder, the relevant series of `decode`
1042
+ * calls is made, and then on failure the resulting `Partial<DecoderError>`
1043
+ * is turned into a `DecoderError` by filling in the missing information.
1044
+ *
1045
+ * While hiding the constructor may seem restrictive, leveraging the
1046
+ * provided decoder combinators and helper functions such as
1047
+ * `andThen` and `map` should be enough to build specialized decoders as
1048
+ * needed.
1049
+ */
1050
+ function Decoder(decode) {
1051
+ var _this = this;
1052
+ this.decode = decode;
1053
+ /**
1054
+ * Run the decoder and return a `Result` with either the decoded value or a
1055
+ * `DecoderError` containing the json input, the location of the error, and
1056
+ * the error message.
1057
+ *
1058
+ * Examples:
1059
+ * ```
1060
+ * number().run(12)
1061
+ * // => {ok: true, result: 12}
1062
+ *
1063
+ * string().run(9001)
1064
+ * // =>
1065
+ * // {
1066
+ * // ok: false,
1067
+ * // error: {
1068
+ * // kind: 'DecoderError',
1069
+ * // input: 9001,
1070
+ * // at: 'input',
1071
+ * // message: 'expected a string, got 9001'
1072
+ * // }
1073
+ * // }
1074
+ * ```
1075
+ */
1076
+ this.run = function (json) {
1077
+ return mapError(function (error) { return ({
1078
+ kind: 'DecoderError',
1079
+ input: json,
1080
+ at: 'input' + (error.at || ''),
1081
+ message: error.message || ''
1082
+ }); }, _this.decode(json));
1083
+ };
1084
+ /**
1085
+ * Run the decoder as a `Promise`.
1086
+ */
1087
+ this.runPromise = function (json) { return asPromise(_this.run(json)); };
1088
+ /**
1089
+ * Run the decoder and return the value on success, or throw an exception
1090
+ * with a formatted error string.
1091
+ */
1092
+ this.runWithException = function (json) { return withException(_this.run(json)); };
1093
+ /**
1094
+ * Construct a new decoder that applies a transformation to the decoded
1095
+ * result. If the decoder succeeds then `f` will be applied to the value. If
1096
+ * it fails the error will propagated through.
1097
+ *
1098
+ * Example:
1099
+ * ```
1100
+ * number().map(x => x * 5).run(10)
1101
+ * // => {ok: true, result: 50}
1102
+ * ```
1103
+ */
1104
+ this.map = function (f) {
1105
+ return new Decoder(function (json) { return map(f, _this.decode(json)); });
1106
+ };
1107
+ /**
1108
+ * Chain together a sequence of decoders. The first decoder will run, and
1109
+ * then the function will determine what decoder to run second. If the result
1110
+ * of the first decoder succeeds then `f` will be applied to the decoded
1111
+ * value. If it fails the error will propagate through.
1112
+ *
1113
+ * This is a very powerful method -- it can act as both the `map` and `where`
1114
+ * methods, can improve error messages for edge cases, and can be used to
1115
+ * make a decoder for custom types.
1116
+ *
1117
+ * Example of adding an error message:
1118
+ * ```
1119
+ * const versionDecoder = valueAt(['version'], number());
1120
+ * const infoDecoder3 = object({a: boolean()});
1121
+ *
1122
+ * const decoder = versionDecoder.andThen(version => {
1123
+ * switch (version) {
1124
+ * case 3:
1125
+ * return infoDecoder3;
1126
+ * default:
1127
+ * return fail(`Unable to decode info, version ${version} is not supported.`);
1128
+ * }
1129
+ * });
1130
+ *
1131
+ * decoder.run({version: 3, a: true})
1132
+ * // => {ok: true, result: {a: true}}
1133
+ *
1134
+ * decoder.run({version: 5, x: 'abc'})
1135
+ * // =>
1136
+ * // {
1137
+ * // ok: false,
1138
+ * // error: {... message: 'Unable to decode info, version 5 is not supported.'}
1139
+ * // }
1140
+ * ```
1141
+ *
1142
+ * Example of decoding a custom type:
1143
+ * ```
1144
+ * // nominal type for arrays with a length of at least one
1145
+ * type NonEmptyArray<T> = T[] & { __nonEmptyArrayBrand__: void };
1146
+ *
1147
+ * const nonEmptyArrayDecoder = <T>(values: Decoder<T>): Decoder<NonEmptyArray<T>> =>
1148
+ * array(values).andThen(arr =>
1149
+ * arr.length > 0
1150
+ * ? succeed(createNonEmptyArray(arr))
1151
+ * : fail(`expected a non-empty array, got an empty array`)
1152
+ * );
1153
+ * ```
1154
+ */
1155
+ this.andThen = function (f) {
1156
+ return new Decoder(function (json) {
1157
+ return andThen(function (value) { return f(value).decode(json); }, _this.decode(json));
1158
+ });
1159
+ };
1160
+ /**
1161
+ * Add constraints to a decoder _without_ changing the resulting type. The
1162
+ * `test` argument is a predicate function which returns true for valid
1163
+ * inputs. When `test` fails on an input, the decoder fails with the given
1164
+ * `errorMessage`.
1165
+ *
1166
+ * ```
1167
+ * const chars = (length: number): Decoder<string> =>
1168
+ * string().where(
1169
+ * (s: string) => s.length === length,
1170
+ * `expected a string of length ${length}`
1171
+ * );
1172
+ *
1173
+ * chars(5).run('12345')
1174
+ * // => {ok: true, result: '12345'}
1175
+ *
1176
+ * chars(2).run('HELLO')
1177
+ * // => {ok: false, error: {... message: 'expected a string of length 2'}}
1178
+ *
1179
+ * chars(12).run(true)
1180
+ * // => {ok: false, error: {... message: 'expected a string, got a boolean'}}
1181
+ * ```
1182
+ */
1183
+ this.where = function (test, errorMessage) {
1184
+ return _this.andThen(function (value) { return (test(value) ? Decoder.succeed(value) : Decoder.fail(errorMessage)); });
1185
+ };
1186
+ }
1187
+ /**
1188
+ * Decoder primitive that validates strings, and fails on all other input.
1189
+ */
1190
+ Decoder.string = function () {
1191
+ return new Decoder(function (json) {
1192
+ return typeof json === 'string'
1193
+ ? ok(json)
1194
+ : err({ message: expectedGot('a string', json) });
1195
+ });
1196
+ };
1197
+ /**
1198
+ * Decoder primitive that validates numbers, and fails on all other input.
1199
+ */
1200
+ Decoder.number = function () {
1201
+ return new Decoder(function (json) {
1202
+ return typeof json === 'number'
1203
+ ? ok(json)
1204
+ : err({ message: expectedGot('a number', json) });
1205
+ });
1206
+ };
1207
+ /**
1208
+ * Decoder primitive that validates booleans, and fails on all other input.
1209
+ */
1210
+ Decoder.boolean = function () {
1211
+ return new Decoder(function (json) {
1212
+ return typeof json === 'boolean'
1213
+ ? ok(json)
1214
+ : err({ message: expectedGot('a boolean', json) });
1215
+ });
1216
+ };
1217
+ Decoder.constant = function (value) {
1218
+ return new Decoder(function (json) {
1219
+ return isEqual(json, value)
1220
+ ? ok(value)
1221
+ : err({ message: "expected " + JSON.stringify(value) + ", got " + JSON.stringify(json) });
1222
+ });
1223
+ };
1224
+ Decoder.object = function (decoders) {
1225
+ return new Decoder(function (json) {
1226
+ if (isJsonObject(json) && decoders) {
1227
+ var obj = {};
1228
+ for (var key in decoders) {
1229
+ if (decoders.hasOwnProperty(key)) {
1230
+ var r = decoders[key].decode(json[key]);
1231
+ if (r.ok === true) {
1232
+ // tslint:disable-next-line:strict-type-predicates
1233
+ if (r.result !== undefined) {
1234
+ obj[key] = r.result;
1235
+ }
1236
+ }
1237
+ else if (json[key] === undefined) {
1238
+ return err({ message: "the key '" + key + "' is required but was not present" });
1239
+ }
1240
+ else {
1241
+ return err(prependAt("." + key, r.error));
1242
+ }
1243
+ }
1244
+ }
1245
+ return ok(obj);
1246
+ }
1247
+ else if (isJsonObject(json)) {
1248
+ return ok(json);
1249
+ }
1250
+ else {
1251
+ return err({ message: expectedGot('an object', json) });
1252
+ }
1253
+ });
1254
+ };
1255
+ Decoder.array = function (decoder) {
1256
+ return new Decoder(function (json) {
1257
+ if (isJsonArray(json) && decoder) {
1258
+ var decodeValue_1 = function (v, i) {
1259
+ return mapError(function (err$$1) { return prependAt("[" + i + "]", err$$1); }, decoder.decode(v));
1260
+ };
1261
+ return json.reduce(function (acc, v, i) {
1262
+ return map2(function (arr, result) { return arr.concat([result]); }, acc, decodeValue_1(v, i));
1263
+ }, ok([]));
1264
+ }
1265
+ else if (isJsonArray(json)) {
1266
+ return ok(json);
1267
+ }
1268
+ else {
1269
+ return err({ message: expectedGot('an array', json) });
1270
+ }
1271
+ });
1272
+ };
1273
+ Decoder.tuple = function (decoders) {
1274
+ return new Decoder(function (json) {
1275
+ if (isJsonArray(json)) {
1276
+ if (json.length !== decoders.length) {
1277
+ return err({
1278
+ message: "expected a tuple of length " + decoders.length + ", got one of length " + json.length
1279
+ });
1280
+ }
1281
+ var result = [];
1282
+ for (var i = 0; i < decoders.length; i++) {
1283
+ var nth = decoders[i].decode(json[i]);
1284
+ if (nth.ok) {
1285
+ result[i] = nth.result;
1286
+ }
1287
+ else {
1288
+ return err(prependAt("[" + i + "]", nth.error));
1289
+ }
1290
+ }
1291
+ return ok(result);
1292
+ }
1293
+ else {
1294
+ return err({ message: expectedGot("a tuple of length " + decoders.length, json) });
1295
+ }
1296
+ });
1297
+ };
1298
+ Decoder.union = function (ad, bd) {
1299
+ var decoders = [];
1300
+ for (var _i = 2; _i < arguments.length; _i++) {
1301
+ decoders[_i - 2] = arguments[_i];
1302
+ }
1303
+ return Decoder.oneOf.apply(Decoder, [ad, bd].concat(decoders));
1304
+ };
1305
+ Decoder.intersection = function (ad, bd) {
1306
+ var ds = [];
1307
+ for (var _i = 2; _i < arguments.length; _i++) {
1308
+ ds[_i - 2] = arguments[_i];
1309
+ }
1310
+ return new Decoder(function (json) {
1311
+ return [ad, bd].concat(ds).reduce(function (acc, decoder) { return map2(Object.assign, acc, decoder.decode(json)); }, ok({}));
1312
+ });
1313
+ };
1314
+ /**
1315
+ * Escape hatch to bypass validation. Always succeeds and types the result as
1316
+ * `any`. Useful for defining decoders incrementally, particularly for
1317
+ * complex objects.
1318
+ *
1319
+ * Example:
1320
+ * ```
1321
+ * interface User {
1322
+ * name: string;
1323
+ * complexUserData: ComplexType;
1324
+ * }
1325
+ *
1326
+ * const userDecoder: Decoder<User> = object({
1327
+ * name: string(),
1328
+ * complexUserData: anyJson()
1329
+ * });
1330
+ * ```
1331
+ */
1332
+ Decoder.anyJson = function () { return new Decoder(function (json) { return ok(json); }); };
1333
+ /**
1334
+ * Decoder identity function which always succeeds and types the result as
1335
+ * `unknown`.
1336
+ */
1337
+ Decoder.unknownJson = function () {
1338
+ return new Decoder(function (json) { return ok(json); });
1339
+ };
1340
+ /**
1341
+ * Decoder for json objects where the keys are unknown strings, but the values
1342
+ * should all be of the same type.
1343
+ *
1344
+ * Example:
1345
+ * ```
1346
+ * dict(number()).run({chocolate: 12, vanilla: 10, mint: 37});
1347
+ * // => {ok: true, result: {chocolate: 12, vanilla: 10, mint: 37}}
1348
+ * ```
1349
+ */
1350
+ Decoder.dict = function (decoder) {
1351
+ return new Decoder(function (json) {
1352
+ if (isJsonObject(json)) {
1353
+ var obj = {};
1354
+ for (var key in json) {
1355
+ if (json.hasOwnProperty(key)) {
1356
+ var r = decoder.decode(json[key]);
1357
+ if (r.ok === true) {
1358
+ obj[key] = r.result;
1359
+ }
1360
+ else {
1361
+ return err(prependAt("." + key, r.error));
1362
+ }
1363
+ }
1364
+ }
1365
+ return ok(obj);
1366
+ }
1367
+ else {
1368
+ return err({ message: expectedGot('an object', json) });
1369
+ }
1370
+ });
1371
+ };
1372
+ /**
1373
+ * Decoder for values that may be `undefined`. This is primarily helpful for
1374
+ * decoding interfaces with optional fields.
1375
+ *
1376
+ * Example:
1377
+ * ```
1378
+ * interface User {
1379
+ * id: number;
1380
+ * isOwner?: boolean;
1381
+ * }
1382
+ *
1383
+ * const decoder: Decoder<User> = object({
1384
+ * id: number(),
1385
+ * isOwner: optional(boolean())
1386
+ * });
1387
+ * ```
1388
+ */
1389
+ Decoder.optional = function (decoder) {
1390
+ return new Decoder(function (json) { return (json === undefined || json === null ? ok(undefined) : decoder.decode(json)); });
1391
+ };
1392
+ /**
1393
+ * Decoder that attempts to run each decoder in `decoders` and either succeeds
1394
+ * with the first successful decoder, or fails after all decoders have failed.
1395
+ *
1396
+ * Note that `oneOf` expects the decoders to all have the same return type,
1397
+ * while `union` creates a decoder for the union type of all the input
1398
+ * decoders.
1399
+ *
1400
+ * Examples:
1401
+ * ```
1402
+ * oneOf(string(), number().map(String))
1403
+ * oneOf(constant('start'), constant('stop'), succeed('unknown'))
1404
+ * ```
1405
+ */
1406
+ Decoder.oneOf = function () {
1407
+ var decoders = [];
1408
+ for (var _i = 0; _i < arguments.length; _i++) {
1409
+ decoders[_i] = arguments[_i];
1410
+ }
1411
+ return new Decoder(function (json) {
1412
+ var errors = [];
1413
+ for (var i = 0; i < decoders.length; i++) {
1414
+ var r = decoders[i].decode(json);
1415
+ if (r.ok === true) {
1416
+ return r;
1417
+ }
1418
+ else {
1419
+ errors[i] = r.error;
1420
+ }
1421
+ }
1422
+ var errorsList = errors
1423
+ .map(function (error) { return "at error" + (error.at || '') + ": " + error.message; })
1424
+ .join('", "');
1425
+ return err({
1426
+ message: "expected a value matching one of the decoders, got the errors [\"" + errorsList + "\"]"
1427
+ });
1428
+ });
1429
+ };
1430
+ /**
1431
+ * Decoder that always succeeds with either the decoded value, or a fallback
1432
+ * default value.
1433
+ */
1434
+ Decoder.withDefault = function (defaultValue, decoder) {
1435
+ return new Decoder(function (json) {
1436
+ return ok(withDefault(defaultValue, decoder.decode(json)));
1437
+ });
1438
+ };
1439
+ /**
1440
+ * Decoder that pulls a specific field out of a json structure, instead of
1441
+ * decoding and returning the full structure. The `paths` array describes the
1442
+ * object keys and array indices to traverse, so that values can be pulled out
1443
+ * of a nested structure.
1444
+ *
1445
+ * Example:
1446
+ * ```
1447
+ * const decoder = valueAt(['a', 'b', 0], string());
1448
+ *
1449
+ * decoder.run({a: {b: ['surprise!']}})
1450
+ * // => {ok: true, result: 'surprise!'}
1451
+ *
1452
+ * decoder.run({a: {x: 'cats'}})
1453
+ * // => {ok: false, error: {... at: 'input.a.b[0]' message: 'path does not exist'}}
1454
+ * ```
1455
+ *
1456
+ * Note that the `decoder` is ran on the value found at the last key in the
1457
+ * path, even if the last key is not found. This allows the `optional`
1458
+ * decoder to succeed when appropriate.
1459
+ * ```
1460
+ * const optionalDecoder = valueAt(['a', 'b', 'c'], optional(string()));
1461
+ *
1462
+ * optionalDecoder.run({a: {b: {c: 'surprise!'}}})
1463
+ * // => {ok: true, result: 'surprise!'}
1464
+ *
1465
+ * optionalDecoder.run({a: {b: 'cats'}})
1466
+ * // => {ok: false, error: {... at: 'input.a.b.c' message: 'expected an object, got "cats"'}
1467
+ *
1468
+ * optionalDecoder.run({a: {b: {z: 1}}})
1469
+ * // => {ok: true, result: undefined}
1470
+ * ```
1471
+ */
1472
+ Decoder.valueAt = function (paths, decoder) {
1473
+ return new Decoder(function (json) {
1474
+ var jsonAtPath = json;
1475
+ for (var i = 0; i < paths.length; i++) {
1476
+ if (jsonAtPath === undefined) {
1477
+ return err({
1478
+ at: printPath(paths.slice(0, i + 1)),
1479
+ message: 'path does not exist'
1480
+ });
1481
+ }
1482
+ else if (typeof paths[i] === 'string' && !isJsonObject(jsonAtPath)) {
1483
+ return err({
1484
+ at: printPath(paths.slice(0, i + 1)),
1485
+ message: expectedGot('an object', jsonAtPath)
1486
+ });
1487
+ }
1488
+ else if (typeof paths[i] === 'number' && !isJsonArray(jsonAtPath)) {
1489
+ return err({
1490
+ at: printPath(paths.slice(0, i + 1)),
1491
+ message: expectedGot('an array', jsonAtPath)
1492
+ });
1493
+ }
1494
+ else {
1495
+ jsonAtPath = jsonAtPath[paths[i]];
1496
+ }
1497
+ }
1498
+ return mapError(function (error) {
1499
+ return jsonAtPath === undefined
1500
+ ? { at: printPath(paths), message: 'path does not exist' }
1501
+ : prependAt(printPath(paths), error);
1502
+ }, decoder.decode(jsonAtPath));
1503
+ });
1504
+ };
1505
+ /**
1506
+ * Decoder that ignores the input json and always succeeds with `fixedValue`.
1507
+ */
1508
+ Decoder.succeed = function (fixedValue) {
1509
+ return new Decoder(function (json) { return ok(fixedValue); });
1510
+ };
1511
+ /**
1512
+ * Decoder that ignores the input json and always fails with `errorMessage`.
1513
+ */
1514
+ Decoder.fail = function (errorMessage) {
1515
+ return new Decoder(function (json) { return err({ message: errorMessage }); });
1516
+ };
1517
+ /**
1518
+ * Decoder that allows for validating recursive data structures. Unlike with
1519
+ * functions, decoders assigned to variables can't reference themselves
1520
+ * before they are fully defined. We can avoid prematurely referencing the
1521
+ * decoder by wrapping it in a function that won't be called until use, at
1522
+ * which point the decoder has been defined.
1523
+ *
1524
+ * Example:
1525
+ * ```
1526
+ * interface Comment {
1527
+ * msg: string;
1528
+ * replies: Comment[];
1529
+ * }
1530
+ *
1531
+ * const decoder: Decoder<Comment> = object({
1532
+ * msg: string(),
1533
+ * replies: lazy(() => array(decoder))
1534
+ * });
1535
+ * ```
1536
+ */
1537
+ Decoder.lazy = function (mkDecoder) {
1538
+ return new Decoder(function (json) { return mkDecoder().decode(json); });
1539
+ };
1540
+ return Decoder;
1541
+ }());
1542
+
1543
+ /* tslint:disable:variable-name */
1544
+ /** See `Decoder.string` */
1545
+ var string = Decoder.string;
1546
+ /** See `Decoder.number` */
1547
+ var number = Decoder.number;
1548
+ /** See `Decoder.boolean` */
1549
+ var boolean = Decoder.boolean;
1550
+ /** See `Decoder.anyJson` */
1551
+ var anyJson = Decoder.anyJson;
1552
+ /** See `Decoder.unknownJson` */
1553
+ Decoder.unknownJson;
1554
+ /** See `Decoder.constant` */
1555
+ var constant = Decoder.constant;
1556
+ /** See `Decoder.object` */
1557
+ var object = Decoder.object;
1558
+ /** See `Decoder.array` */
1559
+ var array = Decoder.array;
1560
+ /** See `Decoder.tuple` */
1561
+ Decoder.tuple;
1562
+ /** See `Decoder.dict` */
1563
+ var dict = Decoder.dict;
1564
+ /** See `Decoder.optional` */
1565
+ var optional = Decoder.optional;
1566
+ /** See `Decoder.oneOf` */
1567
+ var oneOf = Decoder.oneOf;
1568
+ /** See `Decoder.union` */
1569
+ Decoder.union;
1570
+ /** See `Decoder.intersection` */
1571
+ Decoder.intersection;
1572
+ /** See `Decoder.withDefault` */
1573
+ Decoder.withDefault;
1574
+ /** See `Decoder.valueAt` */
1575
+ Decoder.valueAt;
1576
+ /** See `Decoder.succeed` */
1577
+ Decoder.succeed;
1578
+ /** See `Decoder.fail` */
1579
+ Decoder.fail;
1580
+ /** See `Decoder.lazy` */
1581
+ Decoder.lazy;
1582
+
1583
+ const nonEmptyStringDecoder$4 = string().where((s) => s.length > 0, "Expected a non-empty string");
1584
+ const nonNegativeNumberDecoder = number().where((num) => num >= 0, "Expected a non-negative number");
1585
+
1586
+ const intentDefinitionDecoder = object({
1587
+ name: nonEmptyStringDecoder$4,
1588
+ displayName: optional(string()),
1589
+ contexts: optional(array(string())),
1590
+ customConfig: optional(object())
1591
+ });
1592
+ const v2TypeDecoder = oneOf(constant("web"), constant("native"), constant("citrix"), constant("onlineNative"), constant("other"));
1593
+ const v2DetailsDecoder = object({
1594
+ url: nonEmptyStringDecoder$4
1595
+ });
1596
+ const v2IconDecoder = object({
1597
+ src: nonEmptyStringDecoder$4,
1598
+ size: optional(nonEmptyStringDecoder$4),
1599
+ type: optional(nonEmptyStringDecoder$4)
1600
+ });
1601
+ const v2ScreenshotDecoder = object({
1602
+ src: nonEmptyStringDecoder$4,
1603
+ size: optional(nonEmptyStringDecoder$4),
1604
+ type: optional(nonEmptyStringDecoder$4),
1605
+ label: optional(nonEmptyStringDecoder$4)
1606
+ });
1607
+ const v2ListensForIntentDecoder = object({
1608
+ contexts: array(nonEmptyStringDecoder$4),
1609
+ displayName: optional(nonEmptyStringDecoder$4),
1610
+ resultType: optional(nonEmptyStringDecoder$4),
1611
+ customConfig: optional(anyJson())
1612
+ });
1613
+ const v2IntentsDecoder = object({
1614
+ listensFor: optional(dict(v2ListensForIntentDecoder)),
1615
+ raises: optional(dict(array(nonEmptyStringDecoder$4)))
1616
+ });
1617
+ const v2UserChannelDecoder = object({
1618
+ broadcasts: optional(array(nonEmptyStringDecoder$4)),
1619
+ listensFor: optional(array(nonEmptyStringDecoder$4))
1620
+ });
1621
+ const v2AppChannelDecoder = object({
1622
+ name: nonEmptyStringDecoder$4,
1623
+ description: optional(nonEmptyStringDecoder$4),
1624
+ broadcasts: optional(array(nonEmptyStringDecoder$4)),
1625
+ listensFor: optional(array(nonEmptyStringDecoder$4))
1626
+ });
1627
+ const v2InteropDecoder = object({
1628
+ intents: optional(v2IntentsDecoder),
1629
+ userChannels: optional(v2UserChannelDecoder),
1630
+ appChannels: optional(array(v2AppChannelDecoder))
1631
+ });
1632
+ const glue42ApplicationDetailsDecoder = object({
1633
+ url: optional(nonEmptyStringDecoder$4),
1634
+ top: optional(number()),
1635
+ left: optional(number()),
1636
+ width: optional(nonNegativeNumberDecoder),
1637
+ height: optional(nonNegativeNumberDecoder)
1638
+ });
1639
+ const glue42HostManifestsBrowserDecoder = object({
1640
+ name: optional(nonEmptyStringDecoder$4),
1641
+ type: optional(nonEmptyStringDecoder$4.where((s) => s === "window", "Expected a value of window")),
1642
+ title: optional(nonEmptyStringDecoder$4),
1643
+ version: optional(nonEmptyStringDecoder$4),
1644
+ customProperties: optional(anyJson()),
1645
+ icon: optional(string()),
1646
+ caption: optional(string()),
1647
+ details: optional(glue42ApplicationDetailsDecoder),
1648
+ intents: optional(array(intentDefinitionDecoder)),
1649
+ hidden: optional(boolean())
1650
+ });
1651
+ const v1DefinitionDecoder = object({
1652
+ name: nonEmptyStringDecoder$4,
1653
+ appId: nonEmptyStringDecoder$4,
1654
+ title: optional(nonEmptyStringDecoder$4),
1655
+ version: optional(nonEmptyStringDecoder$4),
1656
+ manifest: nonEmptyStringDecoder$4,
1657
+ manifestType: nonEmptyStringDecoder$4,
1658
+ tooltip: optional(nonEmptyStringDecoder$4),
1659
+ description: optional(nonEmptyStringDecoder$4),
1660
+ contactEmail: optional(nonEmptyStringDecoder$4),
1661
+ supportEmail: optional(nonEmptyStringDecoder$4),
1662
+ publisher: optional(nonEmptyStringDecoder$4),
1663
+ images: optional(array(object({ url: optional(nonEmptyStringDecoder$4) }))),
1664
+ icons: optional(array(object({ icon: optional(nonEmptyStringDecoder$4) }))),
1665
+ customConfig: anyJson(),
1666
+ intents: optional(array(intentDefinitionDecoder))
1667
+ });
1668
+ const v2LocalizedDefinitionDecoder = object({
1669
+ appId: optional(nonEmptyStringDecoder$4),
1670
+ name: optional(nonEmptyStringDecoder$4),
1671
+ details: optional(v2DetailsDecoder),
1672
+ version: optional(nonEmptyStringDecoder$4),
1673
+ title: optional(nonEmptyStringDecoder$4),
1674
+ tooltip: optional(nonEmptyStringDecoder$4),
1675
+ lang: optional(nonEmptyStringDecoder$4),
1676
+ description: optional(nonEmptyStringDecoder$4),
1677
+ categories: optional(array(nonEmptyStringDecoder$4)),
1678
+ icons: optional(array(v2IconDecoder)),
1679
+ screenshots: optional(array(v2ScreenshotDecoder)),
1680
+ contactEmail: optional(nonEmptyStringDecoder$4),
1681
+ supportEmail: optional(nonEmptyStringDecoder$4),
1682
+ moreInfo: optional(nonEmptyStringDecoder$4),
1683
+ publisher: optional(nonEmptyStringDecoder$4),
1684
+ customConfig: optional(array(anyJson())),
1685
+ hostManifests: optional(anyJson()),
1686
+ interop: optional(v2InteropDecoder)
1687
+ });
1688
+ const v2DefinitionDecoder = object({
1689
+ appId: nonEmptyStringDecoder$4,
1690
+ name: nonEmptyStringDecoder$4,
1691
+ type: v2TypeDecoder,
1692
+ details: v2DetailsDecoder,
1693
+ version: optional(nonEmptyStringDecoder$4),
1694
+ title: optional(nonEmptyStringDecoder$4),
1695
+ tooltip: optional(nonEmptyStringDecoder$4),
1696
+ lang: optional(nonEmptyStringDecoder$4),
1697
+ description: optional(nonEmptyStringDecoder$4),
1698
+ categories: optional(array(nonEmptyStringDecoder$4)),
1699
+ icons: optional(array(v2IconDecoder)),
1700
+ screenshots: optional(array(v2ScreenshotDecoder)),
1701
+ contactEmail: optional(nonEmptyStringDecoder$4),
1702
+ supportEmail: optional(nonEmptyStringDecoder$4),
1703
+ moreInfo: optional(nonEmptyStringDecoder$4),
1704
+ publisher: optional(nonEmptyStringDecoder$4),
1705
+ customConfig: optional(array(anyJson())),
1706
+ hostManifests: optional(anyJson()),
1707
+ interop: optional(v2InteropDecoder),
1708
+ localizedVersions: optional(dict(v2LocalizedDefinitionDecoder))
1709
+ });
1710
+ const allDefinitionsDecoder = oneOf(v1DefinitionDecoder, v2DefinitionDecoder);
1711
+
1712
+ const parseDecoderErrorToStringMessage = (error) => {
1713
+ return `${error.kind} at ${error.at}: ${JSON.stringify(error.input)}. Reason - ${error.message}`;
1714
+ };
1715
+
1716
+ class FDC3Service {
1717
+ fdc3ToDesktopDefinitionType = {
1718
+ web: "window",
1719
+ native: "exe",
1720
+ citrix: "citrix",
1721
+ onlineNative: "clickonce",
1722
+ other: "window"
1723
+ };
1724
+ toApi() {
1725
+ return {
1726
+ isFdc3Definition: this.isFdc3Definition.bind(this),
1727
+ parseToBrowserBaseAppData: this.parseToBrowserBaseAppData.bind(this),
1728
+ parseToDesktopAppConfig: this.parseToDesktopAppConfig.bind(this)
1729
+ };
1730
+ }
1731
+ isFdc3Definition(definition) {
1732
+ const decodeRes = allDefinitionsDecoder.run(definition);
1733
+ if (!decodeRes.ok) {
1734
+ return { isFdc3: false, reason: parseDecoderErrorToStringMessage(decodeRes.error) };
1735
+ }
1736
+ if (definition.appId && definition.details) {
1737
+ return { isFdc3: true, version: "2.0" };
1738
+ }
1739
+ if (definition.manifest) {
1740
+ return { isFdc3: true, version: "1.2" };
1741
+ }
1742
+ return { isFdc3: false, reason: "The passed definition is not FDC3" };
1743
+ }
1744
+ parseToBrowserBaseAppData(definition) {
1745
+ const { isFdc3, version } = this.isFdc3Definition(definition);
1746
+ if (!isFdc3) {
1747
+ throw new Error("The passed definition is not FDC3");
1748
+ }
1749
+ const decodeRes = allDefinitionsDecoder.run(definition);
1750
+ if (!decodeRes.ok) {
1751
+ throw new Error(`Invalid FDC3 ${version} definition. Error: ${parseDecoderErrorToStringMessage(decodeRes.error)}`);
1752
+ }
1753
+ const userProperties = this.getUserPropertiesFromDefinition(definition, version);
1754
+ const createOptions = { url: this.getUrl(definition, version) };
1755
+ const baseApplicationData = {
1756
+ name: definition.appId,
1757
+ type: "window",
1758
+ createOptions,
1759
+ userProperties: {
1760
+ ...userProperties,
1761
+ intents: version === "1.2"
1762
+ ? userProperties.intents
1763
+ : this.getIntentsFromV2AppDefinition(definition),
1764
+ details: createOptions
1765
+ },
1766
+ title: definition.title,
1767
+ version: definition.version,
1768
+ icon: this.getIconFromDefinition(definition, version),
1769
+ caption: definition.description,
1770
+ fdc3: version === "2.0" ? { ...definition, definitionVersion: "2.0" } : undefined,
1771
+ };
1772
+ const ioConnectDefinition = definition.hostManifests?.ioConnect || definition.hostManifests?.["Glue42"];
1773
+ if (!ioConnectDefinition) {
1774
+ return baseApplicationData;
1775
+ }
1776
+ const ioDefinitionDecodeRes = glue42HostManifestsBrowserDecoder.run(ioConnectDefinition);
1777
+ if (!ioDefinitionDecodeRes.ok) {
1778
+ throw new Error(`Invalid FDC3 ${version} definition. Error: ${parseDecoderErrorToStringMessage(ioDefinitionDecodeRes.error)}`);
1779
+ }
1780
+ if (!Object.keys(ioDefinitionDecodeRes.result).length) {
1781
+ return baseApplicationData;
1782
+ }
1783
+ return this.mergeBaseAppDataWithGlueManifest(baseApplicationData, ioDefinitionDecodeRes.result);
1784
+ }
1785
+ parseToDesktopAppConfig(definition) {
1786
+ const { isFdc3, version } = this.isFdc3Definition(definition);
1787
+ if (!isFdc3) {
1788
+ throw new Error("The passed definition is not FDC3");
1789
+ }
1790
+ const decodeRes = allDefinitionsDecoder.run(definition);
1791
+ if (!decodeRes.ok) {
1792
+ throw new Error(`Invalid FDC3 ${version} definition. Error: ${parseDecoderErrorToStringMessage(decodeRes.error)}`);
1793
+ }
1794
+ if (version === "1.2") {
1795
+ const fdc3v1Definition = definition;
1796
+ return {
1797
+ name: fdc3v1Definition.appId,
1798
+ type: "window",
1799
+ details: {
1800
+ url: this.getUrl(definition, version)
1801
+ },
1802
+ version: fdc3v1Definition.version,
1803
+ title: fdc3v1Definition.title,
1804
+ tooltip: fdc3v1Definition.tooltip,
1805
+ caption: fdc3v1Definition.description,
1806
+ icon: fdc3v1Definition.icons?.[0].icon,
1807
+ intents: fdc3v1Definition.intents,
1808
+ customProperties: {
1809
+ manifestType: fdc3v1Definition.manifestType,
1810
+ images: fdc3v1Definition.images,
1811
+ contactEmail: fdc3v1Definition.contactEmail,
1812
+ supportEmail: fdc3v1Definition.supportEmail,
1813
+ publisher: fdc3v1Definition.publisher,
1814
+ icons: fdc3v1Definition.icons,
1815
+ customConfig: fdc3v1Definition.customConfig
1816
+ }
1817
+ };
1818
+ }
1819
+ const fdc3v2Definition = definition;
1820
+ const desktopDefinition = {
1821
+ name: fdc3v2Definition.appId,
1822
+ type: this.fdc3ToDesktopDefinitionType[fdc3v2Definition.type],
1823
+ details: fdc3v2Definition.details,
1824
+ version: fdc3v2Definition.version,
1825
+ title: fdc3v2Definition.title,
1826
+ tooltip: fdc3v2Definition.tooltip,
1827
+ caption: fdc3v2Definition.description,
1828
+ icon: this.getIconFromDefinition(fdc3v2Definition, "2.0"),
1829
+ intents: this.getIntentsFromV2AppDefinition(fdc3v2Definition),
1830
+ fdc3: { ...fdc3v2Definition, definitionVersion: "2.0" }
1831
+ };
1832
+ const ioConnectDefinition = definition.hostManifests?.ioConnect || definition.hostManifests?.["Glue42"];
1833
+ if (!ioConnectDefinition) {
1834
+ return desktopDefinition;
1835
+ }
1836
+ if (typeof ioConnectDefinition !== "object" || Array.isArray(ioConnectDefinition)) {
1837
+ throw new Error(`Invalid '${definition.hostManifests.ioConnect ? "hostManifests.ioConnect" : "hostManifests['Glue42']"}' key`);
1838
+ }
1839
+ return this.mergeDesktopConfigWithGlueManifest(desktopDefinition, ioConnectDefinition);
1840
+ }
1841
+ getUserPropertiesFromDefinition(definition, version) {
1842
+ if (version === "1.2") {
1843
+ return Object.fromEntries(Object.entries(definition).filter(([key]) => !connectBrowserAppProps.includes(key)));
1844
+ }
1845
+ return Object.fromEntries(Object.entries(definition).filter(([key]) => !connectBrowserAppProps.includes(key) && !fdc3v2AppProps.includes(key)));
1846
+ }
1847
+ getUrl(definition, version) {
1848
+ let url;
1849
+ if (version === "1.2") {
1850
+ const parsedManifest = JSON.parse(definition.manifest);
1851
+ url = parsedManifest.details?.url || parsedManifest.url;
1852
+ }
1853
+ else {
1854
+ url = definition.details?.url;
1855
+ }
1856
+ if (!url || typeof url !== "string") {
1857
+ throw new Error(`Invalid FDC3 ${version} definition. Provide valid 'url' under '${version === "1.2" ? "manifest" : "details"}' key`);
1858
+ }
1859
+ return url;
1860
+ }
1861
+ getIntentsFromV2AppDefinition(definition) {
1862
+ const fdc3Intents = definition.interop?.intents?.listensFor;
1863
+ if (!fdc3Intents) {
1864
+ return;
1865
+ }
1866
+ const intents = Object.entries(fdc3Intents).map((fdc3Intent) => {
1867
+ const [intentName, intentData] = fdc3Intent;
1868
+ return {
1869
+ name: intentName,
1870
+ ...intentData
1871
+ };
1872
+ });
1873
+ return intents;
1874
+ }
1875
+ getIconFromDefinition(definition, version) {
1876
+ if (version === "1.2") {
1877
+ return definition.icons?.find((iconDef) => iconDef.icon)?.icon || undefined;
1878
+ }
1879
+ return definition.icons?.find((iconDef) => iconDef.src)?.src || undefined;
1880
+ }
1881
+ mergeBaseAppDataWithGlueManifest(baseAppData, hostManifestDefinition) {
1882
+ let baseApplicationDefinition = baseAppData;
1883
+ if (hostManifestDefinition.customProperties) {
1884
+ baseApplicationDefinition.userProperties = { ...baseAppData.userProperties, ...hostManifestDefinition.customProperties };
1885
+ }
1886
+ if (hostManifestDefinition.details) {
1887
+ const details = { ...baseAppData.createOptions, ...hostManifestDefinition.details };
1888
+ baseApplicationDefinition.createOptions = details;
1889
+ baseApplicationDefinition.userProperties.details = details;
1890
+ }
1891
+ if (Array.isArray(hostManifestDefinition.intents)) {
1892
+ baseApplicationDefinition.userProperties.intents = (baseApplicationDefinition.userProperties.intents || []).concat(hostManifestDefinition.intents);
1893
+ }
1894
+ baseApplicationDefinition = { ...baseApplicationDefinition, ...hostManifestDefinition };
1895
+ delete baseApplicationDefinition.details;
1896
+ delete baseApplicationDefinition.intents;
1897
+ return baseApplicationDefinition;
1898
+ }
1899
+ mergeDesktopConfigWithGlueManifest(config, desktopDefinition) {
1900
+ const appConfig = Object.assign({}, config, desktopDefinition, { details: { ...config.details, ...desktopDefinition.details } });
1901
+ if (Array.isArray(desktopDefinition.intents)) {
1902
+ appConfig.intents = (config.intents || []).concat(desktopDefinition.intents);
1903
+ }
1904
+ return appConfig;
1905
+ }
1906
+ }
1907
+
1908
+ const decoders$1 = {
1909
+ common: {
1910
+ nonEmptyStringDecoder: nonEmptyStringDecoder$4,
1911
+ nonNegativeNumberDecoder
1912
+ },
1913
+ fdc3: {
1914
+ allDefinitionsDecoder,
1915
+ v1DefinitionDecoder,
1916
+ v2DefinitionDecoder
1917
+ }
1918
+ };
1919
+
1920
+ var INTENTS_ERRORS;
1921
+ (function (INTENTS_ERRORS) {
1922
+ INTENTS_ERRORS["USER_CANCELLED"] = "User Closed Intents Resolver UI without choosing a handler";
1923
+ INTENTS_ERRORS["CALLER_NOT_DEFINED"] = "Caller Id is not defined";
1924
+ INTENTS_ERRORS["TIMEOUT_HIT"] = "Timeout hit";
1925
+ INTENTS_ERRORS["INTENT_NOT_FOUND"] = "Cannot find Intent";
1926
+ INTENTS_ERRORS["HANDLER_NOT_FOUND"] = "Cannot find Intent Handler";
1927
+ INTENTS_ERRORS["TARGET_INSTANCE_UNAVAILABLE"] = "Cannot start Target Instance";
1928
+ INTENTS_ERRORS["INTENT_DELIVERY_FAILED"] = "Target Instance did not add a listener";
1929
+ INTENTS_ERRORS["RESOLVER_UNAVAILABLE"] = "Intents Resolver UI unavailable";
1930
+ INTENTS_ERRORS["RESOLVER_TIMEOUT"] = "User did not choose a handler";
1931
+ INTENTS_ERRORS["INVALID_RESOLVER_RESPONSE"] = "Intents Resolver UI returned invalid response";
1932
+ INTENTS_ERRORS["INTENT_HANDLER_REJECTION"] = "Intent Handler function processing the raised intent threw an error or rejected the promise it returned";
1933
+ })(INTENTS_ERRORS || (INTENTS_ERRORS = {}));
1934
+
1935
+ let IoC$1 = class IoC {
1936
+ _fdc3;
1937
+ _decoders = decoders$1;
1938
+ _errors = {
1939
+ intents: INTENTS_ERRORS
1940
+ };
1941
+ get fdc3() {
1942
+ if (!this._fdc3) {
1943
+ this._fdc3 = new FDC3Service().toApi();
1944
+ }
1945
+ return this._fdc3;
1946
+ }
1947
+ get decoders() {
1948
+ return this._decoders;
1949
+ }
1950
+ get errors() {
1951
+ return this._errors;
1952
+ }
1953
+ };
1954
+
1955
+ const ioc = new IoC$1();
1956
+ ioc.fdc3;
1957
+ const decoders = ioc.decoders;
1958
+ ioc.errors;
1959
+
1960
+ const { nonEmptyStringDecoder: nonEmptyStringDecoder$3 } = decoders.common;
1961
+ const requestMessageTypeDecoder = oneOf$1(constant$1("addContextListenerRequest"), constant$1("addEventListenerRequest"), constant$1("addIntentListenerRequest"), constant$1("broadcastRequest"), constant$1("contextListenerUnsubscribeRequest"), constant$1("createPrivateChannelRequest"), constant$1("eventListenerUnsubscribeRequest"), constant$1("findInstancesRequest"), constant$1("findIntentRequest"), constant$1("findIntentsByContextRequest"), constant$1("getAppMetadataRequest"), constant$1("getCurrentChannelRequest"), constant$1("getCurrentContextRequest"), constant$1("getInfoRequest"), constant$1("getOrCreateChannelRequest"), constant$1("getUserChannelsRequest"), constant$1("heartbeatAcknowledgementRequest"), constant$1("intentListenerUnsubscribeRequest"), constant$1("intentResultRequest"), constant$1("joinUserChannelRequest"), constant$1("leaveCurrentChannelRequest"), constant$1("openRequest"), constant$1("privateChannelAddEventListenerRequest"), constant$1("privateChannelDisconnectRequest"), constant$1("privateChannelUnsubscribeEventListenerRequest"), constant$1("raiseIntentForContextRequest"), constant$1("raiseIntentRequest"));
1962
+ const responseMessageTypeDecoder = oneOf$1(constant$1("addContextListenerResponse"), constant$1("addEventListenerResponse"), constant$1("addIntentListenerResponse"), constant$1("broadcastResponse"), constant$1("contextListenerUnsubscribeResponse"), constant$1("createPrivateChannelResponse"), constant$1("eventListenerUnsubscribeResponse"), constant$1("findInstancesResponse"), constant$1("findIntentResponse"), constant$1("findIntentsByContextResponse"), constant$1("getAppMetadataResponse"), constant$1("getCurrentChannelResponse"), constant$1("getCurrentContextResponse"), constant$1("getInfoResponse"), constant$1("getOrCreateChannelResponse"), constant$1("getUserChannelsResponse"), constant$1("intentListenerUnsubscribeResponse"), constant$1("intentResultResponse"), constant$1("joinUserChannelResponse"), constant$1("leaveCurrentChannelResponse"), constant$1("openResponse"), constant$1("privateChannelAddEventListenerResponse"), constant$1("privateChannelDisconnectResponse"), constant$1("privateChannelUnsubscribeEventListenerResponse"), constant$1("raiseIntentForContextResponse"), constant$1("raiseIntentResponse"), constant$1("raiseIntentResultResponse"));
1963
+ const webConnectionProtocolMessageTypeDecoder = oneOf$1(constant$1("WCP1Hello"), constant$1("WCP2LoadUrl"), constant$1("WCP3Handshake"), constant$1("WCP4ValidateAppIdentity"), constant$1("WCP5ValidateAppIdentityFailedResponse"), constant$1("WCP5ValidateAppIdentityResponse"), constant$1("WCP6Goodbye"));
1964
+ const appIdentifierDecoder = object$1({
1965
+ appId: nonEmptyStringDecoder$3,
1966
+ desktopAgent: optional$1(nonEmptyStringDecoder$3),
1967
+ instanceId: optional$1(nonEmptyStringDecoder$3)
1968
+ });
1969
+ const appRequestMetaDecoder = object$1({
1970
+ requestUuid: nonEmptyStringDecoder$3,
1971
+ timestamp: object$1().where((timestamp) => timestamp instanceof Date, `Expected 'input.meta.timestamp' to be instance of Date`),
1972
+ source: optional$1(appIdentifierDecoder)
1973
+ });
1974
+ const responseMetaDecoder = object$1({
1975
+ requestUuid: nonEmptyStringDecoder$3,
1976
+ responseUuid: nonEmptyStringDecoder$3,
1977
+ source: optional$1(appIdentifierDecoder),
1978
+ timestamp: object$1().where((timestamp) => timestamp instanceof Date, `Expected 'input.meta.timestamp' to be instance of Date`),
1979
+ });
1980
+ const connectionStepMetaDecoder = object$1({
1981
+ connectionAttemptUuid: nonEmptyStringDecoder$3,
1982
+ timestamp: object$1().where((timestamp) => timestamp instanceof Date, `Expected 'input.meta.timestamp' to be instance of Date`),
1983
+ });
1984
+ object$1({
1985
+ type: webConnectionProtocolMessageTypeDecoder,
1986
+ meta: connectionStepMetaDecoder,
1987
+ payload: anyJson$1()
1988
+ });
1989
+ const contextDecoder = object$1({
1990
+ type: nonEmptyStringDecoder$3,
1991
+ name: optional$1(nonEmptyStringDecoder$3),
1992
+ id: optional$1(anyJson$1()),
1993
+ });
1994
+ const responsePayloadErrorDecoder = oneOf$1(constant$1("AccessDenied"), constant$1("CreationFailed"), constant$1("MalformedContext"), constant$1("NoChannelFound"), constant$1("AppNotFound"), constant$1("AppTimeout"), constant$1("DesktopAgentNotFound"), constant$1("ErrorOnLaunch"), constant$1("ResolverUnavailable"), constant$1("IntentDeliveryFailed"), constant$1("NoAppsFound"), constant$1("ResolverTimeout"), constant$1("TargetAppUnavailable"), constant$1("TargetInstanceUnavailable"), constant$1("UserCancelledResolution"), constant$1("IntentHandlerRejected"), constant$1("NoResultReturned"), constant$1("AgentDisconnected"), constant$1("NotConnectedToBridge"), constant$1("ResponseToBridgeTimedOut"), constant$1("MalformedMessage"));
1995
+ const fluffyErrorDecoder = oneOf$1(constant$1("MalformedContext"), constant$1("DesktopAgentNotFound"), constant$1("ResolverUnavailable"), constant$1("IntentDeliveryFailed"), constant$1("NoAppsFound"), constant$1("ResolverTimeout"), constant$1("TargetAppUnavailable"), constant$1("TargetInstanceUnavailable"), constant$1("UserCancelledResolution"));
1996
+ const wcp1HelloPayloadDecoder = object$1({
1997
+ actualUrl: nonEmptyStringDecoder$3,
1998
+ channelSelector: optional$1(boolean$1()),
1999
+ fdc3Version: nonEmptyStringDecoder$3,
2000
+ identityUrl: nonEmptyStringDecoder$3,
2001
+ resolver: optional$1(boolean$1())
2002
+ });
2003
+ const wcp1HelloMetaDecoder = object$1({
2004
+ connectionAttemptUuid: nonEmptyStringDecoder$3,
2005
+ timestamp: object$1().where((timestamp) => timestamp instanceof Date, `Expected 'input.meta.timestamp' to be instance of Date`),
2006
+ });
2007
+ const wcp1HelloDecoder = object$1({
2008
+ type: constant$1("WCP1Hello"),
2009
+ meta: wcp1HelloMetaDecoder,
2010
+ payload: wcp1HelloPayloadDecoder
2011
+ });
2012
+ const wcp3HandshakePayloadChannelSelectorUrlDecoder = oneOf$1(boolean$1(), nonEmptyStringDecoder$3);
2013
+ const wcp3HandshakePayloadIntentResolverUrlDecoder = oneOf$1(boolean$1(), nonEmptyStringDecoder$3);
2014
+ const wcp3HandshakePayloadDecoder = object$1({
2015
+ channelSelectorUrl: wcp3HandshakePayloadChannelSelectorUrlDecoder,
2016
+ fdc3Version: nonEmptyStringDecoder$3,
2017
+ intentResolverUrl: wcp3HandshakePayloadIntentResolverUrlDecoder
2018
+ });
2019
+ object$1({
2020
+ type: constant$1("WCP3Handshake"),
2021
+ meta: wcp1HelloMetaDecoder,
2022
+ payload: wcp3HandshakePayloadDecoder
2023
+ });
2024
+ const wcp4ValidateAppIdentityPayloadDecoder = object$1({
2025
+ actualUrl: nonEmptyStringDecoder$3,
2026
+ identityUrl: nonEmptyStringDecoder$3,
2027
+ instanceId: optional$1(nonEmptyStringDecoder$3),
2028
+ instanceUuid: optional$1(nonEmptyStringDecoder$3)
2029
+ });
2030
+ const wcp4ValidateAppIdentityDecoder = object$1({
2031
+ type: constant$1("WCP4ValidateAppIdentity"),
2032
+ meta: wcp1HelloMetaDecoder,
2033
+ payload: wcp4ValidateAppIdentityPayloadDecoder
2034
+ });
2035
+ const wcp5ValidateAppIdentityFailedResponsePayloadDecoder = object$1({
2036
+ message: optional$1(nonEmptyStringDecoder$3)
2037
+ });
2038
+ object$1({
2039
+ type: constant$1("WCP5ValidateAppIdentityFailedResponse"),
2040
+ meta: wcp1HelloMetaDecoder,
2041
+ payload: wcp5ValidateAppIdentityFailedResponsePayloadDecoder
2042
+ });
2043
+ const wcp6GoodbyeRequestDecoder = object$1({
2044
+ type: constant$1("WCP6Goodbye"),
2045
+ meta: connectionStepMetaDecoder,
2046
+ payload: anyJson$1()
2047
+ });
2048
+ const iconDecoder = object$1({
2049
+ src: nonEmptyStringDecoder$3,
2050
+ size: optional$1(nonEmptyStringDecoder$3),
2051
+ type: optional$1(nonEmptyStringDecoder$3)
2052
+ });
2053
+ const imageDecoder = object$1({
2054
+ src: nonEmptyStringDecoder$3,
2055
+ size: optional$1(nonEmptyStringDecoder$3),
2056
+ type: optional$1(nonEmptyStringDecoder$3),
2057
+ label: optional$1(nonEmptyStringDecoder$3),
2058
+ });
2059
+ const appMetadataDecoder = object$1({
2060
+ appId: nonEmptyStringDecoder$3,
2061
+ description: optional$1(nonEmptyStringDecoder$3),
2062
+ desktopAgent: optional$1(nonEmptyStringDecoder$3),
2063
+ icons: optional$1(array$1(iconDecoder)),
2064
+ instanceId: optional$1(nonEmptyStringDecoder$3),
2065
+ instanceMetadata: optional$1(anyJson$1()),
2066
+ name: optional$1(nonEmptyStringDecoder$3),
2067
+ resultType: optional$1(nonEmptyStringDecoder$3),
2068
+ screenshots: optional$1(array$1(imageDecoder)),
2069
+ title: optional$1(nonEmptyStringDecoder$3),
2070
+ tooltip: optional$1(nonEmptyStringDecoder$3),
2071
+ version: optional$1(nonEmptyStringDecoder$3),
2072
+ });
2073
+ const optionalFeaturesDecoder = object$1({
2074
+ DesktopAgentBridging: boolean$1(),
2075
+ OriginatingAppMetadata: boolean$1(),
2076
+ UserChannelMembershipAPIs: boolean$1()
2077
+ });
2078
+ const implementationMetadataDecoder = object$1({
2079
+ appMetadata: appMetadataDecoder,
2080
+ fdc3Version: nonEmptyStringDecoder$3,
2081
+ optionalFeatures: optionalFeaturesDecoder,
2082
+ provider: nonEmptyStringDecoder$3,
2083
+ providerVersion: optional$1(nonEmptyStringDecoder$3)
2084
+ });
2085
+ const wcp5ValidateAppIdentitySuccessResponsePayloadDecoder = object$1({
2086
+ appId: nonEmptyStringDecoder$3,
2087
+ implementationMetadata: implementationMetadataDecoder,
2088
+ instanceId: nonEmptyStringDecoder$3,
2089
+ instanceUuid: nonEmptyStringDecoder$3
2090
+ });
2091
+ object$1({
2092
+ type: constant$1("WCP5ValidateAppIdentityResponse"),
2093
+ meta: wcp1HelloMetaDecoder,
2094
+ payload: wcp5ValidateAppIdentitySuccessResponsePayloadDecoder
2095
+ });
2096
+
2097
+ const { nonEmptyStringDecoder: nonEmptyStringDecoder$2 } = decoders.common;
2098
+ const addContextListenerRequestMetaDecoder = object$1({
2099
+ requestUuid: nonEmptyStringDecoder$2,
2100
+ source: optional$1(appIdentifierDecoder),
2101
+ timestamp: object$1().where((timestamp) => timestamp instanceof Date, `Expected 'input.meta.timestamp' to be instance of Date`),
2102
+ });
2103
+ const addContextListenerRequestPayloadDecoder = object$1({
2104
+ channelId: optional$1(nonEmptyStringDecoder$2),
2105
+ contextType: optional$1(nonEmptyStringDecoder$2)
2106
+ });
2107
+ const addContextListenerRequestDecoder = object$1({
2108
+ type: constant$1("addContextListenerRequest"),
2109
+ meta: addContextListenerRequestMetaDecoder,
2110
+ payload: addContextListenerRequestPayloadDecoder
2111
+ });
2112
+ const addContextListenerResponseMetaDecoder = object$1({
2113
+ requestUuid: nonEmptyStringDecoder$2,
2114
+ responseUuid: nonEmptyStringDecoder$2,
2115
+ source: optional$1(appIdentifierDecoder),
2116
+ timestamp: object$1().where((timestamp) => timestamp instanceof Date, `Expected 'input.meta.timestamp' to be instance of Date`),
2117
+ });
2118
+ const addEventListenerTypeDecoder = oneOf$1(constant$1("USER_CHANNEL_CHANGED"));
2119
+ const addEventListenerRequestPayloadDecoder = object$1({
2120
+ type: optional$1(addEventListenerTypeDecoder)
2121
+ });
2122
+ const addEventListenerRequestDecoder = object$1({
2123
+ type: constant$1("addEventListenerRequest"),
2124
+ meta: addContextListenerRequestMetaDecoder,
2125
+ payload: addEventListenerRequestPayloadDecoder
2126
+ });
2127
+ const addEventListenerResponsePayloadDecoder = object$1({
2128
+ error: optional$1(responsePayloadErrorDecoder),
2129
+ listenerUUID: optional$1(nonEmptyStringDecoder$2)
2130
+ });
2131
+ const addEventListenerResponseDecoder = object$1({
2132
+ type: constant$1("addEventListenerResponse"),
2133
+ meta: addContextListenerResponseMetaDecoder,
2134
+ payload: addEventListenerResponsePayloadDecoder
2135
+ });
2136
+ const purpleErrorDecoder = oneOf$1(constant$1("AccessDenied"), constant$1("CreationFailed"), constant$1("MalformedContext"), constant$1("NoChannelFound"));
2137
+ const addContextListenerResponsePayloadDecoder = object$1({
2138
+ error: optional$1(purpleErrorDecoder),
2139
+ listenerUUID: optional$1(nonEmptyStringDecoder$2)
2140
+ });
2141
+ const addContextListenerResponseDecoder = object$1({
2142
+ type: constant$1("addContextListenerResponse"),
2143
+ meta: addContextListenerResponseMetaDecoder,
2144
+ payload: addContextListenerResponsePayloadDecoder
2145
+ });
2146
+ const broadcastRequestPayloadDecoder = object$1({
2147
+ channelId: nonEmptyStringDecoder$2,
2148
+ context: contextDecoder
2149
+ });
2150
+ const broadcastRequestDecoder = object$1({
2151
+ type: constant$1("broadcastRequest"),
2152
+ meta: appRequestMetaDecoder,
2153
+ payload: broadcastRequestPayloadDecoder
2154
+ });
2155
+ const broadcastResponsePayloadDecoder = object$1({
2156
+ error: optional$1(responsePayloadErrorDecoder)
2157
+ });
2158
+ const broadcastResponseDecoder = object$1({
2159
+ type: constant$1("broadcastResponse"),
2160
+ meta: responseMetaDecoder,
2161
+ payload: broadcastResponsePayloadDecoder
2162
+ });
2163
+ const channelTypeDecoder = oneOf$1(constant$1("app"), constant$1("user"), constant$1("private"));
2164
+ const displayMetadataDecoder = object$1({
2165
+ color: optional$1(nonEmptyStringDecoder$2),
2166
+ glyph: optional$1(nonEmptyStringDecoder$2),
2167
+ name: optional$1(nonEmptyStringDecoder$2),
2168
+ });
2169
+ const channelDecoder = object$1({
2170
+ id: nonEmptyStringDecoder$2,
2171
+ type: channelTypeDecoder,
2172
+ displayMetadata: optional$1(displayMetadataDecoder)
2173
+ });
2174
+ const contextListenerUnsubscribeRequestPayloadDecoder = object$1({
2175
+ listenerUUID: nonEmptyStringDecoder$2
2176
+ });
2177
+ const contextListenerUnsubscribeRequestDecoder = object$1({
2178
+ type: constant$1("contextListenerUnsubscribeRequest"),
2179
+ meta: addContextListenerRequestMetaDecoder,
2180
+ payload: contextListenerUnsubscribeRequestPayloadDecoder
2181
+ });
2182
+ const contextListenerUnsubscribeResponseDecoder = object$1({
2183
+ type: constant$1("contextListenerUnsubscribeResponse"),
2184
+ meta: addContextListenerResponseMetaDecoder,
2185
+ payload: broadcastResponsePayloadDecoder
2186
+ });
2187
+ const createPrivateChannelRequestDecoder = object$1({
2188
+ type: constant$1("createPrivateChannelRequest"),
2189
+ meta: addContextListenerRequestMetaDecoder,
2190
+ payload: anyJson$1()
2191
+ });
2192
+ const createPrivateChannelResponsePayloadDecoder = object$1({
2193
+ error: optional$1(purpleErrorDecoder),
2194
+ privateChannel: optional$1(channelDecoder)
2195
+ });
2196
+ const createPrivateChannelResponseDecoder = object$1({
2197
+ type: constant$1("createPrivateChannelResponse"),
2198
+ meta: addContextListenerResponseMetaDecoder,
2199
+ payload: createPrivateChannelResponsePayloadDecoder
2200
+ });
2201
+ const eventListenerUnsubscribeRequestPayloadDecoder = object$1({
2202
+ listenerUUID: nonEmptyStringDecoder$2
2203
+ });
2204
+ const eventListenerUnsubscribeRequestDecoder = object$1({
2205
+ type: constant$1("eventListenerUnsubscribeRequest"),
2206
+ meta: addContextListenerRequestMetaDecoder,
2207
+ payload: eventListenerUnsubscribeRequestPayloadDecoder
2208
+ });
2209
+ const eventListenerUnsubscribeResponseDecoder = object$1({
2210
+ type: constant$1("eventListenerUnsubscribeResponse"),
2211
+ meta: addContextListenerResponseMetaDecoder,
2212
+ payload: broadcastResponsePayloadDecoder
2213
+ });
2214
+ const getCurrentChannelRequestDecoder = object$1({
2215
+ type: constant$1("getCurrentChannelRequest"),
2216
+ meta: addContextListenerRequestMetaDecoder,
2217
+ payload: anyJson$1()
2218
+ });
2219
+ const getCurrentChannelResponsePayloadDecoder = object$1({
2220
+ error: optional$1(responsePayloadErrorDecoder),
2221
+ channel: optional$1(channelDecoder)
2222
+ });
2223
+ const getCurrentChannelResponseDecoder = object$1({
2224
+ type: constant$1("getCurrentChannelResponse"),
2225
+ meta: addContextListenerResponseMetaDecoder,
2226
+ payload: getCurrentChannelResponsePayloadDecoder
2227
+ });
2228
+ const getCurrentContextRequestPayloadDecoder = object$1({
2229
+ channelId: nonEmptyStringDecoder$2,
2230
+ contextType: optional$1(nonEmptyStringDecoder$2)
2231
+ });
2232
+ const getCurrentContextRequestDecoder = object$1({
2233
+ type: constant$1("getCurrentContextRequest"),
2234
+ meta: addContextListenerRequestMetaDecoder,
2235
+ payload: getCurrentContextRequestPayloadDecoder
2236
+ });
2237
+ const getCurrentContextResponsePayloadDecoder = object$1({
2238
+ error: optional$1(purpleErrorDecoder),
2239
+ context: optional$1(contextDecoder)
2240
+ });
2241
+ const getCurrentContextResponseDecoder = object$1({
2242
+ type: constant$1("getCurrentContextResponse"),
2243
+ meta: addContextListenerResponseMetaDecoder,
2244
+ payload: getCurrentContextResponsePayloadDecoder
2245
+ });
2246
+ const getOrCreateChannelRequestPayloadDecoder = object$1({
2247
+ channelId: nonEmptyStringDecoder$2
2248
+ });
2249
+ const getOrCreateChannelRequestDecoder = object$1({
2250
+ type: constant$1("getOrCreateChannelRequest"),
2251
+ meta: addContextListenerRequestMetaDecoder,
2252
+ payload: getOrCreateChannelRequestPayloadDecoder
2253
+ });
2254
+ const getOrCreateChannelResponsePayloadDecoder = object$1({
2255
+ error: optional$1(purpleErrorDecoder),
2256
+ channel: optional$1(channelDecoder)
2257
+ });
2258
+ const getOrCreateChannelResponseDecoder = object$1({
2259
+ type: constant$1("getOrCreateChannelResponse"),
2260
+ meta: addContextListenerResponseMetaDecoder,
2261
+ payload: getOrCreateChannelResponsePayloadDecoder
2262
+ });
2263
+ const getUserChannelsRequestDecoder = object$1({
2264
+ type: constant$1("getUserChannelsRequest"),
2265
+ meta: addContextListenerRequestMetaDecoder,
2266
+ payload: anyJson$1()
2267
+ });
2268
+ const getUserChannelsResponsePayloadDecoder = object$1({
2269
+ error: optional$1(purpleErrorDecoder),
2270
+ userChannels: optional$1(array$1(channelDecoder))
2271
+ });
2272
+ const getUserChannelsResponseDecoder = object$1({
2273
+ type: constant$1("getUserChannelsResponse"),
2274
+ meta: addContextListenerResponseMetaDecoder,
2275
+ payload: getUserChannelsResponsePayloadDecoder
2276
+ });
2277
+ const joinUserChannelRequestPayloadDecoder = object$1({
2278
+ channelId: nonEmptyStringDecoder$2
2279
+ });
2280
+ const joinUserChannelRequestDecoder = object$1({
2281
+ type: constant$1("joinUserChannelRequest"),
2282
+ meta: addContextListenerRequestMetaDecoder,
2283
+ payload: joinUserChannelRequestPayloadDecoder
2284
+ });
2285
+ const joinUserChannelResponsePayloadDecoder = object$1({
2286
+ error: optional$1(purpleErrorDecoder)
2287
+ });
2288
+ const joinUserChannelResponseDecoder = object$1({
2289
+ type: constant$1("joinUserChannelResponse"),
2290
+ meta: addContextListenerResponseMetaDecoder,
2291
+ payload: joinUserChannelResponsePayloadDecoder
2292
+ });
2293
+ const leaveCurrentChannelRequestDecoder = object$1({
2294
+ type: constant$1("leaveCurrentChannelRequest"),
2295
+ meta: addContextListenerRequestMetaDecoder,
2296
+ payload: anyJson$1()
2297
+ });
2298
+ const leaveCurrentChannelResponsePayloadDecoder = object$1({
2299
+ error: optional$1(purpleErrorDecoder)
2300
+ });
2301
+ const leaveCurrentChannelResponseDecoder = object$1({
2302
+ type: constant$1("leaveCurrentChannelResponse"),
2303
+ meta: addContextListenerResponseMetaDecoder,
2304
+ payload: leaveCurrentChannelResponsePayloadDecoder
2305
+ });
2306
+ const privateChannelEventListenerTypesDecoder = oneOf$1(constant$1("addContextListener"), constant$1("unsubscribe"), constant$1("disconnect"));
2307
+ const privateChannelAddEventListenerRequestPayloadDecoder = object$1({
2308
+ listenerType: optional$1(privateChannelEventListenerTypesDecoder),
2309
+ privateChannelId: nonEmptyStringDecoder$2
2310
+ });
2311
+ const privateChannelAddEventListenerRequestDecoder = object$1({
2312
+ type: constant$1("privateChannelAddEventListenerRequest"),
2313
+ meta: addContextListenerRequestMetaDecoder,
2314
+ payload: privateChannelAddEventListenerRequestPayloadDecoder
2315
+ });
2316
+ const privateChannelAddEventListenerResponsePayloadDecoder = object$1({
2317
+ listenerUUID: optional$1(nonEmptyStringDecoder$2),
2318
+ error: optional$1(purpleErrorDecoder)
2319
+ });
2320
+ const privateChannelAddEventListenerResponseDecoder = object$1({
2321
+ type: constant$1("privateChannelAddEventListenerResponse"),
2322
+ meta: addContextListenerResponseMetaDecoder,
2323
+ payload: privateChannelAddEventListenerResponsePayloadDecoder
2324
+ });
2325
+ const privateChannelDisconnectRequestPayloadDecoder = object$1({
2326
+ channelId: nonEmptyStringDecoder$2
2327
+ });
2328
+ const privateChannelDisconnectRequestDecoder = object$1({
2329
+ type: constant$1("privateChannelDisconnectRequest"),
2330
+ meta: addContextListenerRequestMetaDecoder,
2331
+ payload: privateChannelDisconnectRequestPayloadDecoder
2332
+ });
2333
+ const privateChannelDisconnectResponseDecoder = object$1({
2334
+ type: constant$1("privateChannelDisconnectResponse"),
2335
+ meta: addContextListenerResponseMetaDecoder,
2336
+ payload: addContextListenerResponsePayloadDecoder
2337
+ });
2338
+ const privateChannelUnsubscribeEventListenerRequestPayloadDecoder = object$1({
2339
+ listenerUUID: nonEmptyStringDecoder$2
2340
+ });
2341
+ const privateChannelUnsubscribeEventListenerRequestDecoder = object$1({
2342
+ type: constant$1("privateChannelUnsubscribeEventListenerRequest"),
2343
+ meta: addContextListenerRequestMetaDecoder,
2344
+ payload: privateChannelUnsubscribeEventListenerRequestPayloadDecoder
2345
+ });
2346
+ const privateChannelUnsubscribeEventListenerResponseDecoder = object$1({
2347
+ type: constant$1("privateChannelUnsubscribeEventListenerResponse"),
2348
+ meta: addContextListenerResponseMetaDecoder,
2349
+ payload: broadcastResponsePayloadDecoder
2350
+ });
2351
+ const broadcastEventMetaDecoder = object$1({
2352
+ eventUuid: nonEmptyStringDecoder$2,
2353
+ timestamp: object$1().where((timestamp) => timestamp instanceof Date, `Expected 'input.meta.timestamp' to be instance of Date`),
2354
+ });
2355
+
2356
+ const { nonEmptyStringDecoder: nonEmptyStringDecoder$1 } = decoders.common;
2357
+ const findInstancesRequestPayloadDecoder = object$1({
2358
+ app: appIdentifierDecoder
2359
+ });
2360
+ const findInstancesRequestDecoder = object$1({
2361
+ type: constant$1("findInstancesRequest"),
2362
+ meta: addContextListenerRequestMetaDecoder,
2363
+ payload: findInstancesRequestPayloadDecoder
2364
+ });
2365
+ const getAppMetadataRequestPayloadDecoder = object$1({
2366
+ app: appIdentifierDecoder
2367
+ });
2368
+ const getAppMetadataRequestDecoder = object$1({
2369
+ type: constant$1("getAppMetadataRequest"),
2370
+ meta: addContextListenerRequestMetaDecoder,
2371
+ payload: getAppMetadataRequestPayloadDecoder
2372
+ });
2373
+ const getInfoRequestDecoder = object$1({
2374
+ type: constant$1("getInfoRequest"),
2375
+ meta: addContextListenerRequestMetaDecoder,
2376
+ payload: anyJson$1()
2377
+ });
2378
+ const openRequestPayloadDecoder = object$1({
2379
+ app: appIdentifierDecoder,
2380
+ context: optional$1(contextDecoder)
2381
+ });
2382
+ const openRequestDecoder = object$1({
2383
+ type: constant$1("openRequest"),
2384
+ meta: addContextListenerRequestMetaDecoder,
2385
+ payload: openRequestPayloadDecoder
2386
+ });
2387
+ const findInstancesErrorsDecoder = oneOf$1(constant$1("MalformedContext"), constant$1("DesktopAgentNotFound"), constant$1("ResolverUnavailable"), constant$1("IntentDeliveryFailed"), constant$1("NoAppsFound"), constant$1("ResolverTimeout"), constant$1("TargetAppUnavailable"), constant$1("TargetInstanceUnavailable"), constant$1("UserCancelledResolution"), constant$1("AgentDisconnected"), constant$1("NotConnectedToBridge"), constant$1("ResponseToBridgeTimedOut"), constant$1("MalformedMessage"));
2388
+ const findInstancesResponsePayloadDecoder = object$1({
2389
+ error: optional$1(findInstancesErrorsDecoder),
2390
+ appIdentifiers: optional$1(array$1(appMetadataDecoder))
2391
+ });
2392
+ const findInstancesResponseDecoder = object$1({
2393
+ type: constant$1("findInstancesResponse"),
2394
+ meta: addContextListenerResponseMetaDecoder,
2395
+ payload: findInstancesResponsePayloadDecoder
2396
+ });
2397
+ const getAppMetadataResponsePayloadDecoder = object$1({
2398
+ error: optional$1(findInstancesErrorsDecoder),
2399
+ appMetadata: optional$1(appMetadataDecoder)
2400
+ });
2401
+ const getAppMetadataResponseDecoder = object$1({
2402
+ type: constant$1("getAppMetadataResponse"),
2403
+ meta: addContextListenerResponseMetaDecoder,
2404
+ payload: getAppMetadataResponsePayloadDecoder
2405
+ });
2406
+ const getInfoResponsePayloadDecoder = object$1({
2407
+ error: optional$1(responsePayloadErrorDecoder),
2408
+ implementationMetadata: optional$1(implementationMetadataDecoder)
2409
+ });
2410
+ const getInfoResponseDecoder = object$1({
2411
+ type: constant$1("getInfoResponse"),
2412
+ meta: addContextListenerResponseMetaDecoder,
2413
+ payload: getInfoResponsePayloadDecoder
2414
+ });
2415
+ const openErrorResponsePayloadDecoder = oneOf$1(constant$1("MalformedContext"), constant$1("AppNotFound"), constant$1("AppTimeout"), constant$1("DesktopAgentNotFound"), constant$1("ErrorOnLaunch"), constant$1("ResolverUnavailable"), constant$1("AgentDisconnected"), constant$1("NotConnectedToBridge"), constant$1("ResponseToBridgeTimedOut"), constant$1("MalformedMessage"));
2416
+ const openResponsePayloadDecoder = object$1({
2417
+ error: optional$1(openErrorResponsePayloadDecoder),
2418
+ appIdentifier: optional$1(appIdentifierDecoder)
2419
+ });
2420
+ const openResponseDecoder = object$1({
2421
+ type: constant$1("openResponse"),
2422
+ meta: addContextListenerResponseMetaDecoder,
2423
+ payload: openResponsePayloadDecoder
2424
+ });
2425
+ const heartbeatAcknowledgementRequestPayloadDecoder = object$1({
2426
+ heartbeatEventUuid: nonEmptyStringDecoder$1
2427
+ });
2428
+ const heartbeatAcknowledgementRequestDecoder = object$1({
2429
+ type: constant$1("heartbeatAcknowledgementRequest"),
2430
+ meta: addContextListenerRequestMetaDecoder,
2431
+ payload: heartbeatAcknowledgementRequestPayloadDecoder
2432
+ });
2433
+ const heartbeatEventPayloadDecoder = anyJson$1();
2434
+ const heartbeatEventDecoder = object$1({
2435
+ type: constant$1("heartbeatEvent"),
2436
+ meta: broadcastEventMetaDecoder,
2437
+ payload: heartbeatEventPayloadDecoder
2438
+ });
2439
+
2440
+ class ApplicationsController {
2441
+ logger;
2442
+ operations = {
2443
+ findInstancesRequest: { requestType: "findInstancesRequest", requestDecoder: findInstancesRequestDecoder, responseType: "findInstancesResponse", responseDecoder: findInstancesResponseDecoder, execute: this.handleFindInstancesRequest.bind(this) },
2444
+ getAppMetadataRequest: { requestType: "getAppMetadataRequest", requestDecoder: getAppMetadataRequestDecoder, responseType: "getAppMetadataResponse", responseDecoder: getAppMetadataResponseDecoder, execute: this.handleGetAppMetadataRequest.bind(this) },
2445
+ getInfoRequest: { requestType: "getInfoRequest", requestDecoder: getInfoRequestDecoder, responseType: "getInfoResponse", responseDecoder: getInfoResponseDecoder, execute: this.handleGetInfoRequest.bind(this) },
2446
+ openRequest: { requestType: "openRequest", requestDecoder: openRequestDecoder, responseType: "openResponse", responseDecoder: openResponseDecoder, execute: this.handleOpenRequest.bind(this) },
2447
+ heartbeatAcknowledgementRequest: { requestType: "heartbeatAcknowledgementRequest", requestDecoder: heartbeatAcknowledgementRequestDecoder, responseType: "heartbeatEvent", responseDecoder: heartbeatEventDecoder, execute: this.handleHeartbeatAcknowledgementRequest.bind(this) }
2448
+ };
2449
+ constructor(logger) {
2450
+ this.logger = logger;
2451
+ }
2452
+ async handleControl(request) {
2453
+ const operation = this.operations[request.type];
2454
+ const responseUuid = nanoid(10);
2455
+ if (!operation) {
2456
+ this.logger?.error(`Controller cannot perform unsupported message: ${JSON.stringify(request)}`);
2457
+ return this.decorateResponse({ request, responseUuid, payload: { error: "MalformedMessage", message: `Received unsupported message type: ${request.type} for request: ${JSON.stringify(request)}` } });
2458
+ }
2459
+ this.logger?.info(`Received request: ${JSON.stringify(request)}`);
2460
+ const { requestDecoder, responseDecoder, execute } = operation;
2461
+ const decodedRequest = requestDecoder.run(request);
2462
+ if (!decodedRequest.ok) {
2463
+ this.logger?.error(`Received invalid request: ${JSON.stringify(request)}`);
2464
+ return this.decorateResponse({ request, responseUuid, payload: { error: "MalformedMessage", message: `Received invalid request message. Reason: ${decodedRequest.error.message}` } });
2465
+ }
2466
+ this.logger?.info(`Handling ${request.type} request: ${JSON.stringify(request)}`);
2467
+ let payload;
2468
+ try {
2469
+ payload = await execute(request);
2470
+ }
2471
+ catch (error) {
2472
+ payload = { error: typeof error === "string" ? error : error.message };
2473
+ }
2474
+ this.logger?.info(`Execution logic for ${request.type} completed. Received payload: ${JSON.stringify(payload)}`);
2475
+ const response = this.decorateResponse({ request, payload, responseUuid });
2476
+ const decodedResponse = responseDecoder.run(response);
2477
+ if (!decodedResponse.ok) {
2478
+ this.logger?.error(`Invalid response type ${response.type}. Error: ${JSON.stringify(decodedResponse.error)}`);
2479
+ return this.decorateResponse({ request, responseUuid, payload: { error: "MalformedMessage", message: `Received invalid response message. Reason: ${decodedResponse.error}` } });
2480
+ }
2481
+ this.logger?.info(`Returning response: ${JSON.stringify(response)}`);
2482
+ return response;
2483
+ }
2484
+ async handleFindInstancesRequest({ payload }) {
2485
+ const appIdentifiers = await window.fdc3?.findInstances(payload.app);
2486
+ return { appIdentifiers };
2487
+ }
2488
+ async handleGetAppMetadataRequest({ payload }) {
2489
+ const appMetadata = await window.fdc3?.getAppMetadata(payload.app);
2490
+ return { appMetadata };
2491
+ }
2492
+ async handleGetInfoRequest(request) {
2493
+ const implementationMetadata = await window.fdc3?.getInfo();
2494
+ return { implementationMetadata };
2495
+ }
2496
+ async handleOpenRequest({ payload }) {
2497
+ const appIdentifier = await window.fdc3?.open(payload.app, payload.context);
2498
+ return { appIdentifier };
2499
+ }
2500
+ async handleHeartbeatAcknowledgementRequest({ heartbeatEventUuid }) {
2501
+ return { alive: true, heartbeatEventUuid };
2502
+ }
2503
+ decorateResponse({ payload, request, responseUuid }) {
2504
+ return {
2505
+ type: this.operations[request.type].responseType,
2506
+ meta: {
2507
+ requestUuid: request.meta.requestUuid,
2508
+ responseUuid: responseUuid,
2509
+ source: request.meta.source,
2510
+ timestamp: new Date()
2511
+ },
2512
+ payload
2513
+ };
2514
+ }
2515
+ }
2516
+
2517
+ var WCPMessageTypes;
2518
+ (function (WCPMessageTypes) {
2519
+ WCPMessageTypes["WCP1Hello"] = "WCP1Hello";
2520
+ WCPMessageTypes["WCP2LoadUrl"] = "WCP2LoadUrl";
2521
+ WCPMessageTypes["WCP3Handshake"] = "WCP3Handshake";
2522
+ WCPMessageTypes["WCP4ValidateAppIdentity"] = "WCP4ValidateAppIdentity";
2523
+ WCPMessageTypes["WCP5ValidateAppIdentityFailedResponse"] = "WCP5ValidateAppIdentityFailedResponse";
2524
+ WCPMessageTypes["WCP5ValidateAppIdentityResponse"] = "WCP5ValidateAppIdentityResponse";
2525
+ WCPMessageTypes["WCP6Goodbye"] = "WCP6Goodbye";
2526
+ })(WCPMessageTypes || (WCPMessageTypes = {}));
2527
+ const FDC3_READY_TIMEOUT = 120 * 1000;
2528
+ const DESKTOP_AGENT_NAME = "io.Connect Browser";
2529
+ const channelTypes = ["user", "app", "private"];
2530
+ const defaultChannelsProps = ["id", "type", "broadcast", "addContextListener", "getCurrentContext"];
2531
+
2532
+ var ChannelEventToTypeDictionary;
2533
+ (function (ChannelEventToTypeDictionary) {
2534
+ ChannelEventToTypeDictionary["USER_CHANNEL_CHANGED"] = "userChannelChanged";
2535
+ })(ChannelEventToTypeDictionary || (ChannelEventToTypeDictionary = {}));
2536
+ const privateChannelPrefix = "___privateFDC3Channel___";
2537
+
2538
+ class ChannelsController {
2539
+ sendBridgeMessage;
2540
+ logger;
2541
+ listenersCollection = {};
2542
+ privateChannelsCollection = {};
2543
+ operations = {
2544
+ addContextListenerRequest: { requestType: "addContextListenerRequest", requestDecoder: addContextListenerRequestDecoder, responseType: "addContextListenerResponse", responseDecoder: addContextListenerResponseDecoder, execute: this.handleAddContextListenerRequest.bind(this) },
2545
+ addEventListenerRequest: { requestType: "addEventListenerRequest", requestDecoder: addEventListenerRequestDecoder, responseType: "addEventListenerResponse", responseDecoder: addEventListenerResponseDecoder, execute: this.handleAddEventListenerRequest.bind(this) },
2546
+ broadcastRequest: { requestType: "broadcastRequest", responseType: "broadcastResponse", requestDecoder: broadcastRequestDecoder, responseDecoder: broadcastResponseDecoder, execute: this.handleBroadcastRequest.bind(this) },
2547
+ contextListenerUnsubscribeRequest: { requestType: "contextListenerUnsubscribeRequest", requestDecoder: contextListenerUnsubscribeRequestDecoder, responseType: "contextListenerUnsubscribeResponse", responseDecoder: contextListenerUnsubscribeResponseDecoder, execute: this.handleUnsubscribeRequest.bind(this) },
2548
+ createPrivateChannelRequest: { requestType: "createPrivateChannelRequest", requestDecoder: createPrivateChannelRequestDecoder, responseType: "createPrivateChannelResponse", responseDecoder: createPrivateChannelResponseDecoder, execute: this.handleCreatePrivateChannelRequest.bind(this) },
2549
+ eventListenerUnsubscribeRequest: { requestType: "eventListenerUnsubscribeRequest", requestDecoder: eventListenerUnsubscribeRequestDecoder, responseType: "eventListenerUnsubscribeResponse", responseDecoder: eventListenerUnsubscribeResponseDecoder, execute: this.handleUnsubscribeRequest.bind(this) },
2550
+ getCurrentChannelRequest: { requestType: "getCurrentChannelRequest", requestDecoder: getCurrentChannelRequestDecoder, responseType: "getCurrentChannelResponse", responseDecoder: getCurrentChannelResponseDecoder, execute: this.handleGetCurrentChannelRequest.bind(this) },
2551
+ getCurrentContextRequest: { requestType: "getCurrentContextRequest", requestDecoder: getCurrentContextRequestDecoder, responseType: "getCurrentContextResponse", responseDecoder: getCurrentContextResponseDecoder, execute: this.handleGetCurrentContextRequest.bind(this) },
2552
+ getOrCreateChannelRequest: { requestType: "getOrCreateChannelRequest", requestDecoder: getOrCreateChannelRequestDecoder, responseType: "getOrCreateChannelResponse", responseDecoder: getOrCreateChannelResponseDecoder, execute: this.handleGetOrCreateChannelRequest.bind(this) },
2553
+ getUserChannelsRequest: { requestType: "getUserChannelsRequest", requestDecoder: getUserChannelsRequestDecoder, responseType: "getUserChannelsResponse", responseDecoder: getUserChannelsResponseDecoder, execute: this.handleGetUserChannelsRequest.bind(this) },
2554
+ joinUserChannelRequest: { requestType: "joinUserChannelRequest", requestDecoder: joinUserChannelRequestDecoder, responseType: "joinUserChannelResponse", responseDecoder: joinUserChannelResponseDecoder, execute: this.handleJoinUserChannelRequest.bind(this) },
2555
+ leaveCurrentChannelRequest: { requestType: "leaveCurrentChannelRequest", requestDecoder: leaveCurrentChannelRequestDecoder, responseType: "leaveCurrentChannelResponse", responseDecoder: leaveCurrentChannelResponseDecoder, execute: this.handleLeaveCurrentChannel.bind(this) },
2556
+ privateChannelAddEventListenerRequest: { requestType: "privateChannelAddEventListenerRequest", requestDecoder: privateChannelAddEventListenerRequestDecoder, responseType: "privateChannelAddEventListenerResponse", responseDecoder: privateChannelAddEventListenerResponseDecoder, execute: this.handlePrivateChannelAddEventListenerRequest.bind(this) },
2557
+ privateChannelDisconnectRequest: { requestType: "privateChannelDisconnectRequest", requestDecoder: privateChannelDisconnectRequestDecoder, responseType: "privateChannelDisconnectResponse", responseDecoder: privateChannelDisconnectResponseDecoder, execute: this.handlePrivateChannelDisconnectRequest.bind(this) },
2558
+ privateChannelUnsubscribeEventListenerRequest: { requestType: "privateChannelUnsubscribeEventListenerRequest", requestDecoder: privateChannelUnsubscribeEventListenerRequestDecoder, responseType: "privateChannelUnsubscribeEventListenerResponse", responseDecoder: privateChannelUnsubscribeEventListenerResponseDecoder, execute: this.handlePrivateChannelUnsubscribeEventListenerRequest.bind(this) }
2559
+ };
2560
+ constructor(sendBridgeMessage, logger) {
2561
+ this.sendBridgeMessage = sendBridgeMessage;
2562
+ this.logger = logger;
2563
+ }
2564
+ async handleControl(request) {
2565
+ const operation = this.operations[request.type];
2566
+ const responseUuid = nanoid(10);
2567
+ if (!operation) {
2568
+ this.logger?.error(`Controller cannot perform unsupported message: ${JSON.stringify(request)}`);
2569
+ return this.decorateResponse({ request, responseUuid, payload: { error: "MalformedMessage", message: `Received unsupported message type: ${request.type} for request: ${JSON.stringify(request)}` } });
2570
+ }
2571
+ this.logger?.info(`Received request: ${JSON.stringify(request)}`);
2572
+ const { requestDecoder, responseDecoder, execute } = operation;
2573
+ const decodedRequest = requestDecoder.run(request);
2574
+ if (!decodedRequest.ok) {
2575
+ this.logger?.error(`Received invalid request: ${JSON.stringify(request)}`);
2576
+ return this.decorateResponse({ request, responseUuid, payload: { error: "MalformedMessage", message: `Received invalid request message. Reason: ${decodedRequest.error.message}` } });
2577
+ }
2578
+ this.logger?.info(`Handling ${request.type} request: ${JSON.stringify(request)}`);
2579
+ let payload;
2580
+ try {
2581
+ payload = await execute(request);
2582
+ }
2583
+ catch (error) {
2584
+ payload = { error: typeof error === "string" ? error : error.message };
2585
+ }
2586
+ this.logger?.info(`Execution logic for ${request.type} completed. Received payload: ${JSON.stringify(payload)}`);
2587
+ const response = this.decorateResponse({ request, payload, responseUuid });
2588
+ const decodedResponse = responseDecoder.run(response);
2589
+ if (!decodedResponse.ok) {
2590
+ this.logger?.error(`Invalid response type ${response.type}. Error: ${JSON.stringify(decodedResponse.error)}`);
2591
+ return this.decorateResponse({ request, responseUuid, payload: { error: "MalformedMessage", message: `Received invalid response message. Reason: ${decodedResponse.error}` } });
2592
+ }
2593
+ this.logger?.info(`Returning response: ${JSON.stringify(response)}`);
2594
+ return response;
2595
+ }
2596
+ addPrivateChannel(privateChannel) {
2597
+ this.logger?.info(`addPrivateChannel called with channel id: ${privateChannel.id}, type: ${privateChannel.type}`);
2598
+ this.privateChannelsCollection[privateChannel.id] = privateChannel;
2599
+ }
2600
+ async handleAddContextListenerRequest({ payload }) {
2601
+ const listenerUUID = nanoid();
2602
+ const channel = payload.channelId ? await this.getChannelById(payload.channelId) : null;
2603
+ const handler = async (context, metadata) => {
2604
+ this.logger?.info(`addContextListener handler invoked with context: ${JSON.stringify(context)} and metadata: ${JSON.stringify(metadata)}`);
2605
+ const eventUuid = nanoid();
2606
+ const channelId = !payload.channelId || channel?.type === "user"
2607
+ ? (await window.fdc3?.getCurrentChannel())?.id ?? null
2608
+ : payload.channelId;
2609
+ const broadcastEventMsg = {
2610
+ type: "broadcastEvent",
2611
+ meta: {
2612
+ eventUuid,
2613
+ timestamp: new Date()
2614
+ },
2615
+ payload: {
2616
+ channelId,
2617
+ context,
2618
+ originatingApp: {
2619
+ appId: metadata?.source.appId ?? "",
2620
+ instanceId: metadata?.source.instanceId,
2621
+ desktopAgent: DESKTOP_AGENT_NAME
2622
+ }
2623
+ }
2624
+ };
2625
+ this.logger?.info(`Sending 'broadcastEvent' message: ${JSON.stringify(broadcastEventMsg)}`);
2626
+ this.sendBridgeMessage(broadcastEventMsg);
2627
+ };
2628
+ const addContextListenerInterfaceMsg = channel ? "channel '" + channel.id + "'" : "fdc3";
2629
+ this.logger?.info(`Adding context listener on ${addContextListenerInterfaceMsg} interface for context type ${payload.contextType ?? null}`);
2630
+ const listener = await (channel ?? window.fdc3)?.addContextListener(payload.contextType ?? null, handler);
2631
+ this.listenersCollection[listenerUUID] = listener;
2632
+ return { listenerUUID };
2633
+ }
2634
+ async getChannelById(id) {
2635
+ const privateChannel = this.privateChannelsCollection[id];
2636
+ if (privateChannel) {
2637
+ return privateChannel;
2638
+ }
2639
+ const channel = await window.fdc3?.getOrCreateChannel(id);
2640
+ return channel;
2641
+ }
2642
+ async handleAddEventListenerRequest({ payload }) {
2643
+ const listenerUUID = nanoid();
2644
+ const handler = (event) => {
2645
+ this.logger?.info(`addEventListener's callback invoked with event: ${JSON.stringify(event)}`);
2646
+ const eventUuid = nanoid();
2647
+ if (event.type !== "userChannelChanged") {
2648
+ return;
2649
+ }
2650
+ const response = {
2651
+ type: "channelChangedEvent",
2652
+ meta: {
2653
+ eventUuid,
2654
+ timestamp: new Date()
2655
+ },
2656
+ payload: {
2657
+ newChannelId: event.details.currentChannelId ?? null,
2658
+ }
2659
+ };
2660
+ this.logger?.info(`Sending 'channelChangedEvent' message: ${JSON.stringify(response)}`);
2661
+ this.sendBridgeMessage(response);
2662
+ };
2663
+ this.logger?.info(`Adding event listener for type ${payload.type ?? null} on fdc3 interface`);
2664
+ const type = this.getAddEventListenerTypeByRequestPayloadType(payload.type);
2665
+ const listener = await window.fdc3.addEventListener(type, handler);
2666
+ this.listenersCollection[listenerUUID] = listener;
2667
+ return { listenerUUID };
2668
+ }
2669
+ getAddEventListenerTypeByRequestPayloadType(requestType) {
2670
+ if (!requestType) {
2671
+ return null;
2672
+ }
2673
+ return ChannelEventToTypeDictionary[requestType] ?? null;
2674
+ }
2675
+ async handleBroadcastRequest({ payload }) {
2676
+ const { channelId, context } = payload;
2677
+ const channel = await this.getChannelById(channelId);
2678
+ await (channel ?? window.fdc3)?.broadcast(context);
2679
+ return {};
2680
+ }
2681
+ async handleUnsubscribeRequest({ payload }) {
2682
+ const listener = this.listenersCollection[payload.listenerUUID];
2683
+ if (!listener) {
2684
+ return { error: "MalformedMessage", reason: `Cannot find listener with listenerUUID: ${payload.listenerUUID}` };
2685
+ }
2686
+ this.logger?.info(`Unsubscribing listener with UUID: ${payload.listenerUUID}`);
2687
+ await listener.unsubscribe();
2688
+ delete this.listenersCollection[payload.listenerUUID];
2689
+ return {};
2690
+ }
2691
+ async handleCreatePrivateChannelRequest() {
2692
+ const privateChannel = await window.fdc3?.createPrivateChannel();
2693
+ if (!privateChannel) {
2694
+ return { error: "CreationFailed" };
2695
+ }
2696
+ this.privateChannelsCollection[privateChannel.id] = privateChannel;
2697
+ const pureChannel = JSON.parse(JSON.stringify(privateChannel));
2698
+ return { privateChannel: pureChannel };
2699
+ }
2700
+ async handleGetCurrentChannelRequest() {
2701
+ const channel = await window.fdc3?.getCurrentChannel();
2702
+ const pureChannel = JSON.parse(JSON.stringify(channel));
2703
+ return { channel: pureChannel };
2704
+ }
2705
+ async handleGetCurrentContextRequest({ payload }) {
2706
+ const channel = await window.fdc3?.getOrCreateChannel(payload.channelId);
2707
+ const contextType = payload.contextType ?? undefined;
2708
+ const context = await channel?.getCurrentContext(contextType);
2709
+ return { context };
2710
+ }
2711
+ async handleGetOrCreateChannelRequest({ payload }) {
2712
+ const isPrivateChannel = this.privateChannelsCollection[payload.channelId] ?? payload.channelId.startsWith(privateChannelPrefix);
2713
+ if (isPrivateChannel) {
2714
+ return { error: "AccessDenied" };
2715
+ }
2716
+ const channel = await window.fdc3?.getOrCreateChannel(payload.channelId);
2717
+ const pureChannel = JSON.parse(JSON.stringify(channel));
2718
+ return { channel: pureChannel };
2719
+ }
2720
+ async handleGetUserChannelsRequest() {
2721
+ const userChannels = await window.fdc3?.getUserChannels() ?? [];
2722
+ const pureChannels = userChannels.map((ch) => JSON.parse(JSON.stringify(ch)));
2723
+ return { userChannels: pureChannels };
2724
+ }
2725
+ async handleJoinUserChannelRequest({ payload }) {
2726
+ await window.fdc3?.joinUserChannel(payload.channelId);
2727
+ return {};
2728
+ }
2729
+ async handleLeaveCurrentChannel(request) {
2730
+ await window.fdc3?.leaveCurrentChannel();
2731
+ return {};
2732
+ }
2733
+ async handlePrivateChannelAddEventListenerRequest({ payload }) {
2734
+ const { listenerType, privateChannelId } = payload;
2735
+ this.logger?.info(`Received private channel addEventListenerRequest with payload: ${JSON.stringify(payload)}`);
2736
+ const privateChannel = this.privateChannelsCollection[privateChannelId];
2737
+ if (!privateChannel) {
2738
+ return { error: "NoChannelFound" };
2739
+ }
2740
+ const handler = (event) => {
2741
+ this.logger?.info(`Received event: ${JSON.stringify(event)}`);
2742
+ if (listenerType && listenerType !== event.type) {
2743
+ this.logger?.info(`Listener type from private channel addEventListenerRequest '${listenerType}' does not match the event type '${event.type}'. Handler won't be invoked...`);
2744
+ return;
2745
+ }
2746
+ const eventUuid = nanoid();
2747
+ const responseType = {
2748
+ type: this.getPrivateChannelResponseType(event.type),
2749
+ meta: {
2750
+ eventUuid,
2751
+ timestamp: new Date()
2752
+ },
2753
+ payload: {
2754
+ contextType: event.details?.contextType,
2755
+ privateChannelId: payload.privateChannelId
2756
+ }
2757
+ };
2758
+ this.logger?.info(`Sending private channel event response: ${JSON.stringify(responseType)}`);
2759
+ this.sendBridgeMessage(responseType);
2760
+ };
2761
+ const listenerUUID = nanoid();
2762
+ const listener = await privateChannel.addEventListener(payload.listenerType ?? null, handler);
2763
+ this.listenersCollection[listenerUUID] = listener;
2764
+ return { listenerUUID };
2765
+ }
2766
+ async handlePrivateChannelDisconnectRequest({ payload }) {
2767
+ const privateChannel = this.privateChannelsCollection[payload.channelId];
2768
+ if (!privateChannel) {
2769
+ return { error: "NoChannelFound" };
2770
+ }
2771
+ await privateChannel.disconnect();
2772
+ delete this.privateChannelsCollection[payload.channelId];
2773
+ return {};
2774
+ }
2775
+ async handlePrivateChannelUnsubscribeEventListenerRequest({ payload }) {
2776
+ const listener = this.listenersCollection[payload.listenerUUID];
2777
+ if (!listener) {
2778
+ return { error: "MalformedMessage", reason: `Cannot find listener with id ${payload.listenerUUID}` };
2779
+ }
2780
+ await listener.unsubscribe();
2781
+ delete this.listenersCollection[payload.listenerUUID];
2782
+ return {};
2783
+ }
2784
+ decorateResponse({ request, payload, responseUuid }) {
2785
+ return {
2786
+ type: this.operations[request.type].responseType,
2787
+ meta: {
2788
+ requestUuid: request.meta.requestUuid,
2789
+ responseUuid: responseUuid,
2790
+ source: request.meta.source,
2791
+ timestamp: new Date()
2792
+ },
2793
+ payload
2794
+ };
2795
+ }
2796
+ getPrivateChannelResponseType(eventType) {
2797
+ if (eventType === "addContextListener") {
2798
+ return "privateChannelOnAddContextListenerEvent";
2799
+ }
2800
+ if (eventType === "disconnect") {
2801
+ return "privateChannelOnDisconnectEvent";
2802
+ }
2803
+ if (eventType === "unsubscribe") {
2804
+ return "privateChannelOnUnsubscribeEvent";
2805
+ }
2806
+ throw new Error(`Invalid event type: ${eventType}`);
2807
+ }
2808
+ }
2809
+
2810
+ class BridgeController {
2811
+ ioController;
2812
+ ioc;
2813
+ _messageChannel;
2814
+ _connectionCompleted = false;
2815
+ _helloMessageOrigin;
2816
+ logger;
2817
+ _globalMessageHandler;
2818
+ constructor(ioController, ioc) {
2819
+ this.ioController = ioController;
2820
+ this.ioc = ioc;
2821
+ }
2822
+ configure() {
2823
+ this._globalMessageHandler = this.globalMessageHandler.bind(this);
2824
+ window.addEventListener("message", this._globalMessageHandler);
2825
+ }
2826
+ sendMessage(data) {
2827
+ this._messageChannel?.port1.postMessage(data);
2828
+ }
2829
+ globalMessageHandler(event) {
2830
+ const parentURL = document.referrer;
2831
+ const origin = new URL(parentURL).origin;
2832
+ if (event.origin !== origin) {
2833
+ return;
2834
+ }
2835
+ if (event.data?.type === WCPMessageTypes.WCP1Hello) {
2836
+ return this.handleHelloConnectionRequest(event.source, event.origin, event.data);
2837
+ }
2838
+ }
2839
+ handleHelloConnectionRequest(source, origin, data) {
2840
+ if (this._messageChannel) {
2841
+ console.warn(`${WCPMessageTypes.WCP1Hello} already heard. Message channel port created`);
2842
+ return;
2843
+ }
2844
+ const decodedRequest = wcp1HelloDecoder.run(data);
2845
+ if (!decodedRequest.ok) {
2846
+ const errorMsg = `Received invalid '${WCPMessageTypes.WCP1Hello}' request: ${JSON.stringify(data)}. Reason: ${decodedRequest.error.message} at ${decodedRequest.error.at}`;
2847
+ console.error(errorMsg);
2848
+ source.postMessage({ error: "MalformedMessage", message: errorMsg }, origin);
2849
+ return;
2850
+ }
2851
+ this._helloMessageOrigin = origin;
2852
+ this._messageChannel = this.ioc.createMessageChannel();
2853
+ this._messageChannel.port1.onmessage = this.handlePortMessage.bind(this);
2854
+ this.sendHandshake(source, origin, data);
2855
+ window.removeEventListener("message", this._globalMessageHandler);
2856
+ }
2857
+ async handlePortMessage(event) {
2858
+ this.logger?.info(`Received port message with data: ${JSON.stringify(event.data)}}`);
2859
+ if (!this._connectionCompleted && event.data?.type !== WCPMessageTypes.WCP6Goodbye && event.data.type !== WCPMessageTypes.WCP4ValidateAppIdentity) {
2860
+ console.warn("Web Connection Protocol not completed yet. Ignoring message");
2861
+ return;
2862
+ }
2863
+ if (event.data?.type === WCPMessageTypes.WCP4ValidateAppIdentity) {
2864
+ return this.handleAppIdentityValidationRequest(event.data);
2865
+ }
2866
+ if (event.data?.type === WCPMessageTypes.WCP6Goodbye) {
2867
+ return this.handleGoodbyeRequest(event.data);
2868
+ }
2869
+ const result = await this.ioc.domainsController.handleMessage(event.data);
2870
+ this.logger?.info(`Sending response message: ${JSON.stringify(result)}`);
2871
+ this.sendMessage(result);
2872
+ }
2873
+ async handleAppIdentityValidationRequest(data) {
2874
+ const decodedRequest = wcp4ValidateAppIdentityDecoder.run(data);
2875
+ if (!decodedRequest.ok) {
2876
+ const errorMsg = `Received invalid '${WCPMessageTypes.WCP4ValidateAppIdentity}' request: ${JSON.stringify(data)}. Reason: ${decodedRequest.error.message} at ${decodedRequest.error.at}`;
2877
+ console.error(errorMsg);
2878
+ this.sendMessage({ error: "MalformedMessage", message: errorMsg });
2879
+ return;
2880
+ }
2881
+ const { actualUrl, identityUrl } = data.payload;
2882
+ await this.ioController.initializeLibs();
2883
+ this.logger = this.ioController.io?.logger.subLogger("bridge.controller");
2884
+ this.logger?.info(`IOBrowser and FDC3 libs are initialized. Received ${data.type} request: ${JSON.stringify(data)}`);
2885
+ const validationResult = this.ioController.validateIdentity({ actualUrl, identityUrl, helloMsgOrigin: this._helloMessageOrigin });
2886
+ if (!validationResult.isValid) {
2887
+ this.logger?.info(`App validation failure. Reason: ${validationResult.message}`);
2888
+ this.sendValidationFailure(data.meta.connectionAttemptUuid, validationResult.message);
2889
+ this.cleanSetup();
2890
+ return;
2891
+ }
2892
+ await this.sendValidationSuccess(data.meta.connectionAttemptUuid, validationResult.appId);
2893
+ this.logger?.info(`App validation is successful. Connection is completed`);
2894
+ this._connectionCompleted = true;
2895
+ }
2896
+ sendHandshake(source, origin, data) {
2897
+ const handshakeMsg = {
2898
+ type: WCPMessageTypes.WCP3Handshake,
2899
+ meta: {
2900
+ connectionAttemptUuid: data.meta.connectionAttemptUuid,
2901
+ timestamp: new Date()
2902
+ },
2903
+ payload: {
2904
+ channelSelectorUrl: true,
2905
+ intentResolverUrl: true,
2906
+ fdc3Version: window.fdc3Info.standardVersion,
2907
+ }
2908
+ };
2909
+ const transfer = this._messageChannel ? [this._messageChannel.port2] : undefined;
2910
+ source.postMessage(handshakeMsg, origin, transfer);
2911
+ }
2912
+ sendValidationFailure(attempt, errorMsg) {
2913
+ const validationFailureMsg = {
2914
+ type: "WCP5ValidateAppIdentityFailedResponse",
2915
+ meta: {
2916
+ connectionAttemptUuid: attempt,
2917
+ timestamp: new Date()
2918
+ },
2919
+ payload: {
2920
+ message: errorMsg
2921
+ }
2922
+ };
2923
+ console.warn(`App Identity Validation failed. Reason: ${errorMsg}`);
2924
+ this.sendMessage(validationFailureMsg);
2925
+ }
2926
+ async sendValidationSuccess(attempt, appId) {
2927
+ const implementationMetadata = await window.fdc3?.getInfo();
2928
+ const instanceId = this.ioController.io?.interop.instance.instance;
2929
+ const interopInstance = this.ioController.io?.interop.instance;
2930
+ const instanceUuid = interopInstance.uuid;
2931
+ const validationSuccessMsg = {
2932
+ type: "WCP5ValidateAppIdentityResponse",
2933
+ meta: {
2934
+ connectionAttemptUuid: attempt,
2935
+ timestamp: new Date()
2936
+ },
2937
+ payload: {
2938
+ appId,
2939
+ instanceId,
2940
+ instanceUuid,
2941
+ implementationMetadata
2942
+ }
2943
+ };
2944
+ this.sendMessage(validationSuccessMsg);
2945
+ }
2946
+ cleanSetup() {
2947
+ this._helloMessageOrigin = undefined;
2948
+ this._messageChannel?.port1.close();
2949
+ this._messageChannel?.port2.close();
2950
+ this._connectionCompleted = false;
2951
+ this._messageChannel = undefined;
2952
+ if (window.__karma__) {
2953
+ this.configure();
2954
+ this.ioController._initializationStarted = false;
2955
+ }
2956
+ }
2957
+ handleGoodbyeRequest(data) {
2958
+ const decodedRequest = wcp6GoodbyeRequestDecoder.run(data);
2959
+ if (!decodedRequest.ok) {
2960
+ const errorMsg = `Received invalid '${WCPMessageTypes.WCP6Goodbye}' request: ${JSON.stringify(data)}. Reason: ${decodedRequest.error.message} at ${decodedRequest.error.at}`;
2961
+ console.error(errorMsg);
2962
+ this.sendMessage({ error: "MalformedMessage", message: errorMsg });
2963
+ return;
2964
+ }
2965
+ this.cleanSetup();
2966
+ }
2967
+ }
2968
+
2969
+ class DomainsController {
2970
+ channelsController;
2971
+ intentsController;
2972
+ applicationsController;
2973
+ ioController;
2974
+ domains;
2975
+ logger;
2976
+ constructor(channelsController, intentsController, applicationsController, ioController) {
2977
+ this.channelsController = channelsController;
2978
+ this.intentsController = intentsController;
2979
+ this.applicationsController = applicationsController;
2980
+ this.ioController = ioController;
2981
+ this.setupDomains();
2982
+ this.logger = this.ioController.getLogger("domains.controller");
2983
+ }
2984
+ async handleMessage(data) {
2985
+ const decodedDataTypeRequest = requestMessageTypeDecoder.run(data.type);
2986
+ if (!decodedDataTypeRequest.ok) {
2987
+ this.logger?.error(`Received invalid request type: ${JSON.stringify(data)}`);
2988
+ return { error: "MalformedMessage", message: `Received invalid request message type: ${decodedDataTypeRequest.error.message}` };
2989
+ }
2990
+ const domain = Object.values(this.domains).find((domain) => domain.requestTypes.includes(data.type));
2991
+ if (!domain) {
2992
+ this.logger?.error(`Cannot find domain for message type: ${data.type}`);
2993
+ return { error: "MalformedMessage", message: `Received unsupported message type: ${data.type}` };
2994
+ }
2995
+ this.logger?.info(`Sending request ${data.type} to domain '${domain.name}'`);
2996
+ const result = await domain.controller.handleControl(data);
2997
+ const decodedResultTypeResponse = responseMessageTypeDecoder.run(result.type);
2998
+ if (!decodedResultTypeResponse.ok) {
2999
+ this.logger?.error(`Received invalid response type: ${JSON.stringify(data)}`);
3000
+ return { error: "MalformedMessage", message: `Received invalid response message type: ${decodedResultTypeResponse.error.message}` };
3001
+ }
3002
+ this.logger?.info(`Returning domain result: ${JSON.stringify(result)}`);
3003
+ return result;
3004
+ }
3005
+ setupDomains() {
3006
+ const channelsRequestTypes = ["addContextListenerRequest", "addEventListenerRequest", "broadcastRequest", "contextListenerUnsubscribeRequest", "createPrivateChannelRequest", "eventListenerUnsubscribeRequest", "getCurrentChannelRequest", "getCurrentContextRequest", "getOrCreateChannelRequest", "getUserChannelsRequest", "joinUserChannelRequest", "leaveCurrentChannelRequest", "privateChannelAddEventListenerRequest", "privateChannelDisconnectRequest", "privateChannelUnsubscribeEventListenerRequest"];
3007
+ const intentsRequestTypes = ["addIntentListenerRequest", "findIntentRequest", "findIntentsByContextRequest", "intentListenerUnsubscribeRequest", "intentResultRequest", "raiseIntentForContextRequest", "raiseIntentRequest"];
3008
+ const applicationsRequestTypes = ["findInstancesRequest", "getAppMetadataRequest", "getInfoRequest", "openRequest", "heartbeatAcknowledgementRequest"];
3009
+ this.domains = {
3010
+ channels: {
3011
+ name: "channels",
3012
+ controller: this.channelsController,
3013
+ requestTypes: channelsRequestTypes
3014
+ },
3015
+ intents: {
3016
+ name: "intents",
3017
+ controller: this.intentsController,
3018
+ requestTypes: intentsRequestTypes
3019
+ },
3020
+ applications: {
3021
+ name: "applications",
3022
+ controller: this.applicationsController,
3023
+ requestTypes: applicationsRequestTypes
3024
+ }
3025
+ };
3026
+ }
3027
+ }
3028
+
3029
+ const rejectWithErrorObj = (reject, error) => {
3030
+ if (error instanceof Error) {
3031
+ reject(error.message);
3032
+ return;
3033
+ }
3034
+ if (typeof error === "string") {
3035
+ reject(new Error(error));
3036
+ return;
3037
+ }
3038
+ reject(new Error(JSON.stringify(error)));
3039
+ };
3040
+ const wrapPromise = () => {
3041
+ let wrapperResolve;
3042
+ let wrapperReject;
3043
+ const promise = new Promise((resolve, reject) => {
3044
+ wrapperResolve = resolve;
3045
+ wrapperReject = reject;
3046
+ });
3047
+ return { promise, resolve: wrapperResolve, reject: wrapperReject };
3048
+ };
3049
+ const promisePlus = (promise, timeoutMilliseconds, timeoutMessage) => {
3050
+ return new Promise((resolve, reject) => {
3051
+ const timeout = setTimeout(() => {
3052
+ const message = timeoutMessage || `Promise timeout hit: ${timeoutMilliseconds}`;
3053
+ reject(new Error(message));
3054
+ }, timeoutMilliseconds);
3055
+ promise()
3056
+ .then((result) => {
3057
+ clearTimeout(timeout);
3058
+ resolve(result);
3059
+ })
3060
+ .catch((error) => {
3061
+ clearTimeout(timeout);
3062
+ rejectWithErrorObj(reject, error);
3063
+ });
3064
+ });
3065
+ };
3066
+ const compareOrigins = (url1, url2) => {
3067
+ try {
3068
+ const parsedUrl1 = new URL(url1);
3069
+ const parsedUrl2 = new URL(url2);
3070
+ return parsedUrl1.origin === parsedUrl2.origin;
3071
+ }
3072
+ catch (e) {
3073
+ return false;
3074
+ }
3075
+ };
3076
+ const removeTrailingSlash = (pathname) => {
3077
+ return pathname.endsWith("/")
3078
+ ? pathname.slice(0, -1)
3079
+ : pathname;
3080
+ };
3081
+ const isRecordUrlMatchToIdentityUrl = (recordUrl, identityUrl) => {
3082
+ let parsedRecordUrl;
3083
+ let parsedIdentityUrl;
3084
+ try {
3085
+ parsedRecordUrl = new URL(recordUrl);
3086
+ parsedIdentityUrl = new URL(identityUrl);
3087
+ }
3088
+ catch (error) {
3089
+ return false;
3090
+ }
3091
+ if (parsedRecordUrl.origin !== parsedIdentityUrl.origin) {
3092
+ return false;
3093
+ }
3094
+ const recordPath = removeTrailingSlash(parsedRecordUrl.pathname);
3095
+ const identityPath = removeTrailingSlash(parsedIdentityUrl.pathname);
3096
+ if (recordPath !== identityPath) {
3097
+ return false;
3098
+ }
3099
+ for (const [key, value] of parsedRecordUrl.searchParams) {
3100
+ if (parsedIdentityUrl.searchParams.get(key) !== value) {
3101
+ return false;
3102
+ }
3103
+ }
3104
+ if (parsedRecordUrl.hash && parsedRecordUrl.hash !== parsedIdentityUrl.hash) {
3105
+ return false;
3106
+ }
3107
+ return true;
3108
+ };
3109
+ const checkIfFDC3Channel = (object) => {
3110
+ if (!object || typeof object !== "object" || Array.isArray(object)) {
3111
+ return false;
3112
+ }
3113
+ if (!channelTypes.includes(object?.type)) {
3114
+ return false;
3115
+ }
3116
+ return defaultChannelsProps.every((prop) => Object.keys(object).includes(prop));
3117
+ };
3118
+ const checkIfFDC3Context = (object) => {
3119
+ if (!object || typeof object !== "object" || Array.isArray(object)) {
3120
+ return false;
3121
+ }
3122
+ return "type" in object && typeof object.type === "string";
3123
+ };
3124
+
3125
+ class IOController {
3126
+ _io;
3127
+ _initializationStarted = false;
3128
+ logger;
3129
+ get io() {
3130
+ return this._io;
3131
+ }
3132
+ validateIdentity({ actualUrl, identityUrl, helloMsgOrigin }) {
3133
+ if (!helloMsgOrigin) {
3134
+ return { isValid: false, message: "There's no WCP1Hello message origin provided" };
3135
+ }
3136
+ this.logger?.info(`Comparing origins of identityUrl '${identityUrl}' with actualUrl '${actualUrl}'`);
3137
+ const sameOriginWithActualUrl = compareOrigins(identityUrl, actualUrl);
3138
+ if (!sameOriginWithActualUrl) {
3139
+ return { isValid: false, message: `Origins of actualUrl (${actualUrl}) and identityUrl (${identityUrl}) does not match` };
3140
+ }
3141
+ this.logger?.info(`Comparing origins of identityUrl '${identityUrl}' with helloMsgOrigin '${helloMsgOrigin}'`);
3142
+ const sameOriginWithHelloEvent = compareOrigins(identityUrl, helloMsgOrigin);
3143
+ if (!sameOriginWithHelloEvent) {
3144
+ return { isValid: false, message: `Origins of initial WCP1Hello event (${helloMsgOrigin}) and identityUrl (${identityUrl}) does not match` };
3145
+ }
3146
+ this.logger?.info(`Searching in app directory for definition matching the provided identity url (${identityUrl})`);
3147
+ const application = this.io?.appManager.applications().find((app) => isRecordUrlMatchToIdentityUrl(app.userProperties.details.url, identityUrl));
3148
+ return application
3149
+ ? { isValid: true, appId: application.name }
3150
+ : { isValid: false, message: `There's no app definition matching the provided identityUrl: ${identityUrl}` };
3151
+ }
3152
+ async initializeLibs() {
3153
+ if (this._initializationStarted) {
3154
+ return;
3155
+ }
3156
+ const fdc3ReadyPromise = this.createFdc3ReadyPromise();
3157
+ this._initializationStarted = true;
3158
+ await this.initializeBrowser();
3159
+ await fdc3ReadyPromise;
3160
+ }
3161
+ getLogger(name) {
3162
+ if (!this._io) {
3163
+ return;
3164
+ }
3165
+ return this._io.logger.subLogger(`fdc3-web-bridge.${name}`);
3166
+ }
3167
+ createFdc3ReadyPromise() {
3168
+ return promisePlus(() => {
3169
+ return new Promise((resolve) => {
3170
+ const fdc3ReadyHandler = () => {
3171
+ window.removeEventListener("fdc3Ready", fdc3ReadyHandler);
3172
+ resolve();
3173
+ };
3174
+ window.addEventListener("fdc3Ready", fdc3ReadyHandler);
3175
+ });
3176
+ }, FDC3_READY_TIMEOUT, `Timeout of ${FDC3_READY_TIMEOUT}ms waiting for @interopio/fdc3 lib to initialize`);
3177
+ }
3178
+ async initializeBrowser() {
3179
+ const parentWindowId = this.getParentWindowId();
3180
+ const config = {
3181
+ identity: {
3182
+ instance: parentWindowId,
3183
+ uuid: parentWindowId,
3184
+ }
3185
+ };
3186
+ this._io = await window.IOBrowser(config);
3187
+ window.io = this._io;
3188
+ this.initLogger();
3189
+ }
3190
+ getParentWindowId() {
3191
+ const urlParams = new URLSearchParams(window.location.search);
3192
+ const name = urlParams.get('parentId');
3193
+ return name ?? "";
3194
+ }
3195
+ initLogger() {
3196
+ this.logger = this.io?.logger.subLogger("io.controller");
3197
+ }
3198
+ }
3199
+
3200
+ const { nonEmptyStringDecoder } = decoders.common;
3201
+ const addIntentListenerRequestPayloadDecoder = object$1({
3202
+ intent: nonEmptyStringDecoder
3203
+ });
3204
+ const addIntentListenerRequestDecoder = object$1({
3205
+ type: constant$1("addIntentListenerRequest"),
3206
+ meta: addContextListenerRequestMetaDecoder,
3207
+ payload: addIntentListenerRequestPayloadDecoder
3208
+ });
3209
+ const findIntentRequestPayloadDecoder = object$1({
3210
+ intent: nonEmptyStringDecoder,
3211
+ context: optional$1(contextDecoder),
3212
+ resultType: optional$1(nonEmptyStringDecoder)
3213
+ });
3214
+ const findIntentRequestDecoder = object$1({
3215
+ type: constant$1("findIntentRequest"),
3216
+ meta: addContextListenerRequestMetaDecoder,
3217
+ payload: findIntentRequestPayloadDecoder
3218
+ });
3219
+ const findIntentsByContextRequestPayloadDecoder = object$1({
3220
+ context: contextDecoder,
3221
+ resultType: optional$1(nonEmptyStringDecoder)
3222
+ });
3223
+ const findIntentsByContextRequestDecoder = object$1({
3224
+ type: constant$1("findIntentsByContextRequest"),
3225
+ meta: addContextListenerRequestMetaDecoder,
3226
+ payload: findIntentsByContextRequestPayloadDecoder
3227
+ });
3228
+ const intentListenerUnsubscribeRequestPayloadDecoder = object$1({
3229
+ listenerUUID: nonEmptyStringDecoder
3230
+ });
3231
+ const intentListenerUnsubscribeRequestDecoder = object$1({
3232
+ type: constant$1("intentListenerUnsubscribeRequest"),
3233
+ meta: addContextListenerRequestMetaDecoder,
3234
+ payload: intentListenerUnsubscribeRequestPayloadDecoder
3235
+ });
3236
+ const intentResultDecoder = object$1({
3237
+ context: optional$1(contextDecoder),
3238
+ channel: optional$1(channelDecoder)
3239
+ });
3240
+ const intentResultRequestPayloadDecoder = object$1({
3241
+ intentEventUuid: nonEmptyStringDecoder,
3242
+ intentResult: intentResultDecoder,
3243
+ raiseIntentRequestUuid: nonEmptyStringDecoder
3244
+ });
3245
+ const intentResultRequestDecoder = object$1({
3246
+ type: constant$1("intentResultRequest"),
3247
+ meta: addContextListenerRequestMetaDecoder,
3248
+ payload: intentResultRequestPayloadDecoder
3249
+ });
3250
+ const raiseIntentForContextRequestPayloadDecoder = object$1({
3251
+ context: contextDecoder,
3252
+ app: optional$1(appIdentifierDecoder)
3253
+ });
3254
+ const raiseIntentForContextRequestDecoder = object$1({
3255
+ type: constant$1("raiseIntentForContextRequest"),
3256
+ meta: addContextListenerRequestMetaDecoder,
3257
+ payload: raiseIntentForContextRequestPayloadDecoder
3258
+ });
3259
+ const raiseIntentRequestPayloadDecoder = object$1({
3260
+ intent: nonEmptyStringDecoder,
3261
+ context: contextDecoder,
3262
+ app: optional$1(appIdentifierDecoder)
3263
+ });
3264
+ const raiseIntentRequestDecoder = object$1({
3265
+ type: constant$1("raiseIntentRequest"),
3266
+ meta: addContextListenerRequestMetaDecoder,
3267
+ payload: raiseIntentRequestPayloadDecoder
3268
+ });
3269
+ const raiseIntentResultRequestDecoder = object$1({
3270
+ type: constant$1("raiseIntentResultRequest"),
3271
+ meta: addContextListenerRequestMetaDecoder,
3272
+ payload: oneOf$1(raiseIntentRequestPayloadDecoder, raiseIntentForContextRequestPayloadDecoder)
3273
+ });
3274
+ const addIntentListenerResponsePayloadDecoder = object$1({
3275
+ error: optional$1(fluffyErrorDecoder),
3276
+ listenerUUID: optional$1(nonEmptyStringDecoder)
3277
+ });
3278
+ const addIntentListenerResponseDecoder = object$1({
3279
+ type: constant$1("addIntentListenerResponse"),
3280
+ meta: addContextListenerResponseMetaDecoder,
3281
+ payload: addIntentListenerResponsePayloadDecoder
3282
+ });
3283
+ const intentMetadataDecoder = object$1({
3284
+ name: nonEmptyStringDecoder,
3285
+ displayName: optional$1(string$1())
3286
+ });
3287
+ const appIntentDecoder = object$1({
3288
+ apps: array$1(appMetadataDecoder),
3289
+ intent: intentMetadataDecoder
3290
+ });
3291
+ const findIntentResponsePayloadDecoder = object$1({
3292
+ error: optional$1(findInstancesErrorsDecoder),
3293
+ appIntent: optional$1(appIntentDecoder)
3294
+ });
3295
+ const findIntentResponseDecoder = object$1({
3296
+ type: constant$1("findIntentResponse"),
3297
+ meta: addContextListenerResponseMetaDecoder,
3298
+ payload: findIntentResponsePayloadDecoder
3299
+ });
3300
+ const findIntentsByContextResponsePayloadDecoder = object$1({
3301
+ error: optional$1(findInstancesErrorsDecoder),
3302
+ appIntents: optional$1(array$1(appIntentDecoder))
3303
+ });
3304
+ const findIntentsByContextResponseDecoder = object$1({
3305
+ type: constant$1("findIntentsByContextResponse"),
3306
+ meta: addContextListenerResponseMetaDecoder,
3307
+ payload: findIntentsByContextResponsePayloadDecoder
3308
+ });
3309
+ const intentListenerUnsubscribeResponseDecoder = object$1({
3310
+ type: constant$1("intentListenerUnsubscribeResponse"),
3311
+ meta: addContextListenerResponseMetaDecoder,
3312
+ payload: broadcastResponsePayloadDecoder
3313
+ });
3314
+ const intentResultResponseDecoder = object$1({
3315
+ type: constant$1("intentResultResponse"),
3316
+ meta: addContextListenerResponseMetaDecoder,
3317
+ payload: broadcastResponsePayloadDecoder
3318
+ });
3319
+ const intentResolutionDecoder = object$1({
3320
+ intent: nonEmptyStringDecoder,
3321
+ source: appIdentifierDecoder
3322
+ });
3323
+ const raiseIntentForContextResponsePayloadDecoder = object$1({
3324
+ error: optional$1(findInstancesErrorsDecoder),
3325
+ intentResolution: optional$1(intentResolutionDecoder),
3326
+ appIntents: optional$1(array$1(appIntentDecoder))
3327
+ });
3328
+ const raiseIntentForContextResponseDecoder = object$1({
3329
+ type: constant$1("raiseIntentForContextResponse"),
3330
+ meta: addContextListenerResponseMetaDecoder,
3331
+ payload: raiseIntentForContextResponsePayloadDecoder
3332
+ });
3333
+ const raiseIntentResponsePayloadDecoder = object$1({
3334
+ error: optional$1(findInstancesErrorsDecoder),
3335
+ intentResolution: optional$1(intentResolutionDecoder),
3336
+ appIntent: optional$1(appIntentDecoder)
3337
+ });
3338
+ const raiseIntentResponseDecoder = object$1({
3339
+ type: constant$1("raiseIntentResponse"),
3340
+ meta: addContextListenerResponseMetaDecoder,
3341
+ payload: raiseIntentResponsePayloadDecoder
3342
+ });
3343
+ const raiseIntentResultResponsePayloadDecoder = object$1({
3344
+ error: optional$1(responsePayloadErrorDecoder),
3345
+ intentResult: optional$1(intentResultDecoder),
3346
+ });
3347
+ const raiseIntentResultResponseDecoder = object$1({
3348
+ type: constant$1("raiseIntentResultResponse"),
3349
+ meta: addContextListenerResponseMetaDecoder,
3350
+ payload: raiseIntentResultResponsePayloadDecoder
3351
+ });
3352
+
3353
+ class IntentsController {
3354
+ sendBridgeMessage;
3355
+ addPrivateChannel;
3356
+ logger;
3357
+ listenersCollection = {};
3358
+ intentResolutionsCollection = {};
3359
+ intentEventPayloadCollection = {};
3360
+ intentHandlerResultPromiseCollection = {};
3361
+ operations = {
3362
+ addIntentListenerRequest: { requestType: "addIntentListenerRequest", requestDecoder: addIntentListenerRequestDecoder, responseType: "addIntentListenerResponse", responseDecoder: addIntentListenerResponseDecoder, execute: this.handleAddIntentListenerRequest.bind(this) },
3363
+ findIntentRequest: { requestType: "findIntentRequest", requestDecoder: findIntentRequestDecoder, responseType: "findIntentResponse", responseDecoder: findIntentResponseDecoder, execute: this.handleFindIntentRequest.bind(this) },
3364
+ findIntentsByContextRequest: { requestType: "findIntentsByContextRequest", requestDecoder: findIntentsByContextRequestDecoder, responseType: "findIntentsByContextResponse", responseDecoder: findIntentsByContextResponseDecoder, execute: this.handleFindIntentsByContextRequest.bind(this) },
3365
+ intentListenerUnsubscribeRequest: { requestType: "intentListenerUnsubscribeRequest", requestDecoder: intentListenerUnsubscribeRequestDecoder, responseType: "intentListenerUnsubscribeResponse", responseDecoder: intentListenerUnsubscribeResponseDecoder, execute: this.handleIntentListenerUnsubscribeRequest.bind(this) },
3366
+ intentResultRequest: { requestType: "intentResultRequest", requestDecoder: intentResultRequestDecoder, responseType: "intentResultResponse", responseDecoder: intentResultResponseDecoder, execute: this.handleIntentResultRequest.bind(this) },
3367
+ raiseIntentForContextRequest: { requestType: "raiseIntentForContextRequest", requestDecoder: raiseIntentForContextRequestDecoder, responseType: "raiseIntentForContextResponse", responseDecoder: raiseIntentForContextResponseDecoder, execute: this.handleRaiseIntentForContextRequest.bind(this) },
3368
+ raiseIntentRequest: { requestType: "raiseIntentRequest", requestDecoder: raiseIntentRequestDecoder, responseType: "raiseIntentResponse", responseDecoder: raiseIntentResponseDecoder, execute: this.handleRaiseIntentRequest.bind(this) },
3369
+ raiseIntentResultRequest: { requestType: "raiseIntentResultRequest", requestDecoder: raiseIntentResultRequestDecoder, responseType: "raiseIntentResultResponse", responseDecoder: raiseIntentResultResponseDecoder, execute: this.handleRaiseIntentResultResponse.bind(this) },
3370
+ };
3371
+ constructor(sendBridgeMessage, addPrivateChannel, logger) {
3372
+ this.sendBridgeMessage = sendBridgeMessage;
3373
+ this.addPrivateChannel = addPrivateChannel;
3374
+ this.logger = logger;
3375
+ }
3376
+ async handleControl(request) {
3377
+ const operation = this.operations[request.type];
3378
+ const responseUuid = nanoid(10);
3379
+ if (!operation) {
3380
+ this.logger?.error(`Controller cannot perform unsupported message: ${JSON.stringify(request)}`);
3381
+ return this.decorateResponse({ request, responseUuid, payload: { error: "MalformedMessage", message: `Received unsupported message type: ${request.type} for request: ${JSON.stringify(request)}` } });
3382
+ }
3383
+ this.logger?.info(`Received request: ${JSON.stringify(request)}`);
3384
+ const { requestDecoder, responseDecoder, execute } = operation;
3385
+ const decodedRequest = requestDecoder.run(request);
3386
+ if (!decodedRequest.ok) {
3387
+ this.logger?.error(`Received invalid request: ${JSON.stringify(request)}`);
3388
+ return this.decorateResponse({ request, responseUuid, payload: { error: "MalformedMessage", message: `Received invalid request message. Reason: ${decodedRequest.error.message}` } });
3389
+ }
3390
+ this.logger?.info(`Handling ${request.type} request: ${JSON.stringify(request)}`);
3391
+ let payload;
3392
+ try {
3393
+ payload = await execute(request);
3394
+ }
3395
+ catch (error) {
3396
+ payload = { error: typeof error === "string" ? error : error.message };
3397
+ }
3398
+ this.logger?.info(`Execution logic for ${request.type} completed. Received payload: ${JSON.stringify(payload)}`);
3399
+ const response = this.decorateResponse({ request, payload, responseUuid });
3400
+ const decodedResponse = responseDecoder.run(response);
3401
+ if (!decodedResponse.ok) {
3402
+ this.logger?.error(`Invalid response type ${response.type}. Error: ${JSON.stringify(decodedResponse.error)}`);
3403
+ return this.decorateResponse({ request, responseUuid, payload: { error: "MalformedMessage", message: `Received invalid response message. Reason: ${decodedResponse.error}` } });
3404
+ }
3405
+ this.logger?.info(`Returning response: ${JSON.stringify(response)}`);
3406
+ return response;
3407
+ }
3408
+ async handleAddIntentListenerRequest({ meta, payload }) {
3409
+ const handler = async (context, metadata) => {
3410
+ const eventUuid = nanoid();
3411
+ this.logger?.info(`Received intent event with context: ${JSON.stringify(context)} and metadata: ${JSON.stringify(metadata)}`);
3412
+ const intentEventPayload = {
3413
+ intent: payload.intent,
3414
+ context,
3415
+ originatingApp: {
3416
+ appId: metadata?.source.appId ?? "",
3417
+ instanceId: metadata?.source.instanceId,
3418
+ desktopAgent: DESKTOP_AGENT_NAME
3419
+ },
3420
+ raiseIntentRequestUuid: meta.requestUuid
3421
+ };
3422
+ this.intentEventPayloadCollection[meta.requestUuid] = intentEventPayload;
3423
+ const intentEventMsg = {
3424
+ type: "intentEvent",
3425
+ meta: { eventUuid, timestamp: new Date() },
3426
+ payload: intentEventPayload
3427
+ };
3428
+ this.logger?.info(`Sending 'intentEvent' message: ${JSON.stringify(intentEventMsg)}`);
3429
+ this.sendBridgeMessage(intentEventMsg);
3430
+ const intentResultReceivedPromise = wrapPromise();
3431
+ this.intentHandlerResultPromiseCollection[eventUuid] = intentResultReceivedPromise;
3432
+ this.logger?.info(`Waiting for intent result for eventUuid: ${eventUuid}`);
3433
+ const result = await intentResultReceivedPromise.promise;
3434
+ const resultToReturn = this.getIntentResultToReturn(result);
3435
+ this.logger?.info(`Returning intent result: ${JSON.stringify(resultToReturn)} for eventUuid: ${eventUuid}`);
3436
+ delete this.intentHandlerResultPromiseCollection[eventUuid];
3437
+ return resultToReturn;
3438
+ };
3439
+ const listenerUUID = nanoid();
3440
+ const listener = await window.fdc3?.addIntentListener(payload.intent, handler);
3441
+ this.listenersCollection[listenerUUID] = listener;
3442
+ return { listenerUUID };
3443
+ }
3444
+ getIntentResultToReturn(result) {
3445
+ this.logger?.info(`Processing received intent result: ${JSON.stringify(result)}`);
3446
+ if (!result || (typeof result === "object" && !Object.keys(result).length)) {
3447
+ return undefined;
3448
+ }
3449
+ if (result.context) {
3450
+ return result.context;
3451
+ }
3452
+ if (result.channel) {
3453
+ return {
3454
+ id: result.channel.id,
3455
+ type: result.channel.type,
3456
+ displayMetadata: result.channel.displayMetadata,
3457
+ broadcast: async () => { },
3458
+ addContextListener: async () => { },
3459
+ getCurrentContext: async () => { }
3460
+ };
3461
+ }
3462
+ }
3463
+ async handleFindIntentRequest({ payload }) {
3464
+ const appIntent = await window.fdc3?.findIntent(payload.intent, payload.context, payload.resultType);
3465
+ return { appIntent };
3466
+ }
3467
+ async handleFindIntentsByContextRequest({ payload }) {
3468
+ const appIntents = await window.fdc3?.findIntentsByContext(payload.context, payload.resultType);
3469
+ return { appIntents };
3470
+ }
3471
+ async handleIntentListenerUnsubscribeRequest({ payload }) {
3472
+ const listener = this.listenersCollection[payload.listenerUUID];
3473
+ if (!listener) {
3474
+ return { error: "MalformedMessage", reason: `Cannot find listener with id ${payload.listenerUUID}` };
3475
+ }
3476
+ listener.unsubscribe();
3477
+ delete this.listenersCollection[payload.listenerUUID];
3478
+ return {};
3479
+ }
3480
+ async handleIntentResultRequest({ payload }) {
3481
+ this.logger?.info(`Received intent result request with payload: ${JSON.stringify(payload)}`);
3482
+ const intentEventUuid = payload.intentEventUuid;
3483
+ const intentEventResultPromise = this.intentHandlerResultPromiseCollection[intentEventUuid];
3484
+ if (!intentEventResultPromise) {
3485
+ this.logger?.error(`No intent handler result promise found for eventUuid: ${intentEventUuid}`);
3486
+ return { error: "MalformedMessage" };
3487
+ }
3488
+ this.logger?.info(`Resolving intent handler result promise for eventUuid: ${intentEventUuid} with result: ${JSON.stringify(payload.intentResult)}`);
3489
+ intentEventResultPromise.resolve(payload.intentResult);
3490
+ return {};
3491
+ }
3492
+ async handleRaiseIntentForContextRequest({ meta, payload }) {
3493
+ const intentResolution = await window.fdc3?.raiseIntentForContext(payload.context, payload.app);
3494
+ if (!intentResolution) {
3495
+ return { error: "IntentDeliveryFailed" };
3496
+ }
3497
+ this.logger?.info(`Saving intent resolution for requestUuid: ${meta.requestUuid}`);
3498
+ this.intentResolutionsCollection[meta.requestUuid] = intentResolution;
3499
+ const intentResolutionToReturn = { source: intentResolution.source, intent: intentResolution.intent };
3500
+ this.processRaiseIntentResultResponseAsync({
3501
+ type: "raiseIntentForContextRequest",
3502
+ payload,
3503
+ meta
3504
+ });
3505
+ return { intentResolution: intentResolutionToReturn };
3506
+ }
3507
+ async handleRaiseIntentRequest({ payload, meta }) {
3508
+ const intentResolution = await window.fdc3?.raiseIntent(payload.intent, payload.context, payload.app);
3509
+ if (!intentResolution) {
3510
+ return { error: "IntentDeliveryFailed" };
3511
+ }
3512
+ this.logger?.info(`Saving intent resolution for requestUuid: ${meta.requestUuid}`);
3513
+ this.intentResolutionsCollection[meta.requestUuid] = intentResolution;
3514
+ const intentResolutionToReturn = { source: intentResolution.source, intent: intentResolution.intent };
3515
+ this.processRaiseIntentResultResponseAsync({
3516
+ type: "raiseIntentRequest",
3517
+ payload,
3518
+ meta
3519
+ });
3520
+ return { intentResolution: intentResolutionToReturn };
3521
+ }
3522
+ async handleRaiseIntentResultResponse({ payload, meta }) {
3523
+ this.logger?.info(`handleRaiseIntentResultResponse called with payload: ${JSON.stringify(payload)} and meta: ${JSON.stringify(meta)}`);
3524
+ const intentResolution = await this.intentResolutionsCollection[meta.requestUuid];
3525
+ if (!intentResolution) {
3526
+ this.logger?.info(`Did not find intent resolution for requestUuid: ${meta.requestUuid}`);
3527
+ return { error: "IntentDeliveryFailed" };
3528
+ }
3529
+ this.logger?.info(`Found intent resolution for requestUuid: ${meta.requestUuid}. Retrieving result...`);
3530
+ const result = await intentResolution.getResult();
3531
+ this.logger?.info(`Received intent result: ${JSON.stringify(result)}`);
3532
+ if (!result) {
3533
+ const intentStr = payload.intent ? "intent '" + payload.intent + "'" : "";
3534
+ const contextStr = payload.context ? "context type '" + payload.context + "'" : "";
3535
+ this.logger?.info(`Intent result is void for ${intentStr}${contextStr} and requestUuid: ${meta.requestUuid}`);
3536
+ return { intentResult: undefined };
3537
+ }
3538
+ const intentResult = this.extractRaiseIntentResult(result);
3539
+ this.logger?.info(`Extracted intent result: ${JSON.stringify(intentResult)}`);
3540
+ return intentResult;
3541
+ }
3542
+ extractRaiseIntentResult(receivedResult) {
3543
+ if (!receivedResult) {
3544
+ return { intentResult: undefined };
3545
+ }
3546
+ const isChannel = checkIfFDC3Channel(receivedResult);
3547
+ if (isChannel) {
3548
+ this.checkSetPrivateChanel(receivedResult);
3549
+ return { intentResult: { channel: JSON.parse(JSON.stringify(receivedResult)) } };
3550
+ }
3551
+ const isContext = checkIfFDC3Context(receivedResult);
3552
+ if (isContext) {
3553
+ return { intentResult: { context: receivedResult } };
3554
+ }
3555
+ if (receivedResult.error) {
3556
+ return { error: receivedResult.error };
3557
+ }
3558
+ return { error: "IntentDeliveryFailed" };
3559
+ }
3560
+ checkSetPrivateChanel(channel) {
3561
+ const isPrivate = channel.id.startsWith(privateChannelPrefix) && channel.type === "private";
3562
+ if (!isPrivate) {
3563
+ return;
3564
+ }
3565
+ this.addPrivateChannel(channel);
3566
+ }
3567
+ async processRaiseIntentResultResponseAsync({ payload, meta }) {
3568
+ this.logger?.warn("Processing raise intent result response asynchronously with payload: " + JSON.stringify(payload));
3569
+ const syntheticRequest = {
3570
+ type: "raiseIntentResultRequest",
3571
+ meta: {
3572
+ requestUuid: meta.requestUuid,
3573
+ source: meta.source,
3574
+ timestamp: new Date()
3575
+ },
3576
+ payload: payload
3577
+ };
3578
+ const response = await this.handleControl(syntheticRequest);
3579
+ this.logger?.info(`Sending raise intent result response: ${JSON.stringify(response)}`);
3580
+ this.sendBridgeMessage(response);
3581
+ }
3582
+ decorateResponse({ request, responseUuid, payload }) {
3583
+ return {
3584
+ type: this.operations[request.type].responseType,
3585
+ meta: {
3586
+ requestUuid: request.meta.requestUuid,
3587
+ responseUuid: responseUuid,
3588
+ source: request.meta.source,
3589
+ timestamp: new Date()
3590
+ },
3591
+ payload
3592
+ };
3593
+ }
3594
+ }
3595
+
3596
+ class IoC {
3597
+ _bridgeController;
3598
+ _ioController;
3599
+ _domainsController;
3600
+ _channelsController;
3601
+ _intentsController;
3602
+ _applicationsController;
3603
+ get bridgeController() {
3604
+ if (!this._bridgeController) {
3605
+ this._bridgeController = new BridgeController(this.ioController, this);
3606
+ }
3607
+ return this._bridgeController;
3608
+ }
3609
+ get ioController() {
3610
+ if (!this._ioController) {
3611
+ this._ioController = new IOController();
3612
+ }
3613
+ return this._ioController;
3614
+ }
3615
+ createMessageChannel() {
3616
+ return new MessageChannel();
3617
+ }
3618
+ get domainsController() {
3619
+ if (!this._domainsController) {
3620
+ this._domainsController = new DomainsController(this.channelsController, this.intentsController, this.applicationsController, this.ioController);
3621
+ }
3622
+ return this._domainsController;
3623
+ }
3624
+ get channelsController() {
3625
+ if (!this._channelsController) {
3626
+ this._channelsController = new ChannelsController(this.bridgeController.sendMessage.bind(this.bridgeController), this.ioController.getLogger("channels.controller"));
3627
+ }
3628
+ return this._channelsController;
3629
+ }
3630
+ get intentsController() {
3631
+ if (!this._intentsController) {
3632
+ this._intentsController = new IntentsController(this.bridgeController.sendMessage.bind(this.bridgeController), this.channelsController.addPrivateChannel.bind(this.channelsController), this.ioController.getLogger("intents.controller"));
3633
+ }
3634
+ return this._intentsController;
3635
+ }
3636
+ get applicationsController() {
3637
+ if (!this._applicationsController) {
3638
+ this._applicationsController = new ApplicationsController(this.ioController.getLogger("applications.controller"));
3639
+ }
3640
+ return this._applicationsController;
3641
+ }
3642
+ }
3643
+
3644
+ var version = "1.0.0";
3645
+
3646
+ window.fdc3WebBridgeInfo = {
3647
+ version
3648
+ };
3649
+ const start = () => {
3650
+ const ioc = new IoC();
3651
+ ioc.bridgeController.configure();
3652
+ };
3653
+ start();
3654
+
3655
+ }));
3656
+ //# sourceMappingURL=fdc3-web-bridge.umd.js.map