@interopio/browser-worker 3.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1403 @@
1
+ /*! *****************************************************************************
2
+ Copyright (c) Microsoft Corporation.
3
+
4
+ Permission to use, copy, modify, and/or distribute this software for any
5
+ purpose with or without fee is hereby granted.
6
+
7
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
8
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
9
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
10
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
11
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
12
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
13
+ PERFORMANCE OF THIS SOFTWARE.
14
+ ***************************************************************************** */
15
+
16
+ function __awaiter(thisArg, _arguments, P, generator) {
17
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
18
+ return new (P || (P = Promise))(function (resolve, reject) {
19
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
20
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
21
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
22
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
23
+ });
24
+ }
25
+
26
+ function __generator(thisArg, body) {
27
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
28
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
29
+ function verb(n) { return function (v) { return step([n, v]); }; }
30
+ function step(op) {
31
+ if (f) throw new TypeError("Generator is already executing.");
32
+ while (_) try {
33
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
34
+ if (y = 0, t) op = [op[0] & 2, t.value];
35
+ switch (op[0]) {
36
+ case 0: case 1: t = op; break;
37
+ case 4: _.label++; return { value: op[1], done: false };
38
+ case 5: _.label++; y = op[1]; op = [0]; continue;
39
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
40
+ default:
41
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
42
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
43
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
44
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
45
+ if (t[2]) _.ops.pop();
46
+ _.trys.pop(); continue;
47
+ }
48
+ op = body.call(thisArg, _);
49
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
50
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
51
+ }
52
+ }
53
+
54
+ var serviceWorkerBroadcastChannelName = "glue42-core-worker";
55
+ var platformPingTimeoutMS = 3000;
56
+ var platformOpenTimeoutMS = 60000;
57
+ var dbName = "glue42core";
58
+ var dbVersion = 2;
59
+
60
+ /**
61
+ * Wraps values in an `Ok` type.
62
+ *
63
+ * Example: `ok(5) // => {ok: true, result: 5}`
64
+ */
65
+ var ok = function (result) { return ({ ok: true, result: result }); };
66
+ /**
67
+ * Wraps errors in an `Err` type.
68
+ *
69
+ * Example: `err('on fire') // => {ok: false, error: 'on fire'}`
70
+ */
71
+ var err = function (error) { return ({ ok: false, error: error }); };
72
+ /**
73
+ * Create a `Promise` that either resolves with the result of `Ok` or rejects
74
+ * with the error of `Err`.
75
+ */
76
+ var asPromise = function (r) {
77
+ return r.ok === true ? Promise.resolve(r.result) : Promise.reject(r.error);
78
+ };
79
+ /**
80
+ * Unwraps a `Result` and returns either the result of an `Ok`, or
81
+ * `defaultValue`.
82
+ *
83
+ * Example:
84
+ * ```
85
+ * Result.withDefault(5, number().run(json))
86
+ * ```
87
+ *
88
+ * It would be nice if `Decoder` had an instance method that mirrored this
89
+ * function. Such a method would look something like this:
90
+ * ```
91
+ * class Decoder<A> {
92
+ * runWithDefault = (defaultValue: A, json: any): A =>
93
+ * Result.withDefault(defaultValue, this.run(json));
94
+ * }
95
+ *
96
+ * number().runWithDefault(5, json)
97
+ * ```
98
+ * Unfortunately, the type of `defaultValue: A` on the method causes issues
99
+ * with type inference on the `object` decoder in some situations. While these
100
+ * inference issues can be solved by providing the optional type argument for
101
+ * `object`s, the extra trouble and confusion doesn't seem worth it.
102
+ */
103
+ var withDefault = function (defaultValue, r) {
104
+ return r.ok === true ? r.result : defaultValue;
105
+ };
106
+ /**
107
+ * Return the successful result, or throw an error.
108
+ */
109
+ var withException = function (r) {
110
+ if (r.ok === true) {
111
+ return r.result;
112
+ }
113
+ else {
114
+ throw r.error;
115
+ }
116
+ };
117
+ /**
118
+ * Apply `f` to the result of an `Ok`, or pass the error through.
119
+ */
120
+ var map = function (f, r) {
121
+ return r.ok === true ? ok(f(r.result)) : r;
122
+ };
123
+ /**
124
+ * Apply `f` to the result of two `Ok`s, or pass an error through. If both
125
+ * `Result`s are errors then the first one is returned.
126
+ */
127
+ var map2 = function (f, ar, br) {
128
+ return ar.ok === false ? ar :
129
+ br.ok === false ? br :
130
+ ok(f(ar.result, br.result));
131
+ };
132
+ /**
133
+ * Apply `f` to the error of an `Err`, or pass the success through.
134
+ */
135
+ var mapError = function (f, r) {
136
+ return r.ok === true ? r : err(f(r.error));
137
+ };
138
+ /**
139
+ * Chain together a sequence of computations that may fail, similar to a
140
+ * `Promise`. If the first computation fails then the error will propagate
141
+ * through. If it succeeds, then `f` will be applied to the value, returning a
142
+ * new `Result`.
143
+ */
144
+ var andThen = function (f, r) {
145
+ return r.ok === true ? f(r.result) : r;
146
+ };
147
+
148
+ /*! *****************************************************************************
149
+ Copyright (c) Microsoft Corporation.
150
+
151
+ Permission to use, copy, modify, and/or distribute this software for any
152
+ purpose with or without fee is hereby granted.
153
+
154
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
155
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
156
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
157
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
158
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
159
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
160
+ PERFORMANCE OF THIS SOFTWARE.
161
+ ***************************************************************************** */
162
+ /* global Reflect, Promise */
163
+
164
+
165
+
166
+ var __assign = function() {
167
+ __assign = Object.assign || function __assign(t) {
168
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
169
+ s = arguments[i];
170
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
171
+ }
172
+ return t;
173
+ };
174
+ return __assign.apply(this, arguments);
175
+ };
176
+
177
+ function __rest(s, e) {
178
+ var t = {};
179
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
180
+ t[p] = s[p];
181
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
182
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
183
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
184
+ t[p[i]] = s[p[i]];
185
+ }
186
+ return t;
187
+ }
188
+
189
+ function isEqual(a, b) {
190
+ if (a === b) {
191
+ return true;
192
+ }
193
+ if (a === null && b === null) {
194
+ return true;
195
+ }
196
+ if (typeof (a) !== typeof (b)) {
197
+ return false;
198
+ }
199
+ if (typeof (a) === 'object') {
200
+ // Array
201
+ if (Array.isArray(a)) {
202
+ if (!Array.isArray(b)) {
203
+ return false;
204
+ }
205
+ if (a.length !== b.length) {
206
+ return false;
207
+ }
208
+ for (var i = 0; i < a.length; i++) {
209
+ if (!isEqual(a[i], b[i])) {
210
+ return false;
211
+ }
212
+ }
213
+ return true;
214
+ }
215
+ // Hash table
216
+ var keys = Object.keys(a);
217
+ if (keys.length !== Object.keys(b).length) {
218
+ return false;
219
+ }
220
+ for (var i = 0; i < keys.length; i++) {
221
+ if (!b.hasOwnProperty(keys[i])) {
222
+ return false;
223
+ }
224
+ if (!isEqual(a[keys[i]], b[keys[i]])) {
225
+ return false;
226
+ }
227
+ }
228
+ return true;
229
+ }
230
+ }
231
+ /*
232
+ * Helpers
233
+ */
234
+ var isJsonArray = function (json) { return Array.isArray(json); };
235
+ var isJsonObject = function (json) {
236
+ return typeof json === 'object' && json !== null && !isJsonArray(json);
237
+ };
238
+ var typeString = function (json) {
239
+ switch (typeof json) {
240
+ case 'string':
241
+ return 'a string';
242
+ case 'number':
243
+ return 'a number';
244
+ case 'boolean':
245
+ return 'a boolean';
246
+ case 'undefined':
247
+ return 'undefined';
248
+ case 'object':
249
+ if (json instanceof Array) {
250
+ return 'an array';
251
+ }
252
+ else if (json === null) {
253
+ return 'null';
254
+ }
255
+ else {
256
+ return 'an object';
257
+ }
258
+ default:
259
+ return JSON.stringify(json);
260
+ }
261
+ };
262
+ var expectedGot = function (expected, got) {
263
+ return "expected " + expected + ", got " + typeString(got);
264
+ };
265
+ var printPath = function (paths) {
266
+ return paths.map(function (path) { return (typeof path === 'string' ? "." + path : "[" + path + "]"); }).join('');
267
+ };
268
+ var prependAt = function (newAt, _a) {
269
+ var at = _a.at, rest = __rest(_a, ["at"]);
270
+ return (__assign({ at: newAt + (at || '') }, rest));
271
+ };
272
+ /**
273
+ * Decoders transform json objects with unknown structure into known and
274
+ * verified forms. You can create objects of type `Decoder<A>` with either the
275
+ * primitive decoder functions, such as `boolean()` and `string()`, or by
276
+ * applying higher-order decoders to the primitives, such as `array(boolean())`
277
+ * or `dict(string())`.
278
+ *
279
+ * Each of the decoder functions are available both as a static method on
280
+ * `Decoder` and as a function alias -- for example the string decoder is
281
+ * defined at `Decoder.string()`, but is also aliased to `string()`. Using the
282
+ * function aliases exported with the library is recommended.
283
+ *
284
+ * `Decoder` exposes a number of 'run' methods, which all decode json in the
285
+ * same way, but communicate success and failure in different ways. The `map`
286
+ * and `andThen` methods modify decoders without having to call a 'run' method.
287
+ *
288
+ * Alternatively, the main decoder `run()` method returns an object of type
289
+ * `Result<A, DecoderError>`. This library provides a number of helper
290
+ * functions for dealing with the `Result` type, so you can do all the same
291
+ * things with a `Result` as with the decoder methods.
292
+ */
293
+ var Decoder = /** @class */ (function () {
294
+ /**
295
+ * The Decoder class constructor is kept private to separate the internal
296
+ * `decode` function from the external `run` function. The distinction
297
+ * between the two functions is that `decode` returns a
298
+ * `Partial<DecoderError>` on failure, which contains an unfinished error
299
+ * report. When `run` is called on a decoder, the relevant series of `decode`
300
+ * calls is made, and then on failure the resulting `Partial<DecoderError>`
301
+ * is turned into a `DecoderError` by filling in the missing information.
302
+ *
303
+ * While hiding the constructor may seem restrictive, leveraging the
304
+ * provided decoder combinators and helper functions such as
305
+ * `andThen` and `map` should be enough to build specialized decoders as
306
+ * needed.
307
+ */
308
+ function Decoder(decode) {
309
+ var _this = this;
310
+ this.decode = decode;
311
+ /**
312
+ * Run the decoder and return a `Result` with either the decoded value or a
313
+ * `DecoderError` containing the json input, the location of the error, and
314
+ * the error message.
315
+ *
316
+ * Examples:
317
+ * ```
318
+ * number().run(12)
319
+ * // => {ok: true, result: 12}
320
+ *
321
+ * string().run(9001)
322
+ * // =>
323
+ * // {
324
+ * // ok: false,
325
+ * // error: {
326
+ * // kind: 'DecoderError',
327
+ * // input: 9001,
328
+ * // at: 'input',
329
+ * // message: 'expected a string, got 9001'
330
+ * // }
331
+ * // }
332
+ * ```
333
+ */
334
+ this.run = function (json) {
335
+ return mapError(function (error) { return ({
336
+ kind: 'DecoderError',
337
+ input: json,
338
+ at: 'input' + (error.at || ''),
339
+ message: error.message || ''
340
+ }); }, _this.decode(json));
341
+ };
342
+ /**
343
+ * Run the decoder as a `Promise`.
344
+ */
345
+ this.runPromise = function (json) { return asPromise(_this.run(json)); };
346
+ /**
347
+ * Run the decoder and return the value on success, or throw an exception
348
+ * with a formatted error string.
349
+ */
350
+ this.runWithException = function (json) { return withException(_this.run(json)); };
351
+ /**
352
+ * Construct a new decoder that applies a transformation to the decoded
353
+ * result. If the decoder succeeds then `f` will be applied to the value. If
354
+ * it fails the error will propagated through.
355
+ *
356
+ * Example:
357
+ * ```
358
+ * number().map(x => x * 5).run(10)
359
+ * // => {ok: true, result: 50}
360
+ * ```
361
+ */
362
+ this.map = function (f) {
363
+ return new Decoder(function (json) { return map(f, _this.decode(json)); });
364
+ };
365
+ /**
366
+ * Chain together a sequence of decoders. The first decoder will run, and
367
+ * then the function will determine what decoder to run second. If the result
368
+ * of the first decoder succeeds then `f` will be applied to the decoded
369
+ * value. If it fails the error will propagate through.
370
+ *
371
+ * This is a very powerful method -- it can act as both the `map` and `where`
372
+ * methods, can improve error messages for edge cases, and can be used to
373
+ * make a decoder for custom types.
374
+ *
375
+ * Example of adding an error message:
376
+ * ```
377
+ * const versionDecoder = valueAt(['version'], number());
378
+ * const infoDecoder3 = object({a: boolean()});
379
+ *
380
+ * const decoder = versionDecoder.andThen(version => {
381
+ * switch (version) {
382
+ * case 3:
383
+ * return infoDecoder3;
384
+ * default:
385
+ * return fail(`Unable to decode info, version ${version} is not supported.`);
386
+ * }
387
+ * });
388
+ *
389
+ * decoder.run({version: 3, a: true})
390
+ * // => {ok: true, result: {a: true}}
391
+ *
392
+ * decoder.run({version: 5, x: 'abc'})
393
+ * // =>
394
+ * // {
395
+ * // ok: false,
396
+ * // error: {... message: 'Unable to decode info, version 5 is not supported.'}
397
+ * // }
398
+ * ```
399
+ *
400
+ * Example of decoding a custom type:
401
+ * ```
402
+ * // nominal type for arrays with a length of at least one
403
+ * type NonEmptyArray<T> = T[] & { __nonEmptyArrayBrand__: void };
404
+ *
405
+ * const nonEmptyArrayDecoder = <T>(values: Decoder<T>): Decoder<NonEmptyArray<T>> =>
406
+ * array(values).andThen(arr =>
407
+ * arr.length > 0
408
+ * ? succeed(createNonEmptyArray(arr))
409
+ * : fail(`expected a non-empty array, got an empty array`)
410
+ * );
411
+ * ```
412
+ */
413
+ this.andThen = function (f) {
414
+ return new Decoder(function (json) {
415
+ return andThen(function (value) { return f(value).decode(json); }, _this.decode(json));
416
+ });
417
+ };
418
+ /**
419
+ * Add constraints to a decoder _without_ changing the resulting type. The
420
+ * `test` argument is a predicate function which returns true for valid
421
+ * inputs. When `test` fails on an input, the decoder fails with the given
422
+ * `errorMessage`.
423
+ *
424
+ * ```
425
+ * const chars = (length: number): Decoder<string> =>
426
+ * string().where(
427
+ * (s: string) => s.length === length,
428
+ * `expected a string of length ${length}`
429
+ * );
430
+ *
431
+ * chars(5).run('12345')
432
+ * // => {ok: true, result: '12345'}
433
+ *
434
+ * chars(2).run('HELLO')
435
+ * // => {ok: false, error: {... message: 'expected a string of length 2'}}
436
+ *
437
+ * chars(12).run(true)
438
+ * // => {ok: false, error: {... message: 'expected a string, got a boolean'}}
439
+ * ```
440
+ */
441
+ this.where = function (test, errorMessage) {
442
+ return _this.andThen(function (value) { return (test(value) ? Decoder.succeed(value) : Decoder.fail(errorMessage)); });
443
+ };
444
+ }
445
+ /**
446
+ * Decoder primitive that validates strings, and fails on all other input.
447
+ */
448
+ Decoder.string = function () {
449
+ return new Decoder(function (json) {
450
+ return typeof json === 'string'
451
+ ? ok(json)
452
+ : err({ message: expectedGot('a string', json) });
453
+ });
454
+ };
455
+ /**
456
+ * Decoder primitive that validates numbers, and fails on all other input.
457
+ */
458
+ Decoder.number = function () {
459
+ return new Decoder(function (json) {
460
+ return typeof json === 'number'
461
+ ? ok(json)
462
+ : err({ message: expectedGot('a number', json) });
463
+ });
464
+ };
465
+ /**
466
+ * Decoder primitive that validates booleans, and fails on all other input.
467
+ */
468
+ Decoder.boolean = function () {
469
+ return new Decoder(function (json) {
470
+ return typeof json === 'boolean'
471
+ ? ok(json)
472
+ : err({ message: expectedGot('a boolean', json) });
473
+ });
474
+ };
475
+ Decoder.constant = function (value) {
476
+ return new Decoder(function (json) {
477
+ return isEqual(json, value)
478
+ ? ok(value)
479
+ : err({ message: "expected " + JSON.stringify(value) + ", got " + JSON.stringify(json) });
480
+ });
481
+ };
482
+ Decoder.object = function (decoders) {
483
+ return new Decoder(function (json) {
484
+ if (isJsonObject(json) && decoders) {
485
+ var obj = {};
486
+ for (var key in decoders) {
487
+ if (decoders.hasOwnProperty(key)) {
488
+ var r = decoders[key].decode(json[key]);
489
+ if (r.ok === true) {
490
+ // tslint:disable-next-line:strict-type-predicates
491
+ if (r.result !== undefined) {
492
+ obj[key] = r.result;
493
+ }
494
+ }
495
+ else if (json[key] === undefined) {
496
+ return err({ message: "the key '" + key + "' is required but was not present" });
497
+ }
498
+ else {
499
+ return err(prependAt("." + key, r.error));
500
+ }
501
+ }
502
+ }
503
+ return ok(obj);
504
+ }
505
+ else if (isJsonObject(json)) {
506
+ return ok(json);
507
+ }
508
+ else {
509
+ return err({ message: expectedGot('an object', json) });
510
+ }
511
+ });
512
+ };
513
+ Decoder.array = function (decoder) {
514
+ return new Decoder(function (json) {
515
+ if (isJsonArray(json) && decoder) {
516
+ var decodeValue_1 = function (v, i) {
517
+ return mapError(function (err$$1) { return prependAt("[" + i + "]", err$$1); }, decoder.decode(v));
518
+ };
519
+ return json.reduce(function (acc, v, i) {
520
+ return map2(function (arr, result) { return arr.concat([result]); }, acc, decodeValue_1(v, i));
521
+ }, ok([]));
522
+ }
523
+ else if (isJsonArray(json)) {
524
+ return ok(json);
525
+ }
526
+ else {
527
+ return err({ message: expectedGot('an array', json) });
528
+ }
529
+ });
530
+ };
531
+ Decoder.tuple = function (decoders) {
532
+ return new Decoder(function (json) {
533
+ if (isJsonArray(json)) {
534
+ if (json.length !== decoders.length) {
535
+ return err({
536
+ message: "expected a tuple of length " + decoders.length + ", got one of length " + json.length
537
+ });
538
+ }
539
+ var result = [];
540
+ for (var i = 0; i < decoders.length; i++) {
541
+ var nth = decoders[i].decode(json[i]);
542
+ if (nth.ok) {
543
+ result[i] = nth.result;
544
+ }
545
+ else {
546
+ return err(prependAt("[" + i + "]", nth.error));
547
+ }
548
+ }
549
+ return ok(result);
550
+ }
551
+ else {
552
+ return err({ message: expectedGot("a tuple of length " + decoders.length, json) });
553
+ }
554
+ });
555
+ };
556
+ Decoder.union = function (ad, bd) {
557
+ var decoders = [];
558
+ for (var _i = 2; _i < arguments.length; _i++) {
559
+ decoders[_i - 2] = arguments[_i];
560
+ }
561
+ return Decoder.oneOf.apply(Decoder, [ad, bd].concat(decoders));
562
+ };
563
+ Decoder.intersection = function (ad, bd) {
564
+ var ds = [];
565
+ for (var _i = 2; _i < arguments.length; _i++) {
566
+ ds[_i - 2] = arguments[_i];
567
+ }
568
+ return new Decoder(function (json) {
569
+ return [ad, bd].concat(ds).reduce(function (acc, decoder) { return map2(Object.assign, acc, decoder.decode(json)); }, ok({}));
570
+ });
571
+ };
572
+ /**
573
+ * Escape hatch to bypass validation. Always succeeds and types the result as
574
+ * `any`. Useful for defining decoders incrementally, particularly for
575
+ * complex objects.
576
+ *
577
+ * Example:
578
+ * ```
579
+ * interface User {
580
+ * name: string;
581
+ * complexUserData: ComplexType;
582
+ * }
583
+ *
584
+ * const userDecoder: Decoder<User> = object({
585
+ * name: string(),
586
+ * complexUserData: anyJson()
587
+ * });
588
+ * ```
589
+ */
590
+ Decoder.anyJson = function () { return new Decoder(function (json) { return ok(json); }); };
591
+ /**
592
+ * Decoder identity function which always succeeds and types the result as
593
+ * `unknown`.
594
+ */
595
+ Decoder.unknownJson = function () {
596
+ return new Decoder(function (json) { return ok(json); });
597
+ };
598
+ /**
599
+ * Decoder for json objects where the keys are unknown strings, but the values
600
+ * should all be of the same type.
601
+ *
602
+ * Example:
603
+ * ```
604
+ * dict(number()).run({chocolate: 12, vanilla: 10, mint: 37});
605
+ * // => {ok: true, result: {chocolate: 12, vanilla: 10, mint: 37}}
606
+ * ```
607
+ */
608
+ Decoder.dict = function (decoder) {
609
+ return new Decoder(function (json) {
610
+ if (isJsonObject(json)) {
611
+ var obj = {};
612
+ for (var key in json) {
613
+ if (json.hasOwnProperty(key)) {
614
+ var r = decoder.decode(json[key]);
615
+ if (r.ok === true) {
616
+ obj[key] = r.result;
617
+ }
618
+ else {
619
+ return err(prependAt("." + key, r.error));
620
+ }
621
+ }
622
+ }
623
+ return ok(obj);
624
+ }
625
+ else {
626
+ return err({ message: expectedGot('an object', json) });
627
+ }
628
+ });
629
+ };
630
+ /**
631
+ * Decoder for values that may be `undefined`. This is primarily helpful for
632
+ * decoding interfaces with optional fields.
633
+ *
634
+ * Example:
635
+ * ```
636
+ * interface User {
637
+ * id: number;
638
+ * isOwner?: boolean;
639
+ * }
640
+ *
641
+ * const decoder: Decoder<User> = object({
642
+ * id: number(),
643
+ * isOwner: optional(boolean())
644
+ * });
645
+ * ```
646
+ */
647
+ Decoder.optional = function (decoder) {
648
+ return new Decoder(function (json) { return (json === undefined || json === null ? ok(undefined) : decoder.decode(json)); });
649
+ };
650
+ /**
651
+ * Decoder that attempts to run each decoder in `decoders` and either succeeds
652
+ * with the first successful decoder, or fails after all decoders have failed.
653
+ *
654
+ * Note that `oneOf` expects the decoders to all have the same return type,
655
+ * while `union` creates a decoder for the union type of all the input
656
+ * decoders.
657
+ *
658
+ * Examples:
659
+ * ```
660
+ * oneOf(string(), number().map(String))
661
+ * oneOf(constant('start'), constant('stop'), succeed('unknown'))
662
+ * ```
663
+ */
664
+ Decoder.oneOf = function () {
665
+ var decoders = [];
666
+ for (var _i = 0; _i < arguments.length; _i++) {
667
+ decoders[_i] = arguments[_i];
668
+ }
669
+ return new Decoder(function (json) {
670
+ var errors = [];
671
+ for (var i = 0; i < decoders.length; i++) {
672
+ var r = decoders[i].decode(json);
673
+ if (r.ok === true) {
674
+ return r;
675
+ }
676
+ else {
677
+ errors[i] = r.error;
678
+ }
679
+ }
680
+ var errorsList = errors
681
+ .map(function (error) { return "at error" + (error.at || '') + ": " + error.message; })
682
+ .join('", "');
683
+ return err({
684
+ message: "expected a value matching one of the decoders, got the errors [\"" + errorsList + "\"]"
685
+ });
686
+ });
687
+ };
688
+ /**
689
+ * Decoder that always succeeds with either the decoded value, or a fallback
690
+ * default value.
691
+ */
692
+ Decoder.withDefault = function (defaultValue, decoder) {
693
+ return new Decoder(function (json) {
694
+ return ok(withDefault(defaultValue, decoder.decode(json)));
695
+ });
696
+ };
697
+ /**
698
+ * Decoder that pulls a specific field out of a json structure, instead of
699
+ * decoding and returning the full structure. The `paths` array describes the
700
+ * object keys and array indices to traverse, so that values can be pulled out
701
+ * of a nested structure.
702
+ *
703
+ * Example:
704
+ * ```
705
+ * const decoder = valueAt(['a', 'b', 0], string());
706
+ *
707
+ * decoder.run({a: {b: ['surprise!']}})
708
+ * // => {ok: true, result: 'surprise!'}
709
+ *
710
+ * decoder.run({a: {x: 'cats'}})
711
+ * // => {ok: false, error: {... at: 'input.a.b[0]' message: 'path does not exist'}}
712
+ * ```
713
+ *
714
+ * Note that the `decoder` is ran on the value found at the last key in the
715
+ * path, even if the last key is not found. This allows the `optional`
716
+ * decoder to succeed when appropriate.
717
+ * ```
718
+ * const optionalDecoder = valueAt(['a', 'b', 'c'], optional(string()));
719
+ *
720
+ * optionalDecoder.run({a: {b: {c: 'surprise!'}}})
721
+ * // => {ok: true, result: 'surprise!'}
722
+ *
723
+ * optionalDecoder.run({a: {b: 'cats'}})
724
+ * // => {ok: false, error: {... at: 'input.a.b.c' message: 'expected an object, got "cats"'}
725
+ *
726
+ * optionalDecoder.run({a: {b: {z: 1}}})
727
+ * // => {ok: true, result: undefined}
728
+ * ```
729
+ */
730
+ Decoder.valueAt = function (paths, decoder) {
731
+ return new Decoder(function (json) {
732
+ var jsonAtPath = json;
733
+ for (var i = 0; i < paths.length; i++) {
734
+ if (jsonAtPath === undefined) {
735
+ return err({
736
+ at: printPath(paths.slice(0, i + 1)),
737
+ message: 'path does not exist'
738
+ });
739
+ }
740
+ else if (typeof paths[i] === 'string' && !isJsonObject(jsonAtPath)) {
741
+ return err({
742
+ at: printPath(paths.slice(0, i + 1)),
743
+ message: expectedGot('an object', jsonAtPath)
744
+ });
745
+ }
746
+ else if (typeof paths[i] === 'number' && !isJsonArray(jsonAtPath)) {
747
+ return err({
748
+ at: printPath(paths.slice(0, i + 1)),
749
+ message: expectedGot('an array', jsonAtPath)
750
+ });
751
+ }
752
+ else {
753
+ jsonAtPath = jsonAtPath[paths[i]];
754
+ }
755
+ }
756
+ return mapError(function (error) {
757
+ return jsonAtPath === undefined
758
+ ? { at: printPath(paths), message: 'path does not exist' }
759
+ : prependAt(printPath(paths), error);
760
+ }, decoder.decode(jsonAtPath));
761
+ });
762
+ };
763
+ /**
764
+ * Decoder that ignores the input json and always succeeds with `fixedValue`.
765
+ */
766
+ Decoder.succeed = function (fixedValue) {
767
+ return new Decoder(function (json) { return ok(fixedValue); });
768
+ };
769
+ /**
770
+ * Decoder that ignores the input json and always fails with `errorMessage`.
771
+ */
772
+ Decoder.fail = function (errorMessage) {
773
+ return new Decoder(function (json) { return err({ message: errorMessage }); });
774
+ };
775
+ /**
776
+ * Decoder that allows for validating recursive data structures. Unlike with
777
+ * functions, decoders assigned to variables can't reference themselves
778
+ * before they are fully defined. We can avoid prematurely referencing the
779
+ * decoder by wrapping it in a function that won't be called until use, at
780
+ * which point the decoder has been defined.
781
+ *
782
+ * Example:
783
+ * ```
784
+ * interface Comment {
785
+ * msg: string;
786
+ * replies: Comment[];
787
+ * }
788
+ *
789
+ * const decoder: Decoder<Comment> = object({
790
+ * msg: string(),
791
+ * replies: lazy(() => array(decoder))
792
+ * });
793
+ * ```
794
+ */
795
+ Decoder.lazy = function (mkDecoder) {
796
+ return new Decoder(function (json) { return mkDecoder().decode(json); });
797
+ };
798
+ return Decoder;
799
+ }());
800
+
801
+ /* tslint:disable:variable-name */
802
+ /** See `Decoder.string` */
803
+ var string = Decoder.string;
804
+ /** See `Decoder.number` */
805
+ Decoder.number;
806
+ /** See `Decoder.boolean` */
807
+ var boolean = Decoder.boolean;
808
+ /** See `Decoder.anyJson` */
809
+ var anyJson = Decoder.anyJson;
810
+ /** See `Decoder.unknownJson` */
811
+ Decoder.unknownJson;
812
+ /** See `Decoder.constant` */
813
+ Decoder.constant;
814
+ /** See `Decoder.object` */
815
+ var object = Decoder.object;
816
+ /** See `Decoder.array` */
817
+ var array = Decoder.array;
818
+ /** See `Decoder.tuple` */
819
+ Decoder.tuple;
820
+ /** See `Decoder.dict` */
821
+ Decoder.dict;
822
+ /** See `Decoder.optional` */
823
+ var optional = Decoder.optional;
824
+ /** See `Decoder.oneOf` */
825
+ Decoder.oneOf;
826
+ /** See `Decoder.union` */
827
+ Decoder.union;
828
+ /** See `Decoder.intersection` */
829
+ Decoder.intersection;
830
+ /** See `Decoder.withDefault` */
831
+ Decoder.withDefault;
832
+ /** See `Decoder.valueAt` */
833
+ Decoder.valueAt;
834
+ /** See `Decoder.succeed` */
835
+ Decoder.succeed;
836
+ /** See `Decoder.fail` */
837
+ var fail = Decoder.fail;
838
+ /** See `Decoder.lazy` */
839
+ Decoder.lazy;
840
+
841
+ /* eslint-disable @typescript-eslint/no-explicit-any */
842
+ var nonEmptyStringDecoder = string().where(function (s) { return s.length > 0; }, "Expected a non-empty string");
843
+ var functionCheck = function (input, propDescription) {
844
+ var providedType = typeof input;
845
+ return providedType === "function" ?
846
+ anyJson() :
847
+ fail("The provided argument as ".concat(propDescription, " should be of type function, provided: ").concat(typeof providedType));
848
+ };
849
+ var glue42NotificationClickHandlerDecoder = object({
850
+ action: nonEmptyStringDecoder,
851
+ handler: anyJson().andThen(function (result) { return functionCheck(result, "handler"); })
852
+ });
853
+ var webWorkerConfigDecoder = object({
854
+ platform: optional(object({
855
+ url: optional(nonEmptyStringDecoder),
856
+ openIfMissing: optional(boolean())
857
+ })),
858
+ notifications: optional(object({
859
+ defaultClick: optional(anyJson().andThen(function (result) { return functionCheck(result, "defaultClick"); })),
860
+ actionClicks: optional(array(glue42NotificationClickHandlerDecoder))
861
+ }))
862
+ });
863
+
864
+ let nanoid = (size = 21) =>
865
+ crypto.getRandomValues(new Uint8Array(size)).reduce((id, byte) => {
866
+ byte &= 63;
867
+ if (byte < 36) {
868
+ id += byte.toString(36);
869
+ } else if (byte < 62) {
870
+ id += (byte - 26).toString(36).toUpperCase();
871
+ } else if (byte > 62) {
872
+ id += '-';
873
+ } else {
874
+ id += '_';
875
+ }
876
+ return id
877
+ }, '');
878
+
879
+ const instanceOfAny = (object, constructors) => constructors.some((c) => object instanceof c);
880
+
881
+ let idbProxyableTypes;
882
+ let cursorAdvanceMethods;
883
+ // This is a function to prevent it throwing up in node environments.
884
+ function getIdbProxyableTypes() {
885
+ return (idbProxyableTypes ||
886
+ (idbProxyableTypes = [
887
+ IDBDatabase,
888
+ IDBObjectStore,
889
+ IDBIndex,
890
+ IDBCursor,
891
+ IDBTransaction,
892
+ ]));
893
+ }
894
+ // This is a function to prevent it throwing up in node environments.
895
+ function getCursorAdvanceMethods() {
896
+ return (cursorAdvanceMethods ||
897
+ (cursorAdvanceMethods = [
898
+ IDBCursor.prototype.advance,
899
+ IDBCursor.prototype.continue,
900
+ IDBCursor.prototype.continuePrimaryKey,
901
+ ]));
902
+ }
903
+ const cursorRequestMap = new WeakMap();
904
+ const transactionDoneMap = new WeakMap();
905
+ const transactionStoreNamesMap = new WeakMap();
906
+ const transformCache = new WeakMap();
907
+ const reverseTransformCache = new WeakMap();
908
+ function promisifyRequest(request) {
909
+ const promise = new Promise((resolve, reject) => {
910
+ const unlisten = () => {
911
+ request.removeEventListener('success', success);
912
+ request.removeEventListener('error', error);
913
+ };
914
+ const success = () => {
915
+ resolve(wrap(request.result));
916
+ unlisten();
917
+ };
918
+ const error = () => {
919
+ reject(request.error);
920
+ unlisten();
921
+ };
922
+ request.addEventListener('success', success);
923
+ request.addEventListener('error', error);
924
+ });
925
+ promise
926
+ .then((value) => {
927
+ // Since cursoring reuses the IDBRequest (*sigh*), we cache it for later retrieval
928
+ // (see wrapFunction).
929
+ if (value instanceof IDBCursor) {
930
+ cursorRequestMap.set(value, request);
931
+ }
932
+ // Catching to avoid "Uncaught Promise exceptions"
933
+ })
934
+ .catch(() => { });
935
+ // This mapping exists in reverseTransformCache but doesn't doesn't exist in transformCache. This
936
+ // is because we create many promises from a single IDBRequest.
937
+ reverseTransformCache.set(promise, request);
938
+ return promise;
939
+ }
940
+ function cacheDonePromiseForTransaction(tx) {
941
+ // Early bail if we've already created a done promise for this transaction.
942
+ if (transactionDoneMap.has(tx))
943
+ return;
944
+ const done = new Promise((resolve, reject) => {
945
+ const unlisten = () => {
946
+ tx.removeEventListener('complete', complete);
947
+ tx.removeEventListener('error', error);
948
+ tx.removeEventListener('abort', error);
949
+ };
950
+ const complete = () => {
951
+ resolve();
952
+ unlisten();
953
+ };
954
+ const error = () => {
955
+ reject(tx.error || new DOMException('AbortError', 'AbortError'));
956
+ unlisten();
957
+ };
958
+ tx.addEventListener('complete', complete);
959
+ tx.addEventListener('error', error);
960
+ tx.addEventListener('abort', error);
961
+ });
962
+ // Cache it for later retrieval.
963
+ transactionDoneMap.set(tx, done);
964
+ }
965
+ let idbProxyTraps = {
966
+ get(target, prop, receiver) {
967
+ if (target instanceof IDBTransaction) {
968
+ // Special handling for transaction.done.
969
+ if (prop === 'done')
970
+ return transactionDoneMap.get(target);
971
+ // Polyfill for objectStoreNames because of Edge.
972
+ if (prop === 'objectStoreNames') {
973
+ return target.objectStoreNames || transactionStoreNamesMap.get(target);
974
+ }
975
+ // Make tx.store return the only store in the transaction, or undefined if there are many.
976
+ if (prop === 'store') {
977
+ return receiver.objectStoreNames[1]
978
+ ? undefined
979
+ : receiver.objectStore(receiver.objectStoreNames[0]);
980
+ }
981
+ }
982
+ // Else transform whatever we get back.
983
+ return wrap(target[prop]);
984
+ },
985
+ set(target, prop, value) {
986
+ target[prop] = value;
987
+ return true;
988
+ },
989
+ has(target, prop) {
990
+ if (target instanceof IDBTransaction &&
991
+ (prop === 'done' || prop === 'store')) {
992
+ return true;
993
+ }
994
+ return prop in target;
995
+ },
996
+ };
997
+ function replaceTraps(callback) {
998
+ idbProxyTraps = callback(idbProxyTraps);
999
+ }
1000
+ function wrapFunction(func) {
1001
+ // Due to expected object equality (which is enforced by the caching in `wrap`), we
1002
+ // only create one new func per func.
1003
+ // Edge doesn't support objectStoreNames (booo), so we polyfill it here.
1004
+ if (func === IDBDatabase.prototype.transaction &&
1005
+ !('objectStoreNames' in IDBTransaction.prototype)) {
1006
+ return function (storeNames, ...args) {
1007
+ const tx = func.call(unwrap(this), storeNames, ...args);
1008
+ transactionStoreNamesMap.set(tx, storeNames.sort ? storeNames.sort() : [storeNames]);
1009
+ return wrap(tx);
1010
+ };
1011
+ }
1012
+ // Cursor methods are special, as the behaviour is a little more different to standard IDB. In
1013
+ // IDB, you advance the cursor and wait for a new 'success' on the IDBRequest that gave you the
1014
+ // cursor. It's kinda like a promise that can resolve with many values. That doesn't make sense
1015
+ // with real promises, so each advance methods returns a new promise for the cursor object, or
1016
+ // undefined if the end of the cursor has been reached.
1017
+ if (getCursorAdvanceMethods().includes(func)) {
1018
+ return function (...args) {
1019
+ // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use
1020
+ // the original object.
1021
+ func.apply(unwrap(this), args);
1022
+ return wrap(cursorRequestMap.get(this));
1023
+ };
1024
+ }
1025
+ return function (...args) {
1026
+ // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use
1027
+ // the original object.
1028
+ return wrap(func.apply(unwrap(this), args));
1029
+ };
1030
+ }
1031
+ function transformCachableValue(value) {
1032
+ if (typeof value === 'function')
1033
+ return wrapFunction(value);
1034
+ // This doesn't return, it just creates a 'done' promise for the transaction,
1035
+ // which is later returned for transaction.done (see idbObjectHandler).
1036
+ if (value instanceof IDBTransaction)
1037
+ cacheDonePromiseForTransaction(value);
1038
+ if (instanceOfAny(value, getIdbProxyableTypes()))
1039
+ return new Proxy(value, idbProxyTraps);
1040
+ // Return the same value back if we're not going to transform it.
1041
+ return value;
1042
+ }
1043
+ function wrap(value) {
1044
+ // We sometimes generate multiple promises from a single IDBRequest (eg when cursoring), because
1045
+ // IDB is weird and a single IDBRequest can yield many responses, so these can't be cached.
1046
+ if (value instanceof IDBRequest)
1047
+ return promisifyRequest(value);
1048
+ // If we've already transformed this value before, reuse the transformed value.
1049
+ // This is faster, but it also provides object equality.
1050
+ if (transformCache.has(value))
1051
+ return transformCache.get(value);
1052
+ const newValue = transformCachableValue(value);
1053
+ // Not all types are transformed.
1054
+ // These may be primitive types, so they can't be WeakMap keys.
1055
+ if (newValue !== value) {
1056
+ transformCache.set(value, newValue);
1057
+ reverseTransformCache.set(newValue, value);
1058
+ }
1059
+ return newValue;
1060
+ }
1061
+ const unwrap = (value) => reverseTransformCache.get(value);
1062
+
1063
+ /**
1064
+ * Open a database.
1065
+ *
1066
+ * @param name Name of the database.
1067
+ * @param version Schema version.
1068
+ * @param callbacks Additional callbacks.
1069
+ */
1070
+ function openDB(name, version, { blocked, upgrade, blocking, terminated } = {}) {
1071
+ const request = indexedDB.open(name, version);
1072
+ const openPromise = wrap(request);
1073
+ if (upgrade) {
1074
+ request.addEventListener('upgradeneeded', (event) => {
1075
+ upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction), event);
1076
+ });
1077
+ }
1078
+ if (blocked) {
1079
+ request.addEventListener('blocked', (event) => blocked(
1080
+ // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405
1081
+ event.oldVersion, event.newVersion, event));
1082
+ }
1083
+ openPromise
1084
+ .then((db) => {
1085
+ if (terminated)
1086
+ db.addEventListener('close', () => terminated());
1087
+ if (blocking) {
1088
+ db.addEventListener('versionchange', (event) => blocking(event.oldVersion, event.newVersion, event));
1089
+ }
1090
+ })
1091
+ .catch(() => { });
1092
+ return openPromise;
1093
+ }
1094
+
1095
+ const readMethods = ['get', 'getKey', 'getAll', 'getAllKeys', 'count'];
1096
+ const writeMethods = ['put', 'add', 'delete', 'clear'];
1097
+ const cachedMethods = new Map();
1098
+ function getMethod(target, prop) {
1099
+ if (!(target instanceof IDBDatabase &&
1100
+ !(prop in target) &&
1101
+ typeof prop === 'string')) {
1102
+ return;
1103
+ }
1104
+ if (cachedMethods.get(prop))
1105
+ return cachedMethods.get(prop);
1106
+ const targetFuncName = prop.replace(/FromIndex$/, '');
1107
+ const useIndex = prop !== targetFuncName;
1108
+ const isWrite = writeMethods.includes(targetFuncName);
1109
+ if (
1110
+ // Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge.
1111
+ !(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) ||
1112
+ !(isWrite || readMethods.includes(targetFuncName))) {
1113
+ return;
1114
+ }
1115
+ const method = async function (storeName, ...args) {
1116
+ // isWrite ? 'readwrite' : undefined gzipps better, but fails in Edge :(
1117
+ const tx = this.transaction(storeName, isWrite ? 'readwrite' : 'readonly');
1118
+ let target = tx.store;
1119
+ if (useIndex)
1120
+ target = target.index(args.shift());
1121
+ // Must reject if op rejects.
1122
+ // If it's a write operation, must reject if tx.done rejects.
1123
+ // Must reject with op rejection first.
1124
+ // Must resolve with op value.
1125
+ // Must handle both promises (no unhandled rejections)
1126
+ return (await Promise.all([
1127
+ target[targetFuncName](...args),
1128
+ isWrite && tx.done,
1129
+ ]))[0];
1130
+ };
1131
+ cachedMethods.set(prop, method);
1132
+ return method;
1133
+ }
1134
+ replaceTraps((oldTraps) => ({
1135
+ ...oldTraps,
1136
+ get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver),
1137
+ has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop),
1138
+ }));
1139
+
1140
+ var openDbPromise;
1141
+ var trimUrlQueryHashAndTrailingSlash = function (url) {
1142
+ var trimmedQueryHash = url.split("?")[0].split("#")[0];
1143
+ var trimmedTrailingSlash = trimmedQueryHash.replace(/\/$/, "");
1144
+ return trimmedTrailingSlash;
1145
+ };
1146
+ var startDb = function () {
1147
+ if (openDbPromise) {
1148
+ return openDbPromise;
1149
+ }
1150
+ openDbPromise = openDB(dbName, dbVersion, {
1151
+ upgrade: function (db) {
1152
+ if (!db.objectStoreNames.contains("workspaceLayouts")) {
1153
+ db.createObjectStore("workspaceLayouts");
1154
+ }
1155
+ if (!db.objectStoreNames.contains("globalLayouts")) {
1156
+ db.createObjectStore("globalLayouts");
1157
+ }
1158
+ if (!db.objectStoreNames.contains("serviceWorker")) {
1159
+ db.createObjectStore("serviceWorker");
1160
+ }
1161
+ }
1162
+ });
1163
+ return openDbPromise;
1164
+ };
1165
+ var checkPlatformOpen = function () {
1166
+ var checkPromise = new Promise(function (resolve) {
1167
+ var channel = new BroadcastChannel(serviceWorkerBroadcastChannelName);
1168
+ var existenceHandler = function (event) {
1169
+ var data = event.data;
1170
+ // check to see if somehow I have reference to the client that answers
1171
+ if (data.pong) {
1172
+ channel.removeEventListener("message", existenceHandler);
1173
+ resolve(true);
1174
+ }
1175
+ };
1176
+ channel.addEventListener("message", existenceHandler);
1177
+ channel.postMessage({ messageType: "ping" });
1178
+ });
1179
+ var timeoutPromise = new Promise(function (resolve) { return setTimeout(function () { return resolve(false); }, platformPingTimeoutMS); });
1180
+ return Promise.race([checkPromise, timeoutPromise]);
1181
+ };
1182
+ var getPlatformUrl = function (config) { return __awaiter(void 0, void 0, void 0, function () {
1183
+ var url_1, db, workerData, url;
1184
+ var _a, _b;
1185
+ return __generator(this, function (_c) {
1186
+ switch (_c.label) {
1187
+ case 0:
1188
+ if ((_a = config.platform) === null || _a === void 0 ? void 0 : _a.url) {
1189
+ url_1 = config.platform.url.split("?")[0].split("#")[0];
1190
+ console.debug("getting url from config: ".concat(url_1));
1191
+ return [2 /*return*/, trimUrlQueryHashAndTrailingSlash(url_1)];
1192
+ }
1193
+ console.debug("starting the db");
1194
+ return [4 /*yield*/, startDb()];
1195
+ case 1:
1196
+ db = _c.sent();
1197
+ if (!db.objectStoreNames.contains("serviceWorker")) {
1198
+ console.warn("there is no service worker store");
1199
+ return [2 /*return*/];
1200
+ }
1201
+ return [4 /*yield*/, db.get("serviceWorker", "workerData")];
1202
+ case 2:
1203
+ workerData = _c.sent();
1204
+ url = (_b = workerData === null || workerData === void 0 ? void 0 : workerData.platformUrl) === null || _b === void 0 ? void 0 : _b.split("?")[0].split("#")[0];
1205
+ return [2 /*return*/, trimUrlQueryHashAndTrailingSlash(url)];
1206
+ }
1207
+ });
1208
+ }); };
1209
+ var validateConfig = function (config) {
1210
+ var _a;
1211
+ if (config === void 0) { config = {}; }
1212
+ var validated = webWorkerConfigDecoder.runWithException(config);
1213
+ if ((_a = validated.platform) === null || _a === void 0 ? void 0 : _a.url) {
1214
+ validated.platform.url = validated.platform.url.replace(/\/$/, "");
1215
+ }
1216
+ return validated;
1217
+ };
1218
+ var raiseIONotification = function (settings) { return __awaiter(void 0, void 0, void 0, function () {
1219
+ var options, glueData;
1220
+ var _a;
1221
+ return __generator(this, function (_b) {
1222
+ options = Object.assign({}, settings, { title: undefined, clickInterop: undefined, actions: undefined });
1223
+ options.actions = (_a = settings.actions) === null || _a === void 0 ? void 0 : _a.map(function (action) {
1224
+ return {
1225
+ action: action.action,
1226
+ title: action.title,
1227
+ icon: action.icon
1228
+ };
1229
+ });
1230
+ glueData = {
1231
+ clickInterop: settings.clickInterop,
1232
+ actions: settings.actions,
1233
+ id: nanoid()
1234
+ };
1235
+ if (options.data) {
1236
+ options.data.glueData = glueData;
1237
+ }
1238
+ else {
1239
+ options.data = { glueData: glueData };
1240
+ }
1241
+ return [2 /*return*/, self.registration.showNotification(settings.title, options)];
1242
+ });
1243
+ }); };
1244
+ var openBrowserPlatform = function (url) {
1245
+ return new Promise(function (resolve, reject) {
1246
+ if (!url) {
1247
+ return reject("Cannot open the platform, because a url was not provided");
1248
+ }
1249
+ var channel = new BroadcastChannel(serviceWorkerBroadcastChannelName);
1250
+ var openHandler = function (event) {
1251
+ var data = event.data;
1252
+ if (data.platformStarted) {
1253
+ channel.removeEventListener("message", openHandler);
1254
+ resolve();
1255
+ }
1256
+ };
1257
+ channel.addEventListener("message", openHandler);
1258
+ self.clients.openWindow(url)["catch"](reject);
1259
+ setTimeout(function () { return reject("Timed out waiting for the platform to open and send a ready signal: ".concat(platformOpenTimeoutMS, " MS")); }, platformOpenTimeoutMS);
1260
+ });
1261
+ };
1262
+ var focusCorePlatform = function (url) { return __awaiter(void 0, void 0, void 0, function () {
1263
+ var allWindows, _i, allWindows_1, client, urlStrippedQueryHash, urlStrippedTrailingSlash;
1264
+ return __generator(this, function (_a) {
1265
+ switch (_a.label) {
1266
+ case 0:
1267
+ if (!url) {
1268
+ console.warn("Cannot open the platform, because a url was not provided");
1269
+ return [2 /*return*/];
1270
+ }
1271
+ return [4 /*yield*/, self.clients.matchAll({ type: "window" })];
1272
+ case 1:
1273
+ allWindows = _a.sent();
1274
+ _i = 0, allWindows_1 = allWindows;
1275
+ _a.label = 2;
1276
+ case 2:
1277
+ if (!(_i < allWindows_1.length)) return [3 /*break*/, 5];
1278
+ client = allWindows_1[_i];
1279
+ urlStrippedQueryHash = client.url.split("?")[0].split("#")[0];
1280
+ urlStrippedTrailingSlash = urlStrippedQueryHash.replace(/\/$/, "");
1281
+ if (!(urlStrippedTrailingSlash === url)) return [3 /*break*/, 4];
1282
+ return [4 /*yield*/, client.focus()];
1283
+ case 3:
1284
+ _a.sent();
1285
+ return [2 /*return*/];
1286
+ case 4:
1287
+ _i++;
1288
+ return [3 /*break*/, 2];
1289
+ case 5: return [2 /*return*/];
1290
+ }
1291
+ });
1292
+ }); };
1293
+ var setupCore = function (config) {
1294
+ var verifiedConfig = validateConfig(config);
1295
+ self.addEventListener("notificationclick", function (event) {
1296
+ var isPlatformOpen;
1297
+ var channel = new BroadcastChannel(serviceWorkerBroadcastChannelName);
1298
+ console.debug("Received a notification, checking if the platform is open");
1299
+ var executionPromise = checkPlatformOpen()
1300
+ .then(function (platformExists) {
1301
+ var _a, _b, _c;
1302
+ isPlatformOpen = platformExists;
1303
+ console.debug("The platform is: ".concat(isPlatformOpen ? "open" : "not open"));
1304
+ var action = event.action;
1305
+ if (!action && ((_a = verifiedConfig.notifications) === null || _a === void 0 ? void 0 : _a.defaultClick)) {
1306
+ console.debug("Calling a defined default click handler");
1307
+ return verifiedConfig.notifications.defaultClick(event, isPlatformOpen);
1308
+ }
1309
+ if (action && ((_c = (_b = verifiedConfig.notifications) === null || _b === void 0 ? void 0 : _b.actionClicks) === null || _c === void 0 ? void 0 : _c.some(function (actionDef) { return actionDef.action === action; }))) {
1310
+ var foundHandler = verifiedConfig.notifications.actionClicks.find(function (actionDef) { return actionDef.action === action; }).handler;
1311
+ console.debug("Calling a defined action click handler for action: ".concat(action));
1312
+ return foundHandler(event, isPlatformOpen);
1313
+ }
1314
+ })
1315
+ .then(function () {
1316
+ console.debug("Getting the platform url");
1317
+ return getPlatformUrl(verifiedConfig);
1318
+ })
1319
+ .then(function (url) {
1320
+ var _a, _b, _c;
1321
+ console.debug("Found platform url: ".concat(url));
1322
+ if (!isPlatformOpen && ((_a = verifiedConfig.platform) === null || _a === void 0 ? void 0 : _a.openIfMissing)) {
1323
+ console.debug("Opening the platform");
1324
+ return openBrowserPlatform(url);
1325
+ }
1326
+ var focusOnClick = (_c = (_b = event.notification.data) === null || _b === void 0 ? void 0 : _b.glueData) === null || _c === void 0 ? void 0 : _c.focusPlatformOnDefaultClick;
1327
+ if (isPlatformOpen && focusOnClick) {
1328
+ console.debug("Focusing the platform");
1329
+ return focusCorePlatform(url);
1330
+ }
1331
+ })
1332
+ .then(function () {
1333
+ var messageType = "notificationClick";
1334
+ var action = event.action;
1335
+ var glueData = event.notification.data.glueData;
1336
+ var definition = {
1337
+ badge: event.notification.badge,
1338
+ body: event.notification.body,
1339
+ data: event.notification.data,
1340
+ dir: event.notification.dir,
1341
+ icon: event.notification.icon,
1342
+ image: event.notification.image,
1343
+ lang: event.notification.lang,
1344
+ renotify: event.notification.renotify,
1345
+ requireInteraction: event.notification.requireInteraction,
1346
+ silent: event.notification.silent,
1347
+ tag: event.notification.tag,
1348
+ timestamp: event.notification.timestamp,
1349
+ vibrate: event.notification.vibrate
1350
+ };
1351
+ channel.postMessage({ messageType: messageType, action: action, glueData: glueData, definition: definition });
1352
+ })["catch"](function (error) {
1353
+ var stringError = typeof error === "string" ? error : JSON.stringify(error.message);
1354
+ channel.postMessage({ messageType: "notificationError", error: stringError });
1355
+ });
1356
+ event.waitUntil(executionPromise);
1357
+ });
1358
+ self.addEventListener("notificationclose", function (event) {
1359
+ var channel = new BroadcastChannel(serviceWorkerBroadcastChannelName);
1360
+ console.debug("Received a notification close event, checking if the platform is open");
1361
+ var executionPromise = checkPlatformOpen()
1362
+ .then(function (platformExists) {
1363
+ console.debug("The platform is: ".concat(platformExists ? "open" : "not open"));
1364
+ if (!platformExists) {
1365
+ console.log("The platform is not opened and will not open it for a notification close event");
1366
+ return;
1367
+ }
1368
+ var messageType = "notificationClose";
1369
+ var action = event.action;
1370
+ var glueData = event.notification.data.glueData;
1371
+ var definition = {
1372
+ badge: event.notification.badge,
1373
+ body: event.notification.body,
1374
+ data: event.notification.data,
1375
+ dir: event.notification.dir,
1376
+ icon: event.notification.icon,
1377
+ image: event.notification.image,
1378
+ lang: event.notification.lang,
1379
+ renotify: event.notification.renotify,
1380
+ requireInteraction: event.notification.requireInteraction,
1381
+ silent: event.notification.silent,
1382
+ tag: event.notification.tag,
1383
+ timestamp: event.notification.timestamp,
1384
+ vibrate: event.notification.vibrate
1385
+ };
1386
+ channel.postMessage({ messageType: messageType, action: action, glueData: glueData, definition: definition });
1387
+ })["catch"](function (error) {
1388
+ var stringError = typeof error === "string" ? error : JSON.stringify(error.message);
1389
+ channel.postMessage({ messageType: "notificationError", error: stringError });
1390
+ });
1391
+ event.waitUntil(executionPromise);
1392
+ });
1393
+ };
1394
+
1395
+ /* eslint-disable @typescript-eslint/no-explicit-any */
1396
+ if (typeof self !== "undefined") {
1397
+ self.IOWorker = setupCore;
1398
+ self.openBrowserPlatform = openBrowserPlatform;
1399
+ self.raiseIONotification = raiseIONotification;
1400
+ }
1401
+
1402
+ export { setupCore as default, openBrowserPlatform, raiseIONotification };
1403
+ //# sourceMappingURL=web.worker.es.js.map