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