@interopio/iframes-api 0.1.0-beta.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,1237 @@
1
+ (function (global, factory) {
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
3
+ typeof define === 'function' && define.amd ? define(factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.iframes = factory());
5
+ })(this, (function () { 'use strict';
6
+
7
+ const BrowserPlatformControlName = "T42.Web.Platform.Control";
8
+ const GlueIFramesControlName = "T42.IFrames.Control";
9
+
10
+ /**
11
+ * Wraps values in an `Ok` type.
12
+ *
13
+ * Example: `ok(5) // => {ok: true, result: 5}`
14
+ */
15
+ var ok = function (result) { return ({ ok: true, result: result }); };
16
+ /**
17
+ * Wraps errors in an `Err` type.
18
+ *
19
+ * Example: `err('on fire') // => {ok: false, error: 'on fire'}`
20
+ */
21
+ var err = function (error) { return ({ ok: false, error: error }); };
22
+ /**
23
+ * Create a `Promise` that either resolves with the result of `Ok` or rejects
24
+ * with the error of `Err`.
25
+ */
26
+ var asPromise = function (r) {
27
+ return r.ok === true ? Promise.resolve(r.result) : Promise.reject(r.error);
28
+ };
29
+ /**
30
+ * Unwraps a `Result` and returns either the result of an `Ok`, or
31
+ * `defaultValue`.
32
+ *
33
+ * Example:
34
+ * ```
35
+ * Result.withDefault(5, number().run(json))
36
+ * ```
37
+ *
38
+ * It would be nice if `Decoder` had an instance method that mirrored this
39
+ * function. Such a method would look something like this:
40
+ * ```
41
+ * class Decoder<A> {
42
+ * runWithDefault = (defaultValue: A, json: any): A =>
43
+ * Result.withDefault(defaultValue, this.run(json));
44
+ * }
45
+ *
46
+ * number().runWithDefault(5, json)
47
+ * ```
48
+ * Unfortunately, the type of `defaultValue: A` on the method causes issues
49
+ * with type inference on the `object` decoder in some situations. While these
50
+ * inference issues can be solved by providing the optional type argument for
51
+ * `object`s, the extra trouble and confusion doesn't seem worth it.
52
+ */
53
+ var withDefault = function (defaultValue, r) {
54
+ return r.ok === true ? r.result : defaultValue;
55
+ };
56
+ /**
57
+ * Return the successful result, or throw an error.
58
+ */
59
+ var withException = function (r) {
60
+ if (r.ok === true) {
61
+ return r.result;
62
+ }
63
+ else {
64
+ throw r.error;
65
+ }
66
+ };
67
+ /**
68
+ * Apply `f` to the result of an `Ok`, or pass the error through.
69
+ */
70
+ var map = function (f, r) {
71
+ return r.ok === true ? ok(f(r.result)) : r;
72
+ };
73
+ /**
74
+ * Apply `f` to the result of two `Ok`s, or pass an error through. If both
75
+ * `Result`s are errors then the first one is returned.
76
+ */
77
+ var map2 = function (f, ar, br) {
78
+ return ar.ok === false ? ar :
79
+ br.ok === false ? br :
80
+ ok(f(ar.result, br.result));
81
+ };
82
+ /**
83
+ * Apply `f` to the error of an `Err`, or pass the success through.
84
+ */
85
+ var mapError = function (f, r) {
86
+ return r.ok === true ? r : err(f(r.error));
87
+ };
88
+ /**
89
+ * Chain together a sequence of computations that may fail, similar to a
90
+ * `Promise`. If the first computation fails then the error will propagate
91
+ * through. If it succeeds, then `f` will be applied to the value, returning a
92
+ * new `Result`.
93
+ */
94
+ var andThen = function (f, r) {
95
+ return r.ok === true ? f(r.result) : r;
96
+ };
97
+
98
+ /*! *****************************************************************************
99
+ Copyright (c) Microsoft Corporation.
100
+
101
+ Permission to use, copy, modify, and/or distribute this software for any
102
+ purpose with or without fee is hereby granted.
103
+
104
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
105
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
106
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
107
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
108
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
109
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
110
+ PERFORMANCE OF THIS SOFTWARE.
111
+ ***************************************************************************** */
112
+ /* global Reflect, Promise */
113
+
114
+
115
+
116
+ var __assign = function() {
117
+ __assign = Object.assign || function __assign(t) {
118
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
119
+ s = arguments[i];
120
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
121
+ }
122
+ return t;
123
+ };
124
+ return __assign.apply(this, arguments);
125
+ };
126
+
127
+ function __rest(s, e) {
128
+ var t = {};
129
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
130
+ t[p] = s[p];
131
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
132
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
133
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
134
+ t[p[i]] = s[p[i]];
135
+ }
136
+ return t;
137
+ }
138
+
139
+ function isEqual(a, b) {
140
+ if (a === b) {
141
+ return true;
142
+ }
143
+ if (a === null && b === null) {
144
+ return true;
145
+ }
146
+ if (typeof (a) !== typeof (b)) {
147
+ return false;
148
+ }
149
+ if (typeof (a) === 'object') {
150
+ // Array
151
+ if (Array.isArray(a)) {
152
+ if (!Array.isArray(b)) {
153
+ return false;
154
+ }
155
+ if (a.length !== b.length) {
156
+ return false;
157
+ }
158
+ for (var i = 0; i < a.length; i++) {
159
+ if (!isEqual(a[i], b[i])) {
160
+ return false;
161
+ }
162
+ }
163
+ return true;
164
+ }
165
+ // Hash table
166
+ var keys = Object.keys(a);
167
+ if (keys.length !== Object.keys(b).length) {
168
+ return false;
169
+ }
170
+ for (var i = 0; i < keys.length; i++) {
171
+ if (!b.hasOwnProperty(keys[i])) {
172
+ return false;
173
+ }
174
+ if (!isEqual(a[keys[i]], b[keys[i]])) {
175
+ return false;
176
+ }
177
+ }
178
+ return true;
179
+ }
180
+ }
181
+ /*
182
+ * Helpers
183
+ */
184
+ var isJsonArray = function (json) { return Array.isArray(json); };
185
+ var isJsonObject = function (json) {
186
+ return typeof json === 'object' && json !== null && !isJsonArray(json);
187
+ };
188
+ var typeString = function (json) {
189
+ switch (typeof json) {
190
+ case 'string':
191
+ return 'a string';
192
+ case 'number':
193
+ return 'a number';
194
+ case 'boolean':
195
+ return 'a boolean';
196
+ case 'undefined':
197
+ return 'undefined';
198
+ case 'object':
199
+ if (json instanceof Array) {
200
+ return 'an array';
201
+ }
202
+ else if (json === null) {
203
+ return 'null';
204
+ }
205
+ else {
206
+ return 'an object';
207
+ }
208
+ default:
209
+ return JSON.stringify(json);
210
+ }
211
+ };
212
+ var expectedGot = function (expected, got) {
213
+ return "expected " + expected + ", got " + typeString(got);
214
+ };
215
+ var printPath = function (paths) {
216
+ return paths.map(function (path) { return (typeof path === 'string' ? "." + path : "[" + path + "]"); }).join('');
217
+ };
218
+ var prependAt = function (newAt, _a) {
219
+ var at = _a.at, rest = __rest(_a, ["at"]);
220
+ return (__assign({ at: newAt + (at || '') }, rest));
221
+ };
222
+ /**
223
+ * Decoders transform json objects with unknown structure into known and
224
+ * verified forms. You can create objects of type `Decoder<A>` with either the
225
+ * primitive decoder functions, such as `boolean()` and `string()`, or by
226
+ * applying higher-order decoders to the primitives, such as `array(boolean())`
227
+ * or `dict(string())`.
228
+ *
229
+ * Each of the decoder functions are available both as a static method on
230
+ * `Decoder` and as a function alias -- for example the string decoder is
231
+ * defined at `Decoder.string()`, but is also aliased to `string()`. Using the
232
+ * function aliases exported with the library is recommended.
233
+ *
234
+ * `Decoder` exposes a number of 'run' methods, which all decode json in the
235
+ * same way, but communicate success and failure in different ways. The `map`
236
+ * and `andThen` methods modify decoders without having to call a 'run' method.
237
+ *
238
+ * Alternatively, the main decoder `run()` method returns an object of type
239
+ * `Result<A, DecoderError>`. This library provides a number of helper
240
+ * functions for dealing with the `Result` type, so you can do all the same
241
+ * things with a `Result` as with the decoder methods.
242
+ */
243
+ var Decoder = /** @class */ (function () {
244
+ /**
245
+ * The Decoder class constructor is kept private to separate the internal
246
+ * `decode` function from the external `run` function. The distinction
247
+ * between the two functions is that `decode` returns a
248
+ * `Partial<DecoderError>` on failure, which contains an unfinished error
249
+ * report. When `run` is called on a decoder, the relevant series of `decode`
250
+ * calls is made, and then on failure the resulting `Partial<DecoderError>`
251
+ * is turned into a `DecoderError` by filling in the missing information.
252
+ *
253
+ * While hiding the constructor may seem restrictive, leveraging the
254
+ * provided decoder combinators and helper functions such as
255
+ * `andThen` and `map` should be enough to build specialized decoders as
256
+ * needed.
257
+ */
258
+ function Decoder(decode) {
259
+ var _this = this;
260
+ this.decode = decode;
261
+ /**
262
+ * Run the decoder and return a `Result` with either the decoded value or a
263
+ * `DecoderError` containing the json input, the location of the error, and
264
+ * the error message.
265
+ *
266
+ * Examples:
267
+ * ```
268
+ * number().run(12)
269
+ * // => {ok: true, result: 12}
270
+ *
271
+ * string().run(9001)
272
+ * // =>
273
+ * // {
274
+ * // ok: false,
275
+ * // error: {
276
+ * // kind: 'DecoderError',
277
+ * // input: 9001,
278
+ * // at: 'input',
279
+ * // message: 'expected a string, got 9001'
280
+ * // }
281
+ * // }
282
+ * ```
283
+ */
284
+ this.run = function (json) {
285
+ return mapError(function (error) { return ({
286
+ kind: 'DecoderError',
287
+ input: json,
288
+ at: 'input' + (error.at || ''),
289
+ message: error.message || ''
290
+ }); }, _this.decode(json));
291
+ };
292
+ /**
293
+ * Run the decoder as a `Promise`.
294
+ */
295
+ this.runPromise = function (json) { return asPromise(_this.run(json)); };
296
+ /**
297
+ * Run the decoder and return the value on success, or throw an exception
298
+ * with a formatted error string.
299
+ */
300
+ this.runWithException = function (json) { return withException(_this.run(json)); };
301
+ /**
302
+ * Construct a new decoder that applies a transformation to the decoded
303
+ * result. If the decoder succeeds then `f` will be applied to the value. If
304
+ * it fails the error will propagated through.
305
+ *
306
+ * Example:
307
+ * ```
308
+ * number().map(x => x * 5).run(10)
309
+ * // => {ok: true, result: 50}
310
+ * ```
311
+ */
312
+ this.map = function (f) {
313
+ return new Decoder(function (json) { return map(f, _this.decode(json)); });
314
+ };
315
+ /**
316
+ * Chain together a sequence of decoders. The first decoder will run, and
317
+ * then the function will determine what decoder to run second. If the result
318
+ * of the first decoder succeeds then `f` will be applied to the decoded
319
+ * value. If it fails the error will propagate through.
320
+ *
321
+ * This is a very powerful method -- it can act as both the `map` and `where`
322
+ * methods, can improve error messages for edge cases, and can be used to
323
+ * make a decoder for custom types.
324
+ *
325
+ * Example of adding an error message:
326
+ * ```
327
+ * const versionDecoder = valueAt(['version'], number());
328
+ * const infoDecoder3 = object({a: boolean()});
329
+ *
330
+ * const decoder = versionDecoder.andThen(version => {
331
+ * switch (version) {
332
+ * case 3:
333
+ * return infoDecoder3;
334
+ * default:
335
+ * return fail(`Unable to decode info, version ${version} is not supported.`);
336
+ * }
337
+ * });
338
+ *
339
+ * decoder.run({version: 3, a: true})
340
+ * // => {ok: true, result: {a: true}}
341
+ *
342
+ * decoder.run({version: 5, x: 'abc'})
343
+ * // =>
344
+ * // {
345
+ * // ok: false,
346
+ * // error: {... message: 'Unable to decode info, version 5 is not supported.'}
347
+ * // }
348
+ * ```
349
+ *
350
+ * Example of decoding a custom type:
351
+ * ```
352
+ * // nominal type for arrays with a length of at least one
353
+ * type NonEmptyArray<T> = T[] & { __nonEmptyArrayBrand__: void };
354
+ *
355
+ * const nonEmptyArrayDecoder = <T>(values: Decoder<T>): Decoder<NonEmptyArray<T>> =>
356
+ * array(values).andThen(arr =>
357
+ * arr.length > 0
358
+ * ? succeed(createNonEmptyArray(arr))
359
+ * : fail(`expected a non-empty array, got an empty array`)
360
+ * );
361
+ * ```
362
+ */
363
+ this.andThen = function (f) {
364
+ return new Decoder(function (json) {
365
+ return andThen(function (value) { return f(value).decode(json); }, _this.decode(json));
366
+ });
367
+ };
368
+ /**
369
+ * Add constraints to a decoder _without_ changing the resulting type. The
370
+ * `test` argument is a predicate function which returns true for valid
371
+ * inputs. When `test` fails on an input, the decoder fails with the given
372
+ * `errorMessage`.
373
+ *
374
+ * ```
375
+ * const chars = (length: number): Decoder<string> =>
376
+ * string().where(
377
+ * (s: string) => s.length === length,
378
+ * `expected a string of length ${length}`
379
+ * );
380
+ *
381
+ * chars(5).run('12345')
382
+ * // => {ok: true, result: '12345'}
383
+ *
384
+ * chars(2).run('HELLO')
385
+ * // => {ok: false, error: {... message: 'expected a string of length 2'}}
386
+ *
387
+ * chars(12).run(true)
388
+ * // => {ok: false, error: {... message: 'expected a string, got a boolean'}}
389
+ * ```
390
+ */
391
+ this.where = function (test, errorMessage) {
392
+ return _this.andThen(function (value) { return (test(value) ? Decoder.succeed(value) : Decoder.fail(errorMessage)); });
393
+ };
394
+ }
395
+ /**
396
+ * Decoder primitive that validates strings, and fails on all other input.
397
+ */
398
+ Decoder.string = function () {
399
+ return new Decoder(function (json) {
400
+ return typeof json === 'string'
401
+ ? ok(json)
402
+ : err({ message: expectedGot('a string', json) });
403
+ });
404
+ };
405
+ /**
406
+ * Decoder primitive that validates numbers, and fails on all other input.
407
+ */
408
+ Decoder.number = function () {
409
+ return new Decoder(function (json) {
410
+ return typeof json === 'number'
411
+ ? ok(json)
412
+ : err({ message: expectedGot('a number', json) });
413
+ });
414
+ };
415
+ /**
416
+ * Decoder primitive that validates booleans, and fails on all other input.
417
+ */
418
+ Decoder.boolean = function () {
419
+ return new Decoder(function (json) {
420
+ return typeof json === 'boolean'
421
+ ? ok(json)
422
+ : err({ message: expectedGot('a boolean', json) });
423
+ });
424
+ };
425
+ Decoder.constant = function (value) {
426
+ return new Decoder(function (json) {
427
+ return isEqual(json, value)
428
+ ? ok(value)
429
+ : err({ message: "expected " + JSON.stringify(value) + ", got " + JSON.stringify(json) });
430
+ });
431
+ };
432
+ Decoder.object = function (decoders) {
433
+ return new Decoder(function (json) {
434
+ if (isJsonObject(json) && decoders) {
435
+ var obj = {};
436
+ for (var key in decoders) {
437
+ if (decoders.hasOwnProperty(key)) {
438
+ var r = decoders[key].decode(json[key]);
439
+ if (r.ok === true) {
440
+ // tslint:disable-next-line:strict-type-predicates
441
+ if (r.result !== undefined) {
442
+ obj[key] = r.result;
443
+ }
444
+ }
445
+ else if (json[key] === undefined) {
446
+ return err({ message: "the key '" + key + "' is required but was not present" });
447
+ }
448
+ else {
449
+ return err(prependAt("." + key, r.error));
450
+ }
451
+ }
452
+ }
453
+ return ok(obj);
454
+ }
455
+ else if (isJsonObject(json)) {
456
+ return ok(json);
457
+ }
458
+ else {
459
+ return err({ message: expectedGot('an object', json) });
460
+ }
461
+ });
462
+ };
463
+ Decoder.array = function (decoder) {
464
+ return new Decoder(function (json) {
465
+ if (isJsonArray(json) && decoder) {
466
+ var decodeValue_1 = function (v, i) {
467
+ return mapError(function (err$$1) { return prependAt("[" + i + "]", err$$1); }, decoder.decode(v));
468
+ };
469
+ return json.reduce(function (acc, v, i) {
470
+ return map2(function (arr, result) { return arr.concat([result]); }, acc, decodeValue_1(v, i));
471
+ }, ok([]));
472
+ }
473
+ else if (isJsonArray(json)) {
474
+ return ok(json);
475
+ }
476
+ else {
477
+ return err({ message: expectedGot('an array', json) });
478
+ }
479
+ });
480
+ };
481
+ Decoder.tuple = function (decoders) {
482
+ return new Decoder(function (json) {
483
+ if (isJsonArray(json)) {
484
+ if (json.length !== decoders.length) {
485
+ return err({
486
+ message: "expected a tuple of length " + decoders.length + ", got one of length " + json.length
487
+ });
488
+ }
489
+ var result = [];
490
+ for (var i = 0; i < decoders.length; i++) {
491
+ var nth = decoders[i].decode(json[i]);
492
+ if (nth.ok) {
493
+ result[i] = nth.result;
494
+ }
495
+ else {
496
+ return err(prependAt("[" + i + "]", nth.error));
497
+ }
498
+ }
499
+ return ok(result);
500
+ }
501
+ else {
502
+ return err({ message: expectedGot("a tuple of length " + decoders.length, json) });
503
+ }
504
+ });
505
+ };
506
+ Decoder.union = function (ad, bd) {
507
+ var decoders = [];
508
+ for (var _i = 2; _i < arguments.length; _i++) {
509
+ decoders[_i - 2] = arguments[_i];
510
+ }
511
+ return Decoder.oneOf.apply(Decoder, [ad, bd].concat(decoders));
512
+ };
513
+ Decoder.intersection = function (ad, bd) {
514
+ var ds = [];
515
+ for (var _i = 2; _i < arguments.length; _i++) {
516
+ ds[_i - 2] = arguments[_i];
517
+ }
518
+ return new Decoder(function (json) {
519
+ return [ad, bd].concat(ds).reduce(function (acc, decoder) { return map2(Object.assign, acc, decoder.decode(json)); }, ok({}));
520
+ });
521
+ };
522
+ /**
523
+ * Escape hatch to bypass validation. Always succeeds and types the result as
524
+ * `any`. Useful for defining decoders incrementally, particularly for
525
+ * complex objects.
526
+ *
527
+ * Example:
528
+ * ```
529
+ * interface User {
530
+ * name: string;
531
+ * complexUserData: ComplexType;
532
+ * }
533
+ *
534
+ * const userDecoder: Decoder<User> = object({
535
+ * name: string(),
536
+ * complexUserData: anyJson()
537
+ * });
538
+ * ```
539
+ */
540
+ Decoder.anyJson = function () { return new Decoder(function (json) { return ok(json); }); };
541
+ /**
542
+ * Decoder identity function which always succeeds and types the result as
543
+ * `unknown`.
544
+ */
545
+ Decoder.unknownJson = function () {
546
+ return new Decoder(function (json) { return ok(json); });
547
+ };
548
+ /**
549
+ * Decoder for json objects where the keys are unknown strings, but the values
550
+ * should all be of the same type.
551
+ *
552
+ * Example:
553
+ * ```
554
+ * dict(number()).run({chocolate: 12, vanilla: 10, mint: 37});
555
+ * // => {ok: true, result: {chocolate: 12, vanilla: 10, mint: 37}}
556
+ * ```
557
+ */
558
+ Decoder.dict = function (decoder) {
559
+ return new Decoder(function (json) {
560
+ if (isJsonObject(json)) {
561
+ var obj = {};
562
+ for (var key in json) {
563
+ if (json.hasOwnProperty(key)) {
564
+ var r = decoder.decode(json[key]);
565
+ if (r.ok === true) {
566
+ obj[key] = r.result;
567
+ }
568
+ else {
569
+ return err(prependAt("." + key, r.error));
570
+ }
571
+ }
572
+ }
573
+ return ok(obj);
574
+ }
575
+ else {
576
+ return err({ message: expectedGot('an object', json) });
577
+ }
578
+ });
579
+ };
580
+ /**
581
+ * Decoder for values that may be `undefined`. This is primarily helpful for
582
+ * decoding interfaces with optional fields.
583
+ *
584
+ * Example:
585
+ * ```
586
+ * interface User {
587
+ * id: number;
588
+ * isOwner?: boolean;
589
+ * }
590
+ *
591
+ * const decoder: Decoder<User> = object({
592
+ * id: number(),
593
+ * isOwner: optional(boolean())
594
+ * });
595
+ * ```
596
+ */
597
+ Decoder.optional = function (decoder) {
598
+ return new Decoder(function (json) { return (json === undefined || json === null ? ok(undefined) : decoder.decode(json)); });
599
+ };
600
+ /**
601
+ * Decoder that attempts to run each decoder in `decoders` and either succeeds
602
+ * with the first successful decoder, or fails after all decoders have failed.
603
+ *
604
+ * Note that `oneOf` expects the decoders to all have the same return type,
605
+ * while `union` creates a decoder for the union type of all the input
606
+ * decoders.
607
+ *
608
+ * Examples:
609
+ * ```
610
+ * oneOf(string(), number().map(String))
611
+ * oneOf(constant('start'), constant('stop'), succeed('unknown'))
612
+ * ```
613
+ */
614
+ Decoder.oneOf = function () {
615
+ var decoders = [];
616
+ for (var _i = 0; _i < arguments.length; _i++) {
617
+ decoders[_i] = arguments[_i];
618
+ }
619
+ return new Decoder(function (json) {
620
+ var errors = [];
621
+ for (var i = 0; i < decoders.length; i++) {
622
+ var r = decoders[i].decode(json);
623
+ if (r.ok === true) {
624
+ return r;
625
+ }
626
+ else {
627
+ errors[i] = r.error;
628
+ }
629
+ }
630
+ var errorsList = errors
631
+ .map(function (error) { return "at error" + (error.at || '') + ": " + error.message; })
632
+ .join('", "');
633
+ return err({
634
+ message: "expected a value matching one of the decoders, got the errors [\"" + errorsList + "\"]"
635
+ });
636
+ });
637
+ };
638
+ /**
639
+ * Decoder that always succeeds with either the decoded value, or a fallback
640
+ * default value.
641
+ */
642
+ Decoder.withDefault = function (defaultValue, decoder) {
643
+ return new Decoder(function (json) {
644
+ return ok(withDefault(defaultValue, decoder.decode(json)));
645
+ });
646
+ };
647
+ /**
648
+ * Decoder that pulls a specific field out of a json structure, instead of
649
+ * decoding and returning the full structure. The `paths` array describes the
650
+ * object keys and array indices to traverse, so that values can be pulled out
651
+ * of a nested structure.
652
+ *
653
+ * Example:
654
+ * ```
655
+ * const decoder = valueAt(['a', 'b', 0], string());
656
+ *
657
+ * decoder.run({a: {b: ['surprise!']}})
658
+ * // => {ok: true, result: 'surprise!'}
659
+ *
660
+ * decoder.run({a: {x: 'cats'}})
661
+ * // => {ok: false, error: {... at: 'input.a.b[0]' message: 'path does not exist'}}
662
+ * ```
663
+ *
664
+ * Note that the `decoder` is ran on the value found at the last key in the
665
+ * path, even if the last key is not found. This allows the `optional`
666
+ * decoder to succeed when appropriate.
667
+ * ```
668
+ * const optionalDecoder = valueAt(['a', 'b', 'c'], optional(string()));
669
+ *
670
+ * optionalDecoder.run({a: {b: {c: 'surprise!'}}})
671
+ * // => {ok: true, result: 'surprise!'}
672
+ *
673
+ * optionalDecoder.run({a: {b: 'cats'}})
674
+ * // => {ok: false, error: {... at: 'input.a.b.c' message: 'expected an object, got "cats"'}
675
+ *
676
+ * optionalDecoder.run({a: {b: {z: 1}}})
677
+ * // => {ok: true, result: undefined}
678
+ * ```
679
+ */
680
+ Decoder.valueAt = function (paths, decoder) {
681
+ return new Decoder(function (json) {
682
+ var jsonAtPath = json;
683
+ for (var i = 0; i < paths.length; i++) {
684
+ if (jsonAtPath === undefined) {
685
+ return err({
686
+ at: printPath(paths.slice(0, i + 1)),
687
+ message: 'path does not exist'
688
+ });
689
+ }
690
+ else if (typeof paths[i] === 'string' && !isJsonObject(jsonAtPath)) {
691
+ return err({
692
+ at: printPath(paths.slice(0, i + 1)),
693
+ message: expectedGot('an object', jsonAtPath)
694
+ });
695
+ }
696
+ else if (typeof paths[i] === 'number' && !isJsonArray(jsonAtPath)) {
697
+ return err({
698
+ at: printPath(paths.slice(0, i + 1)),
699
+ message: expectedGot('an array', jsonAtPath)
700
+ });
701
+ }
702
+ else {
703
+ jsonAtPath = jsonAtPath[paths[i]];
704
+ }
705
+ }
706
+ return mapError(function (error) {
707
+ return jsonAtPath === undefined
708
+ ? { at: printPath(paths), message: 'path does not exist' }
709
+ : prependAt(printPath(paths), error);
710
+ }, decoder.decode(jsonAtPath));
711
+ });
712
+ };
713
+ /**
714
+ * Decoder that ignores the input json and always succeeds with `fixedValue`.
715
+ */
716
+ Decoder.succeed = function (fixedValue) {
717
+ return new Decoder(function (json) { return ok(fixedValue); });
718
+ };
719
+ /**
720
+ * Decoder that ignores the input json and always fails with `errorMessage`.
721
+ */
722
+ Decoder.fail = function (errorMessage) {
723
+ return new Decoder(function (json) { return err({ message: errorMessage }); });
724
+ };
725
+ /**
726
+ * Decoder that allows for validating recursive data structures. Unlike with
727
+ * functions, decoders assigned to variables can't reference themselves
728
+ * before they are fully defined. We can avoid prematurely referencing the
729
+ * decoder by wrapping it in a function that won't be called until use, at
730
+ * which point the decoder has been defined.
731
+ *
732
+ * Example:
733
+ * ```
734
+ * interface Comment {
735
+ * msg: string;
736
+ * replies: Comment[];
737
+ * }
738
+ *
739
+ * const decoder: Decoder<Comment> = object({
740
+ * msg: string(),
741
+ * replies: lazy(() => array(decoder))
742
+ * });
743
+ * ```
744
+ */
745
+ Decoder.lazy = function (mkDecoder) {
746
+ return new Decoder(function (json) { return mkDecoder().decode(json); });
747
+ };
748
+ return Decoder;
749
+ }());
750
+
751
+ /* tslint:disable:variable-name */
752
+ /** See `Decoder.string` */
753
+ var string = Decoder.string;
754
+ /** See `Decoder.number` */
755
+ Decoder.number;
756
+ /** See `Decoder.boolean` */
757
+ var boolean = Decoder.boolean;
758
+ /** See `Decoder.anyJson` */
759
+ var anyJson = Decoder.anyJson;
760
+ /** See `Decoder.unknownJson` */
761
+ Decoder.unknownJson;
762
+ /** See `Decoder.constant` */
763
+ var constant = Decoder.constant;
764
+ /** See `Decoder.object` */
765
+ var object = Decoder.object;
766
+ /** See `Decoder.array` */
767
+ Decoder.array;
768
+ /** See `Decoder.tuple` */
769
+ Decoder.tuple;
770
+ /** See `Decoder.dict` */
771
+ Decoder.dict;
772
+ /** See `Decoder.optional` */
773
+ var optional = Decoder.optional;
774
+ /** See `Decoder.oneOf` */
775
+ var oneOf = Decoder.oneOf;
776
+ /** See `Decoder.union` */
777
+ Decoder.union;
778
+ /** See `Decoder.intersection` */
779
+ Decoder.intersection;
780
+ /** See `Decoder.withDefault` */
781
+ Decoder.withDefault;
782
+ /** See `Decoder.valueAt` */
783
+ Decoder.valueAt;
784
+ /** See `Decoder.succeed` */
785
+ Decoder.succeed;
786
+ /** See `Decoder.fail` */
787
+ Decoder.fail;
788
+ /** See `Decoder.lazy` */
789
+ Decoder.lazy;
790
+
791
+ const nonEmptyStringDecoder = string().where((s) => s.length > 0, "Expected a non-empty string");
792
+ const operationCheckConfigDecoder = object({
793
+ operation: nonEmptyStringDecoder
794
+ });
795
+ const operationCheckResultDecoder = object({
796
+ isSupported: boolean()
797
+ });
798
+ const simpleWindowDecoder = object({
799
+ windowId: nonEmptyStringDecoder
800
+ });
801
+ const iframesOperationTypesDecoder = oneOf(constant("operationCheck"), constant("reserveStandaloneIFrameApp"), constant("registerStandaloneIFrameApp"), constant("unregisterStandaloneIFrameApp"), constant("closeRequested"));
802
+ const iframesOpenAppConfigDecoder = object({
803
+ appName: nonEmptyStringDecoder,
804
+ channelId: optional(nonEmptyStringDecoder),
805
+ context: optional(anyJson()),
806
+ waitForAGMReady: optional(boolean())
807
+ });
808
+ const reserveStandaloneIFrameAppDataDecoder = object({
809
+ appName: nonEmptyStringDecoder,
810
+ waitForAGMReady: boolean()
811
+ });
812
+ const reserveStandaloneIFrameAppResultDecoder = object({
813
+ instanceId: nonEmptyStringDecoder,
814
+ url: nonEmptyStringDecoder
815
+ });
816
+ const registerStandaloneIFrameAppDataDecoder = object({
817
+ channelId: optional(nonEmptyStringDecoder),
818
+ context: optional(anyJson()),
819
+ instanceId: nonEmptyStringDecoder,
820
+ name: nonEmptyStringDecoder,
821
+ parentId: nonEmptyStringDecoder
822
+ });
823
+
824
+ class Bridge {
825
+ io;
826
+ constructor(io) {
827
+ this.io = io;
828
+ }
829
+ getMyInstanceId() {
830
+ return this.io.interop.instance.instance;
831
+ }
832
+ async initiate(handleControlMessage) {
833
+ await this.io.interop.registerAsync(GlueIFramesControlName, (args, _, success, error) => {
834
+ handleControlMessage(args)
835
+ .then((result) => success(result))
836
+ .catch((reason) => error(reason));
837
+ });
838
+ }
839
+ async send(operation, operationData, options, webOptions) {
840
+ if (operation.dataDecoder) {
841
+ try {
842
+ operation.dataDecoder.runWithException(operationData);
843
+ }
844
+ catch (error) {
845
+ throw new Error(`Unexpected Web->Platform outgoing validation error: ${error.message}, for operation: ${operation.name} and input: ${JSON.stringify(error.input)}`);
846
+ }
847
+ }
848
+ const operationSupported = webOptions?.includeOperationCheck ?
849
+ (await this.checkOperationSupported(operation)).isSupported :
850
+ true;
851
+ if (!operationSupported) {
852
+ throw new Error(`Cannot complete operation: ${operation.name} because this client is connected to a platform which does not support it`);
853
+ }
854
+ const operationResult = await this.transmitMessage(operation, operationData, options);
855
+ if (operation.resultDecoder) {
856
+ try {
857
+ operation.resultDecoder.runWithException(operationResult);
858
+ }
859
+ catch (error) {
860
+ throw new Error(`Unexpected Web<-Platform incoming validation error: ${error.message}, for operation: ${operation.name} and input: ${JSON.stringify(error.input)}`);
861
+ }
862
+ }
863
+ return operationResult;
864
+ }
865
+ async checkOperationSupported(operation) {
866
+ try {
867
+ const result = await this.send({
868
+ name: "operationCheck",
869
+ dataDecoder: operationCheckConfigDecoder,
870
+ resultDecoder: operationCheckResultDecoder
871
+ }, { operation: operation.name });
872
+ return result;
873
+ }
874
+ catch {
875
+ return { isSupported: false };
876
+ }
877
+ }
878
+ async transmitMessage(operation, data, options) {
879
+ const browserGlobal = window.glue42core || window.iobrowser;
880
+ const platformTarget = browserGlobal.communicationId;
881
+ const messageData = { domain: "iframes", data, operation: operation.name };
882
+ let invocationResult;
883
+ const baseErrorMessage = `Internal Platform Communication Error. Attempted operation: ${JSON.stringify(operation.name)} with data: ${JSON.stringify(data)}. `;
884
+ try {
885
+ invocationResult = await this.io.interop.invoke(BrowserPlatformControlName, messageData, platformTarget ? { instance: platformTarget } : undefined, options);
886
+ if (!invocationResult) {
887
+ throw new Error("Received unsupported result from the platform - empty result");
888
+ }
889
+ if (!Array.isArray(invocationResult.all_return_values) || invocationResult.all_return_values.length === 0) {
890
+ throw new Error("Received unsupported result from the platform - empty values collection");
891
+ }
892
+ }
893
+ catch (error) {
894
+ if (error?.all_errors?.length) {
895
+ const invocationErrorMessage = error.all_errors[0].message;
896
+ throw new Error(`${baseErrorMessage} -> Inner message: ${invocationErrorMessage}`);
897
+ }
898
+ throw new Error(`${baseErrorMessage} -> Inner message: ${error.message}`);
899
+ }
900
+ return invocationResult.all_return_values[0].returned;
901
+ }
902
+ }
903
+
904
+ function getDefaultExportFromCjs (x) {
905
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
906
+ }
907
+
908
+ function createRegistry(options) {
909
+ if (options && options.errorHandling
910
+ && typeof options.errorHandling !== "function"
911
+ && options.errorHandling !== "log"
912
+ && options.errorHandling !== "silent"
913
+ && options.errorHandling !== "throw") {
914
+ throw new Error("Invalid options passed to createRegistry. Prop errorHandling should be [\"log\" | \"silent\" | \"throw\" | (err) => void], but " + typeof options.errorHandling + " was passed");
915
+ }
916
+ var _userErrorHandler = options && typeof options.errorHandling === "function" && options.errorHandling;
917
+ var callbacks = {};
918
+ function add(key, callback, replayArgumentsArr) {
919
+ var callbacksForKey = callbacks[key];
920
+ if (!callbacksForKey) {
921
+ callbacksForKey = [];
922
+ callbacks[key] = callbacksForKey;
923
+ }
924
+ callbacksForKey.push(callback);
925
+ if (replayArgumentsArr) {
926
+ setTimeout(function () {
927
+ replayArgumentsArr.forEach(function (replayArgument) {
928
+ var _a;
929
+ if ((_a = callbacks[key]) === null || _a === void 0 ? void 0 : _a.includes(callback)) {
930
+ try {
931
+ if (Array.isArray(replayArgument)) {
932
+ callback.apply(undefined, replayArgument);
933
+ }
934
+ else {
935
+ callback.apply(undefined, [replayArgument]);
936
+ }
937
+ }
938
+ catch (err) {
939
+ _handleError(err, key);
940
+ }
941
+ }
942
+ });
943
+ }, 0);
944
+ }
945
+ return function () {
946
+ var allForKey = callbacks[key];
947
+ if (!allForKey) {
948
+ return;
949
+ }
950
+ allForKey = allForKey.reduce(function (acc, element, index) {
951
+ if (!(element === callback && acc.length === index)) {
952
+ acc.push(element);
953
+ }
954
+ return acc;
955
+ }, []);
956
+ if (allForKey.length === 0) {
957
+ delete callbacks[key];
958
+ }
959
+ else {
960
+ callbacks[key] = allForKey;
961
+ }
962
+ };
963
+ }
964
+ function execute(key) {
965
+ var argumentsArr = [];
966
+ for (var _i = 1; _i < arguments.length; _i++) {
967
+ argumentsArr[_i - 1] = arguments[_i];
968
+ }
969
+ var callbacksForKey = callbacks[key];
970
+ if (!callbacksForKey || callbacksForKey.length === 0) {
971
+ return [];
972
+ }
973
+ var results = [];
974
+ callbacksForKey.forEach(function (callback) {
975
+ try {
976
+ var result = callback.apply(undefined, argumentsArr);
977
+ results.push(result);
978
+ }
979
+ catch (err) {
980
+ results.push(undefined);
981
+ _handleError(err, key);
982
+ }
983
+ });
984
+ return results;
985
+ }
986
+ function _handleError(exceptionArtifact, key) {
987
+ var errParam = exceptionArtifact instanceof Error ? exceptionArtifact : new Error(exceptionArtifact);
988
+ if (_userErrorHandler) {
989
+ _userErrorHandler(errParam);
990
+ return;
991
+ }
992
+ var msg = "[ERROR] callback-registry: User callback for key \"" + key + "\" failed: " + errParam.stack;
993
+ if (options) {
994
+ switch (options.errorHandling) {
995
+ case "log":
996
+ return console.error(msg);
997
+ case "silent":
998
+ return;
999
+ case "throw":
1000
+ throw new Error(msg);
1001
+ }
1002
+ }
1003
+ console.error(msg);
1004
+ }
1005
+ function clear() {
1006
+ callbacks = {};
1007
+ }
1008
+ function clearKey(key) {
1009
+ var callbacksForKey = callbacks[key];
1010
+ if (!callbacksForKey) {
1011
+ return;
1012
+ }
1013
+ delete callbacks[key];
1014
+ }
1015
+ return {
1016
+ add: add,
1017
+ execute: execute,
1018
+ clear: clear,
1019
+ clearKey: clearKey
1020
+ };
1021
+ }
1022
+ createRegistry.default = createRegistry;
1023
+ var lib = createRegistry;
1024
+
1025
+
1026
+ var CallbackRegistryFactory = /*@__PURE__*/getDefaultExportFromCjs(lib);
1027
+
1028
+ const getSupportedOperationsNames = (operations) => {
1029
+ return Object.keys(operations).filter((operation) => operations[operation].execute);
1030
+ };
1031
+ const handleOperationCheck = (supportedOperations, operationName) => {
1032
+ const isSupported = supportedOperations.some((operation) => operation.toLowerCase() === operationName.toLowerCase());
1033
+ return { isSupported };
1034
+ };
1035
+ const wrapPromise = () => {
1036
+ let wrapperResolve;
1037
+ let wrapperReject;
1038
+ const promise = new Promise((resolve, reject) => {
1039
+ wrapperResolve = resolve;
1040
+ wrapperReject = reject;
1041
+ });
1042
+ return { promise, resolve: wrapperResolve, reject: wrapperReject };
1043
+ };
1044
+ const PromiseWrap = (callback, timeoutMilliseconds, timeoutMessage) => {
1045
+ return new Promise((resolve, reject) => {
1046
+ let promiseActive = true;
1047
+ const timeout = setTimeout(() => {
1048
+ if (!promiseActive) {
1049
+ return;
1050
+ }
1051
+ promiseActive = false;
1052
+ const message = `Promise timeout hit: ${timeoutMilliseconds}`;
1053
+ reject(message);
1054
+ }, timeoutMilliseconds);
1055
+ callback()
1056
+ .then((result) => {
1057
+ if (!promiseActive) {
1058
+ return;
1059
+ }
1060
+ promiseActive = false;
1061
+ clearTimeout(timeout);
1062
+ resolve(result);
1063
+ })
1064
+ .catch((error) => {
1065
+ if (!promiseActive) {
1066
+ return;
1067
+ }
1068
+ promiseActive = false;
1069
+ clearTimeout(timeout);
1070
+ reject(error);
1071
+ });
1072
+ });
1073
+ };
1074
+
1075
+ const operations = {
1076
+ operationCheck: { name: "operationCheck", dataDecoder: operationCheckConfigDecoder, resultDecoder: operationCheckResultDecoder },
1077
+ reserveStandaloneIFrameApp: { name: "reserveStandaloneIFrameApp", dataDecoder: reserveStandaloneIFrameAppDataDecoder, resultDecoder: reserveStandaloneIFrameAppResultDecoder },
1078
+ registerStandaloneIFrameApp: { name: "registerStandaloneIFrameApp", dataDecoder: registerStandaloneIFrameAppDataDecoder },
1079
+ unregisterStandaloneIFrameApp: { name: "unregisterStandaloneIFrameApp", dataDecoder: simpleWindowDecoder },
1080
+ closeRequested: { name: "closeRequested", dataDecoder: simpleWindowDecoder }
1081
+ };
1082
+
1083
+ class IFramesController {
1084
+ bridge;
1085
+ registry = CallbackRegistryFactory();
1086
+ instances = new Map();
1087
+ pendingCloseResolvers = new Map();
1088
+ supportedOperationsNames = [];
1089
+ confirmFrameClosedTimeoutMs = 15000;
1090
+ constructor(bridge) {
1091
+ this.bridge = bridge;
1092
+ this.addOperationsExecutors();
1093
+ }
1094
+ exposeApi(version) {
1095
+ const api = {
1096
+ openApp: this.openApp.bind(this),
1097
+ onCloseRequested: this.onCloseRequested.bind(this),
1098
+ confirmFrameClosed: this.confirmFrameClosed.bind(this),
1099
+ version,
1100
+ };
1101
+ return Object.freeze(api);
1102
+ }
1103
+ async handleControlMessage(args) {
1104
+ const operationName = iframesOperationTypesDecoder.runWithException(args.operation);
1105
+ const operation = operations[operationName];
1106
+ if (!operation.execute) {
1107
+ return;
1108
+ }
1109
+ let operationData = args.data;
1110
+ if (operation.dataDecoder) {
1111
+ operationData = operation.dataDecoder.runWithException(args.data);
1112
+ }
1113
+ return operation.execute(operationData);
1114
+ }
1115
+ addOperationsExecutors() {
1116
+ operations.operationCheck.execute = async (config) => handleOperationCheck(this.supportedOperationsNames, config.operation);
1117
+ operations.closeRequested.execute = this.handleCloseRequested.bind(this);
1118
+ this.supportedOperationsNames = getSupportedOperationsNames(operations);
1119
+ }
1120
+ async openApp(config) {
1121
+ const { appName, channelId, context, waitForAGMReady = true } = iframesOpenAppConfigDecoder.runWithException(config);
1122
+ const { instanceId, url } = await this.reserveStandaloneIFrameApp({ appName, waitForAGMReady });
1123
+ const parentId = this.bridge.getMyInstanceId();
1124
+ const iframe = this.generateIframeElement(url, instanceId);
1125
+ document.body.appendChild(iframe);
1126
+ try {
1127
+ await this.registerStandaloneIFrameApp({
1128
+ channelId,
1129
+ context,
1130
+ instanceId,
1131
+ name: `${appName}_${instanceId}`,
1132
+ parentId
1133
+ });
1134
+ }
1135
+ catch (error) {
1136
+ iframe.remove();
1137
+ throw error;
1138
+ }
1139
+ const instance = Object.freeze({
1140
+ appName,
1141
+ id: instanceId,
1142
+ iframe,
1143
+ parentId
1144
+ });
1145
+ this.instances.set(instanceId, instance);
1146
+ return instance;
1147
+ }
1148
+ generateIframeElement(url, instanceId) {
1149
+ const iframe = document.createElement("iframe");
1150
+ iframe.name = `${instanceId}#wsp`;
1151
+ iframe.id = instanceId;
1152
+ iframe.src = url;
1153
+ iframe.style.position = "absolute";
1154
+ iframe.style.top = "30000px";
1155
+ iframe.style.left = "30000px";
1156
+ iframe.style.width = "0px";
1157
+ iframe.style.height = "0px";
1158
+ return iframe;
1159
+ }
1160
+ async reserveStandaloneIFrameApp(data) {
1161
+ return this.bridge.send(operations.reserveStandaloneIFrameApp, data, undefined, { includeOperationCheck: true });
1162
+ }
1163
+ async registerStandaloneIFrameApp(data) {
1164
+ await this.bridge.send(operations.registerStandaloneIFrameApp, data, undefined, { includeOperationCheck: true });
1165
+ }
1166
+ async handleCloseRequested({ windowId }) {
1167
+ const instance = this.instances.get(windowId);
1168
+ if (!instance) {
1169
+ throw new Error(`Cannot handle close request for iframe ${windowId}, because no local instance was found`);
1170
+ }
1171
+ const { promise, resolve } = wrapPromise();
1172
+ this.pendingCloseResolvers.set(windowId, resolve);
1173
+ this.registry.execute("on-close-requested", instance);
1174
+ try {
1175
+ await PromiseWrap(() => promise, this.confirmFrameClosedTimeoutMs);
1176
+ }
1177
+ catch {
1178
+ this.pendingCloseResolvers.delete(windowId);
1179
+ throw new Error(`IFrame close for ${windowId} timed out waiting for client to be closed`);
1180
+ }
1181
+ }
1182
+ onCloseRequested(callback) {
1183
+ return this.registry.add("on-close-requested", callback);
1184
+ }
1185
+ async confirmFrameClosed(id) {
1186
+ const resolve = this.pendingCloseResolvers.get(id);
1187
+ const instance = this.instances.get(id);
1188
+ if (!instance) {
1189
+ this.pendingCloseResolvers.delete(id);
1190
+ resolve?.();
1191
+ return;
1192
+ }
1193
+ instance.iframe.remove();
1194
+ await this.bridge.send(operations.unregisterStandaloneIFrameApp, { windowId: id }, undefined, { includeOperationCheck: true });
1195
+ this.instances.delete(id);
1196
+ this.pendingCloseResolvers.delete(id);
1197
+ resolve?.();
1198
+ }
1199
+ }
1200
+
1201
+ class IoC {
1202
+ io;
1203
+ _bridge;
1204
+ _iframesController;
1205
+ constructor(io) {
1206
+ this.io = io;
1207
+ }
1208
+ get bridge() {
1209
+ if (!this._bridge) {
1210
+ this._bridge = new Bridge(this.io);
1211
+ }
1212
+ return this._bridge;
1213
+ }
1214
+ get iframesController() {
1215
+ if (!this._iframesController) {
1216
+ this._iframesController = new IFramesController(this.bridge);
1217
+ }
1218
+ return this._iframesController;
1219
+ }
1220
+ }
1221
+
1222
+ var version = "0.1.0-beta.0";
1223
+
1224
+ const factoryFunction = async (io) => {
1225
+ const ioc = new IoC(io);
1226
+ await ioc.bridge.initiate(ioc.iframesController.handleControlMessage.bind(ioc.iframesController));
1227
+ io.iframes = ioc.iframesController.exposeApi(version);
1228
+ };
1229
+
1230
+ if (typeof window !== "undefined") {
1231
+ window.IOIFrames = factoryFunction;
1232
+ }
1233
+
1234
+ return factoryFunction;
1235
+
1236
+ }));
1237
+ //# sourceMappingURL=iframes.umd.js.map