@uva-fnwi/datanose-core 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3161 @@
1
+ import Ge, { createContext as Ye, useState as Ve, useReducer as Xe, useRef as Ze, useEffect as Qe, useMemo as et, useContext as tt } from "react";
2
+ var de = typeof globalThis < "u" ? globalThis : typeof window < "u" ? window : typeof global < "u" ? global : typeof self < "u" ? self : {};
3
+ function ae(e) {
4
+ return e && e.__esModule && Object.prototype.hasOwnProperty.call(e, "default") ? e.default : e;
5
+ }
6
+ function rt(e) {
7
+ if (Object.prototype.hasOwnProperty.call(e, "__esModule")) return e;
8
+ var t = e.default;
9
+ if (typeof t == "function") {
10
+ var r = function s() {
11
+ var i = !1;
12
+ try {
13
+ i = this instanceof s;
14
+ } catch {
15
+ }
16
+ return i ? Reflect.construct(t, arguments, this.constructor) : t.apply(this, arguments);
17
+ };
18
+ r.prototype = t.prototype;
19
+ } else r = {};
20
+ return Object.defineProperty(r, "__esModule", { value: !0 }), Object.keys(e).forEach(function(s) {
21
+ var i = Object.getOwnPropertyDescriptor(e, s);
22
+ Object.defineProperty(r, s, i.get ? i : {
23
+ enumerable: !0,
24
+ get: function() {
25
+ return e[s];
26
+ }
27
+ });
28
+ }), r;
29
+ }
30
+ function st(e) {
31
+ throw new Error('Could not dynamically require "' + e + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');
32
+ }
33
+ var te = { exports: {} };
34
+ const it = {}, nt = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
35
+ __proto__: null,
36
+ default: it
37
+ }, Symbol.toStringTag, { value: "Module" })), ot = /* @__PURE__ */ rt(nt);
38
+ var at = te.exports, Te;
39
+ function ce() {
40
+ return Te || (Te = 1, (function(e, t) {
41
+ (function(r, s) {
42
+ e.exports = s();
43
+ })(at, function() {
44
+ var r = r || (function(s, i) {
45
+ var n;
46
+ if (typeof window < "u" && window.crypto && (n = window.crypto), typeof self < "u" && self.crypto && (n = self.crypto), typeof globalThis < "u" && globalThis.crypto && (n = globalThis.crypto), !n && typeof window < "u" && window.msCrypto && (n = window.msCrypto), !n && typeof de < "u" && de.crypto && (n = de.crypto), !n && typeof st == "function")
47
+ try {
48
+ n = ot;
49
+ } catch {
50
+ }
51
+ var o = function() {
52
+ if (n) {
53
+ if (typeof n.getRandomValues == "function")
54
+ try {
55
+ return n.getRandomValues(new Uint32Array(1))[0];
56
+ } catch {
57
+ }
58
+ if (typeof n.randomBytes == "function")
59
+ try {
60
+ return n.randomBytes(4).readInt32LE();
61
+ } catch {
62
+ }
63
+ }
64
+ throw new Error("Native crypto module could not be used to get secure random number.");
65
+ }, l = Object.create || /* @__PURE__ */ (function() {
66
+ function a() {
67
+ }
68
+ return function(d) {
69
+ var f;
70
+ return a.prototype = d, f = new a(), a.prototype = null, f;
71
+ };
72
+ })(), u = {}, g = u.lib = {}, _ = g.Base = /* @__PURE__ */ (function() {
73
+ return {
74
+ /**
75
+ * Creates a new object that inherits from this object.
76
+ *
77
+ * @param {Object} overrides Properties to copy into the new object.
78
+ *
79
+ * @return {Object} The new object.
80
+ *
81
+ * @static
82
+ *
83
+ * @example
84
+ *
85
+ * var MyType = CryptoJS.lib.Base.extend({
86
+ * field: 'value',
87
+ *
88
+ * method: function () {
89
+ * }
90
+ * });
91
+ */
92
+ extend: function(a) {
93
+ var d = l(this);
94
+ return a && d.mixIn(a), (!d.hasOwnProperty("init") || this.init === d.init) && (d.init = function() {
95
+ d.$super.init.apply(this, arguments);
96
+ }), d.init.prototype = d, d.$super = this, d;
97
+ },
98
+ /**
99
+ * Extends this object and runs the init method.
100
+ * Arguments to create() will be passed to init().
101
+ *
102
+ * @return {Object} The new object.
103
+ *
104
+ * @static
105
+ *
106
+ * @example
107
+ *
108
+ * var instance = MyType.create();
109
+ */
110
+ create: function() {
111
+ var a = this.extend();
112
+ return a.init.apply(a, arguments), a;
113
+ },
114
+ /**
115
+ * Initializes a newly created object.
116
+ * Override this method to add some logic when your objects are created.
117
+ *
118
+ * @example
119
+ *
120
+ * var MyType = CryptoJS.lib.Base.extend({
121
+ * init: function () {
122
+ * // ...
123
+ * }
124
+ * });
125
+ */
126
+ init: function() {
127
+ },
128
+ /**
129
+ * Copies properties into this object.
130
+ *
131
+ * @param {Object} properties The properties to mix in.
132
+ *
133
+ * @example
134
+ *
135
+ * MyType.mixIn({
136
+ * field: 'value'
137
+ * });
138
+ */
139
+ mixIn: function(a) {
140
+ for (var d in a)
141
+ a.hasOwnProperty(d) && (this[d] = a[d]);
142
+ a.hasOwnProperty("toString") && (this.toString = a.toString);
143
+ },
144
+ /**
145
+ * Creates a copy of this object.
146
+ *
147
+ * @return {Object} The clone.
148
+ *
149
+ * @example
150
+ *
151
+ * var clone = instance.clone();
152
+ */
153
+ clone: function() {
154
+ return this.init.prototype.extend(this);
155
+ }
156
+ };
157
+ })(), h = g.WordArray = _.extend({
158
+ /**
159
+ * Initializes a newly created word array.
160
+ *
161
+ * @param {Array} words (Optional) An array of 32-bit words.
162
+ * @param {number} sigBytes (Optional) The number of significant bytes in the words.
163
+ *
164
+ * @example
165
+ *
166
+ * var wordArray = CryptoJS.lib.WordArray.create();
167
+ * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]);
168
+ * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6);
169
+ */
170
+ init: function(a, d) {
171
+ a = this.words = a || [], d != i ? this.sigBytes = d : this.sigBytes = a.length * 4;
172
+ },
173
+ /**
174
+ * Converts this word array to a string.
175
+ *
176
+ * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex
177
+ *
178
+ * @return {string} The stringified word array.
179
+ *
180
+ * @example
181
+ *
182
+ * var string = wordArray + '';
183
+ * var string = wordArray.toString();
184
+ * var string = wordArray.toString(CryptoJS.enc.Utf8);
185
+ */
186
+ toString: function(a) {
187
+ return (a || w).stringify(this);
188
+ },
189
+ /**
190
+ * Concatenates a word array to this word array.
191
+ *
192
+ * @param {WordArray} wordArray The word array to append.
193
+ *
194
+ * @return {WordArray} This word array.
195
+ *
196
+ * @example
197
+ *
198
+ * wordArray1.concat(wordArray2);
199
+ */
200
+ concat: function(a) {
201
+ var d = this.words, f = a.words, v = this.sigBytes, E = a.sigBytes;
202
+ if (this.clamp(), v % 4)
203
+ for (var R = 0; R < E; R++) {
204
+ var x = f[R >>> 2] >>> 24 - R % 4 * 8 & 255;
205
+ d[v + R >>> 2] |= x << 24 - (v + R) % 4 * 8;
206
+ }
207
+ else
208
+ for (var I = 0; I < E; I += 4)
209
+ d[v + I >>> 2] = f[I >>> 2];
210
+ return this.sigBytes += E, this;
211
+ },
212
+ /**
213
+ * Removes insignificant bits.
214
+ *
215
+ * @example
216
+ *
217
+ * wordArray.clamp();
218
+ */
219
+ clamp: function() {
220
+ var a = this.words, d = this.sigBytes;
221
+ a[d >>> 2] &= 4294967295 << 32 - d % 4 * 8, a.length = s.ceil(d / 4);
222
+ },
223
+ /**
224
+ * Creates a copy of this word array.
225
+ *
226
+ * @return {WordArray} The clone.
227
+ *
228
+ * @example
229
+ *
230
+ * var clone = wordArray.clone();
231
+ */
232
+ clone: function() {
233
+ var a = _.clone.call(this);
234
+ return a.words = this.words.slice(0), a;
235
+ },
236
+ /**
237
+ * Creates a word array filled with random bytes.
238
+ *
239
+ * @param {number} nBytes The number of random bytes to generate.
240
+ *
241
+ * @return {WordArray} The random word array.
242
+ *
243
+ * @static
244
+ *
245
+ * @example
246
+ *
247
+ * var wordArray = CryptoJS.lib.WordArray.random(16);
248
+ */
249
+ random: function(a) {
250
+ for (var d = [], f = 0; f < a; f += 4)
251
+ d.push(o());
252
+ return new h.init(d, a);
253
+ }
254
+ }), b = u.enc = {}, w = b.Hex = {
255
+ /**
256
+ * Converts a word array to a hex string.
257
+ *
258
+ * @param {WordArray} wordArray The word array.
259
+ *
260
+ * @return {string} The hex string.
261
+ *
262
+ * @static
263
+ *
264
+ * @example
265
+ *
266
+ * var hexString = CryptoJS.enc.Hex.stringify(wordArray);
267
+ */
268
+ stringify: function(a) {
269
+ for (var d = a.words, f = a.sigBytes, v = [], E = 0; E < f; E++) {
270
+ var R = d[E >>> 2] >>> 24 - E % 4 * 8 & 255;
271
+ v.push((R >>> 4).toString(16)), v.push((R & 15).toString(16));
272
+ }
273
+ return v.join("");
274
+ },
275
+ /**
276
+ * Converts a hex string to a word array.
277
+ *
278
+ * @param {string} hexStr The hex string.
279
+ *
280
+ * @return {WordArray} The word array.
281
+ *
282
+ * @static
283
+ *
284
+ * @example
285
+ *
286
+ * var wordArray = CryptoJS.enc.Hex.parse(hexString);
287
+ */
288
+ parse: function(a) {
289
+ for (var d = a.length, f = [], v = 0; v < d; v += 2)
290
+ f[v >>> 3] |= parseInt(a.substr(v, 2), 16) << 24 - v % 8 * 4;
291
+ return new h.init(f, d / 2);
292
+ }
293
+ }, k = b.Latin1 = {
294
+ /**
295
+ * Converts a word array to a Latin1 string.
296
+ *
297
+ * @param {WordArray} wordArray The word array.
298
+ *
299
+ * @return {string} The Latin1 string.
300
+ *
301
+ * @static
302
+ *
303
+ * @example
304
+ *
305
+ * var latin1String = CryptoJS.enc.Latin1.stringify(wordArray);
306
+ */
307
+ stringify: function(a) {
308
+ for (var d = a.words, f = a.sigBytes, v = [], E = 0; E < f; E++) {
309
+ var R = d[E >>> 2] >>> 24 - E % 4 * 8 & 255;
310
+ v.push(String.fromCharCode(R));
311
+ }
312
+ return v.join("");
313
+ },
314
+ /**
315
+ * Converts a Latin1 string to a word array.
316
+ *
317
+ * @param {string} latin1Str The Latin1 string.
318
+ *
319
+ * @return {WordArray} The word array.
320
+ *
321
+ * @static
322
+ *
323
+ * @example
324
+ *
325
+ * var wordArray = CryptoJS.enc.Latin1.parse(latin1String);
326
+ */
327
+ parse: function(a) {
328
+ for (var d = a.length, f = [], v = 0; v < d; v++)
329
+ f[v >>> 2] |= (a.charCodeAt(v) & 255) << 24 - v % 4 * 8;
330
+ return new h.init(f, d);
331
+ }
332
+ }, p = b.Utf8 = {
333
+ /**
334
+ * Converts a word array to a UTF-8 string.
335
+ *
336
+ * @param {WordArray} wordArray The word array.
337
+ *
338
+ * @return {string} The UTF-8 string.
339
+ *
340
+ * @static
341
+ *
342
+ * @example
343
+ *
344
+ * var utf8String = CryptoJS.enc.Utf8.stringify(wordArray);
345
+ */
346
+ stringify: function(a) {
347
+ try {
348
+ return decodeURIComponent(escape(k.stringify(a)));
349
+ } catch {
350
+ throw new Error("Malformed UTF-8 data");
351
+ }
352
+ },
353
+ /**
354
+ * Converts a UTF-8 string to a word array.
355
+ *
356
+ * @param {string} utf8Str The UTF-8 string.
357
+ *
358
+ * @return {WordArray} The word array.
359
+ *
360
+ * @static
361
+ *
362
+ * @example
363
+ *
364
+ * var wordArray = CryptoJS.enc.Utf8.parse(utf8String);
365
+ */
366
+ parse: function(a) {
367
+ return k.parse(unescape(encodeURIComponent(a)));
368
+ }
369
+ }, S = g.BufferedBlockAlgorithm = _.extend({
370
+ /**
371
+ * Resets this block algorithm's data buffer to its initial state.
372
+ *
373
+ * @example
374
+ *
375
+ * bufferedBlockAlgorithm.reset();
376
+ */
377
+ reset: function() {
378
+ this._data = new h.init(), this._nDataBytes = 0;
379
+ },
380
+ /**
381
+ * Adds new data to this block algorithm's buffer.
382
+ *
383
+ * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8.
384
+ *
385
+ * @example
386
+ *
387
+ * bufferedBlockAlgorithm._append('data');
388
+ * bufferedBlockAlgorithm._append(wordArray);
389
+ */
390
+ _append: function(a) {
391
+ typeof a == "string" && (a = p.parse(a)), this._data.concat(a), this._nDataBytes += a.sigBytes;
392
+ },
393
+ /**
394
+ * Processes available data blocks.
395
+ *
396
+ * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype.
397
+ *
398
+ * @param {boolean} doFlush Whether all blocks and partial blocks should be processed.
399
+ *
400
+ * @return {WordArray} The processed data.
401
+ *
402
+ * @example
403
+ *
404
+ * var processedData = bufferedBlockAlgorithm._process();
405
+ * var processedData = bufferedBlockAlgorithm._process(!!'flush');
406
+ */
407
+ _process: function(a) {
408
+ var d, f = this._data, v = f.words, E = f.sigBytes, R = this.blockSize, x = R * 4, I = E / x;
409
+ a ? I = s.ceil(I) : I = s.max((I | 0) - this._minBufferSize, 0);
410
+ var N = I * R, O = s.min(N * 4, E);
411
+ if (N) {
412
+ for (var q = 0; q < N; q += R)
413
+ this._doProcessBlock(v, q);
414
+ d = v.splice(0, N), f.sigBytes -= O;
415
+ }
416
+ return new h.init(d, O);
417
+ },
418
+ /**
419
+ * Creates a copy of this object.
420
+ *
421
+ * @return {Object} The clone.
422
+ *
423
+ * @example
424
+ *
425
+ * var clone = bufferedBlockAlgorithm.clone();
426
+ */
427
+ clone: function() {
428
+ var a = _.clone.call(this);
429
+ return a._data = this._data.clone(), a;
430
+ },
431
+ _minBufferSize: 0
432
+ });
433
+ g.Hasher = S.extend({
434
+ /**
435
+ * Configuration options.
436
+ */
437
+ cfg: _.extend(),
438
+ /**
439
+ * Initializes a newly created hasher.
440
+ *
441
+ * @param {Object} cfg (Optional) The configuration options to use for this hash computation.
442
+ *
443
+ * @example
444
+ *
445
+ * var hasher = CryptoJS.algo.SHA256.create();
446
+ */
447
+ init: function(a) {
448
+ this.cfg = this.cfg.extend(a), this.reset();
449
+ },
450
+ /**
451
+ * Resets this hasher to its initial state.
452
+ *
453
+ * @example
454
+ *
455
+ * hasher.reset();
456
+ */
457
+ reset: function() {
458
+ S.reset.call(this), this._doReset();
459
+ },
460
+ /**
461
+ * Updates this hasher with a message.
462
+ *
463
+ * @param {WordArray|string} messageUpdate The message to append.
464
+ *
465
+ * @return {Hasher} This hasher.
466
+ *
467
+ * @example
468
+ *
469
+ * hasher.update('message');
470
+ * hasher.update(wordArray);
471
+ */
472
+ update: function(a) {
473
+ return this._append(a), this._process(), this;
474
+ },
475
+ /**
476
+ * Finalizes the hash computation.
477
+ * Note that the finalize operation is effectively a destructive, read-once operation.
478
+ *
479
+ * @param {WordArray|string} messageUpdate (Optional) A final message update.
480
+ *
481
+ * @return {WordArray} The hash.
482
+ *
483
+ * @example
484
+ *
485
+ * var hash = hasher.finalize();
486
+ * var hash = hasher.finalize('message');
487
+ * var hash = hasher.finalize(wordArray);
488
+ */
489
+ finalize: function(a) {
490
+ a && this._append(a);
491
+ var d = this._doFinalize();
492
+ return d;
493
+ },
494
+ blockSize: 16,
495
+ /**
496
+ * Creates a shortcut function to a hasher's object interface.
497
+ *
498
+ * @param {Hasher} hasher The hasher to create a helper for.
499
+ *
500
+ * @return {Function} The shortcut function.
501
+ *
502
+ * @static
503
+ *
504
+ * @example
505
+ *
506
+ * var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256);
507
+ */
508
+ _createHelper: function(a) {
509
+ return function(d, f) {
510
+ return new a.init(f).finalize(d);
511
+ };
512
+ },
513
+ /**
514
+ * Creates a shortcut function to the HMAC's object interface.
515
+ *
516
+ * @param {Hasher} hasher The hasher to use in this HMAC helper.
517
+ *
518
+ * @return {Function} The shortcut function.
519
+ *
520
+ * @static
521
+ *
522
+ * @example
523
+ *
524
+ * var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256);
525
+ */
526
+ _createHmacHelper: function(a) {
527
+ return function(d, f) {
528
+ return new T.HMAC.init(a, f).finalize(d);
529
+ };
530
+ }
531
+ });
532
+ var T = u.algo = {};
533
+ return u;
534
+ })(Math);
535
+ return r;
536
+ });
537
+ })(te)), te.exports;
538
+ }
539
+ var ct = ce();
540
+ const lt = /* @__PURE__ */ ae(ct);
541
+ var re = { exports: {} }, ut = re.exports, xe;
542
+ function dt() {
543
+ return xe || (xe = 1, (function(e, t) {
544
+ (function(r, s) {
545
+ e.exports = s(ce());
546
+ })(ut, function(r) {
547
+ return (function(s) {
548
+ var i = r, n = i.lib, o = n.WordArray, l = n.Hasher, u = i.algo, g = [], _ = [];
549
+ (function() {
550
+ function w(T) {
551
+ for (var a = s.sqrt(T), d = 2; d <= a; d++)
552
+ if (!(T % d))
553
+ return !1;
554
+ return !0;
555
+ }
556
+ function k(T) {
557
+ return (T - (T | 0)) * 4294967296 | 0;
558
+ }
559
+ for (var p = 2, S = 0; S < 64; )
560
+ w(p) && (S < 8 && (g[S] = k(s.pow(p, 1 / 2))), _[S] = k(s.pow(p, 1 / 3)), S++), p++;
561
+ })();
562
+ var h = [], b = u.SHA256 = l.extend({
563
+ _doReset: function() {
564
+ this._hash = new o.init(g.slice(0));
565
+ },
566
+ _doProcessBlock: function(w, k) {
567
+ for (var p = this._hash.words, S = p[0], T = p[1], a = p[2], d = p[3], f = p[4], v = p[5], E = p[6], R = p[7], x = 0; x < 64; x++) {
568
+ if (x < 16)
569
+ h[x] = w[k + x] | 0;
570
+ else {
571
+ var I = h[x - 15], N = (I << 25 | I >>> 7) ^ (I << 14 | I >>> 18) ^ I >>> 3, O = h[x - 2], q = (O << 15 | O >>> 17) ^ (O << 13 | O >>> 19) ^ O >>> 10;
572
+ h[x] = N + h[x - 7] + q + h[x - 16];
573
+ }
574
+ var H = f & v ^ ~f & E, Y = S & T ^ S & a ^ T & a, W = (S << 30 | S >>> 2) ^ (S << 19 | S >>> 13) ^ (S << 10 | S >>> 22), F = (f << 26 | f >>> 6) ^ (f << 21 | f >>> 11) ^ (f << 7 | f >>> 25), $ = R + F + H + _[x] + h[x], z = W + Y;
575
+ R = E, E = v, v = f, f = d + $ | 0, d = a, a = T, T = S, S = $ + z | 0;
576
+ }
577
+ p[0] = p[0] + S | 0, p[1] = p[1] + T | 0, p[2] = p[2] + a | 0, p[3] = p[3] + d | 0, p[4] = p[4] + f | 0, p[5] = p[5] + v | 0, p[6] = p[6] + E | 0, p[7] = p[7] + R | 0;
578
+ },
579
+ _doFinalize: function() {
580
+ var w = this._data, k = w.words, p = this._nDataBytes * 8, S = w.sigBytes * 8;
581
+ return k[S >>> 5] |= 128 << 24 - S % 32, k[(S + 64 >>> 9 << 4) + 14] = s.floor(p / 4294967296), k[(S + 64 >>> 9 << 4) + 15] = p, w.sigBytes = k.length * 4, this._process(), this._hash;
582
+ },
583
+ clone: function() {
584
+ var w = l.clone.call(this);
585
+ return w._hash = this._hash.clone(), w;
586
+ }
587
+ });
588
+ i.SHA256 = l._createHelper(b), i.HmacSHA256 = l._createHmacHelper(b);
589
+ })(Math), r.SHA256;
590
+ });
591
+ })(re)), re.exports;
592
+ }
593
+ var ht = dt();
594
+ const gt = /* @__PURE__ */ ae(ht);
595
+ var se = { exports: {} }, _t = se.exports, Ie;
596
+ function ft() {
597
+ return Ie || (Ie = 1, (function(e, t) {
598
+ (function(r, s) {
599
+ e.exports = s(ce());
600
+ })(_t, function(r) {
601
+ return (function() {
602
+ var s = r, i = s.lib, n = i.WordArray, o = s.enc;
603
+ o.Base64 = {
604
+ /**
605
+ * Converts a word array to a Base64 string.
606
+ *
607
+ * @param {WordArray} wordArray The word array.
608
+ *
609
+ * @return {string} The Base64 string.
610
+ *
611
+ * @static
612
+ *
613
+ * @example
614
+ *
615
+ * var base64String = CryptoJS.enc.Base64.stringify(wordArray);
616
+ */
617
+ stringify: function(u) {
618
+ var g = u.words, _ = u.sigBytes, h = this._map;
619
+ u.clamp();
620
+ for (var b = [], w = 0; w < _; w += 3)
621
+ for (var k = g[w >>> 2] >>> 24 - w % 4 * 8 & 255, p = g[w + 1 >>> 2] >>> 24 - (w + 1) % 4 * 8 & 255, S = g[w + 2 >>> 2] >>> 24 - (w + 2) % 4 * 8 & 255, T = k << 16 | p << 8 | S, a = 0; a < 4 && w + a * 0.75 < _; a++)
622
+ b.push(h.charAt(T >>> 6 * (3 - a) & 63));
623
+ var d = h.charAt(64);
624
+ if (d)
625
+ for (; b.length % 4; )
626
+ b.push(d);
627
+ return b.join("");
628
+ },
629
+ /**
630
+ * Converts a Base64 string to a word array.
631
+ *
632
+ * @param {string} base64Str The Base64 string.
633
+ *
634
+ * @return {WordArray} The word array.
635
+ *
636
+ * @static
637
+ *
638
+ * @example
639
+ *
640
+ * var wordArray = CryptoJS.enc.Base64.parse(base64String);
641
+ */
642
+ parse: function(u) {
643
+ var g = u.length, _ = this._map, h = this._reverseMap;
644
+ if (!h) {
645
+ h = this._reverseMap = [];
646
+ for (var b = 0; b < _.length; b++)
647
+ h[_.charCodeAt(b)] = b;
648
+ }
649
+ var w = _.charAt(64);
650
+ if (w) {
651
+ var k = u.indexOf(w);
652
+ k !== -1 && (g = k);
653
+ }
654
+ return l(u, g, h);
655
+ },
656
+ _map: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
657
+ };
658
+ function l(u, g, _) {
659
+ for (var h = [], b = 0, w = 0; w < g; w++)
660
+ if (w % 4) {
661
+ var k = _[u.charCodeAt(w - 1)] << w % 4 * 2, p = _[u.charCodeAt(w)] >>> 6 - w % 4 * 2, S = k | p;
662
+ h[b >>> 2] |= S << 24 - b % 4 * 8, b++;
663
+ }
664
+ return n.create(h, b);
665
+ }
666
+ })(), r.enc.Base64;
667
+ });
668
+ })(se)), se.exports;
669
+ }
670
+ var pt = ft();
671
+ const Ce = /* @__PURE__ */ ae(pt);
672
+ var ie = { exports: {} }, wt = ie.exports, Ue;
673
+ function vt() {
674
+ return Ue || (Ue = 1, (function(e, t) {
675
+ (function(r, s) {
676
+ e.exports = s(ce());
677
+ })(wt, function(r) {
678
+ return r.enc.Utf8;
679
+ });
680
+ })(ie)), ie.exports;
681
+ }
682
+ var mt = vt();
683
+ const St = /* @__PURE__ */ ae(mt);
684
+ function ge(e) {
685
+ this.message = e;
686
+ }
687
+ ge.prototype = new Error(), ge.prototype.name = "InvalidCharacterError";
688
+ var Ae = typeof window < "u" && window.atob && window.atob.bind(window) || function(e) {
689
+ var t = String(e).replace(/=+$/, "");
690
+ if (t.length % 4 == 1) throw new ge("'atob' failed: The string to be decoded is not correctly encoded.");
691
+ for (var r, s, i = 0, n = 0, o = ""; s = t.charAt(n++); ~s && (r = i % 4 ? 64 * r + s : s, i++ % 4) ? o += String.fromCharCode(255 & r >> (-2 * i & 6)) : 0) s = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(s);
692
+ return o;
693
+ };
694
+ function yt(e) {
695
+ var t = e.replace(/-/g, "+").replace(/_/g, "/");
696
+ switch (t.length % 4) {
697
+ case 0:
698
+ break;
699
+ case 2:
700
+ t += "==";
701
+ break;
702
+ case 3:
703
+ t += "=";
704
+ break;
705
+ default:
706
+ throw "Illegal base64url string!";
707
+ }
708
+ try {
709
+ return (function(r) {
710
+ return decodeURIComponent(Ae(r).replace(/(.)/g, (function(s, i) {
711
+ var n = i.charCodeAt(0).toString(16).toUpperCase();
712
+ return n.length < 2 && (n = "0" + n), "%" + n;
713
+ })));
714
+ })(t);
715
+ } catch {
716
+ return Ae(t);
717
+ }
718
+ }
719
+ function ne(e) {
720
+ this.message = e;
721
+ }
722
+ function bt(e, t) {
723
+ if (typeof e != "string") throw new ne("Invalid token specified");
724
+ var r = (t = t || {}).header === !0 ? 0 : 1;
725
+ try {
726
+ return JSON.parse(yt(e.split(".")[r]));
727
+ } catch (s) {
728
+ throw new ne("Invalid token specified: " + s.message);
729
+ }
730
+ }
731
+ ne.prototype = new Error(), ne.prototype.name = "InvalidTokenError";
732
+ var kt = {
733
+ debug: () => {
734
+ },
735
+ info: () => {
736
+ },
737
+ warn: () => {
738
+ },
739
+ error: () => {
740
+ }
741
+ }, M, j, oe = /* @__PURE__ */ ((e) => (e[e.NONE = 0] = "NONE", e[e.ERROR = 1] = "ERROR", e[e.WARN = 2] = "WARN", e[e.INFO = 3] = "INFO", e[e.DEBUG = 4] = "DEBUG", e))(oe || {});
742
+ ((e) => {
743
+ function t() {
744
+ M = 3, j = kt;
745
+ }
746
+ e.reset = t;
747
+ function r(i) {
748
+ if (!(0 <= i && i <= 4))
749
+ throw new Error("Invalid log level");
750
+ M = i;
751
+ }
752
+ e.setLevel = r;
753
+ function s(i) {
754
+ j = i;
755
+ }
756
+ e.setLogger = s;
757
+ })(oe || (oe = {}));
758
+ var m = class {
759
+ constructor(e) {
760
+ this._name = e;
761
+ }
762
+ /* eslint-disable @typescript-eslint/no-unsafe-enum-comparison */
763
+ debug(...e) {
764
+ M >= 4 && j.debug(m._format(this._name, this._method), ...e);
765
+ }
766
+ info(...e) {
767
+ M >= 3 && j.info(m._format(this._name, this._method), ...e);
768
+ }
769
+ warn(...e) {
770
+ M >= 2 && j.warn(m._format(this._name, this._method), ...e);
771
+ }
772
+ error(...e) {
773
+ M >= 1 && j.error(m._format(this._name, this._method), ...e);
774
+ }
775
+ /* eslint-enable @typescript-eslint/no-unsafe-enum-comparison */
776
+ throw(e) {
777
+ throw this.error(e), e;
778
+ }
779
+ create(e) {
780
+ const t = Object.create(this);
781
+ return t._method = e, t.debug("begin"), t;
782
+ }
783
+ static createStatic(e, t) {
784
+ const r = new m(`${e}.${t}`);
785
+ return r.debug("begin"), r;
786
+ }
787
+ static _format(e, t) {
788
+ const r = `[${e}]`;
789
+ return t ? `${r} ${t}:` : r;
790
+ }
791
+ /* eslint-disable @typescript-eslint/no-unsafe-enum-comparison */
792
+ // helpers for static class methods
793
+ static debug(e, ...t) {
794
+ M >= 4 && j.debug(m._format(e), ...t);
795
+ }
796
+ static info(e, ...t) {
797
+ M >= 3 && j.info(m._format(e), ...t);
798
+ }
799
+ static warn(e, ...t) {
800
+ M >= 2 && j.warn(m._format(e), ...t);
801
+ }
802
+ static error(e, ...t) {
803
+ M >= 1 && j.error(m._format(e), ...t);
804
+ }
805
+ /* eslint-enable @typescript-eslint/no-unsafe-enum-comparison */
806
+ };
807
+ oe.reset();
808
+ var Et = "10000000-1000-4000-8000-100000000000", L = class {
809
+ static _randomWord() {
810
+ return lt.lib.WordArray.random(1).words[0];
811
+ }
812
+ /**
813
+ * Generates RFC4122 version 4 guid
814
+ */
815
+ static generateUUIDv4() {
816
+ return Et.replace(
817
+ /[018]/g,
818
+ (t) => (+t ^ L._randomWord() & 15 >> +t / 4).toString(16)
819
+ ).replace(/-/g, "");
820
+ }
821
+ /**
822
+ * PKCE: Generate a code verifier
823
+ */
824
+ static generateCodeVerifier() {
825
+ return L.generateUUIDv4() + L.generateUUIDv4() + L.generateUUIDv4();
826
+ }
827
+ /**
828
+ * PKCE: Generate a code challenge
829
+ */
830
+ static generateCodeChallenge(e) {
831
+ try {
832
+ const t = gt(e);
833
+ return Ce.stringify(t).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
834
+ } catch (t) {
835
+ throw m.error("CryptoUtils.generateCodeChallenge", t), t;
836
+ }
837
+ }
838
+ /**
839
+ * Generates a base64-encoded string for a basic auth header
840
+ */
841
+ static generateBasicAuth(e, t) {
842
+ const r = St.parse([e, t].join(":"));
843
+ return Ce.stringify(r);
844
+ }
845
+ }, D = class {
846
+ constructor(e) {
847
+ this._name = e, this._logger = new m(`Event('${this._name}')`), this._callbacks = [];
848
+ }
849
+ addHandler(e) {
850
+ return this._callbacks.push(e), () => this.removeHandler(e);
851
+ }
852
+ removeHandler(e) {
853
+ const t = this._callbacks.lastIndexOf(e);
854
+ t >= 0 && this._callbacks.splice(t, 1);
855
+ }
856
+ raise(...e) {
857
+ this._logger.debug("raise:", ...e);
858
+ for (const t of this._callbacks)
859
+ t(...e);
860
+ }
861
+ }, _e = class {
862
+ // IMPORTANT: doesn't validate the token
863
+ static decode(e) {
864
+ try {
865
+ return bt(e);
866
+ } catch (t) {
867
+ throw m.error("JwtUtils.decode", t), t;
868
+ }
869
+ }
870
+ }, Oe = class {
871
+ /**
872
+ * Populates a map of window features with a placement centered in front of
873
+ * the current window. If no explicit width is given, a default value is
874
+ * binned into [800, 720, 600, 480, 360] based on the current window's width.
875
+ */
876
+ static center({ ...e }) {
877
+ var t, r, s;
878
+ return e.width == null && (e.width = (t = [800, 720, 600, 480].find((i) => i <= window.outerWidth / 1.618)) != null ? t : 360), (r = e.left) != null || (e.left = Math.max(0, Math.round(window.screenX + (window.outerWidth - e.width) / 2))), e.height != null && ((s = e.top) != null || (e.top = Math.max(0, Math.round(window.screenY + (window.outerHeight - e.height) / 2)))), e;
879
+ }
880
+ static serialize(e) {
881
+ return Object.entries(e).filter(([, t]) => t != null).map(([t, r]) => `${t}=${typeof r != "boolean" ? r : r ? "yes" : "no"}`).join(",");
882
+ }
883
+ }, P = class extends D {
884
+ constructor() {
885
+ super(...arguments), this._logger = new m(`Timer('${this._name}')`), this._timerHandle = null, this._expiration = 0, this._callback = () => {
886
+ const e = this._expiration - P.getEpochTime();
887
+ this._logger.debug("timer completes in", e), this._expiration <= P.getEpochTime() && (this.cancel(), super.raise());
888
+ };
889
+ }
890
+ // get the time
891
+ static getEpochTime() {
892
+ return Math.floor(Date.now() / 1e3);
893
+ }
894
+ init(e) {
895
+ const t = this._logger.create("init");
896
+ e = Math.max(Math.floor(e), 1);
897
+ const r = P.getEpochTime() + e;
898
+ if (this.expiration === r && this._timerHandle) {
899
+ t.debug("skipping since already initialized for expiration at", this.expiration);
900
+ return;
901
+ }
902
+ this.cancel(), t.debug("using duration", e), this._expiration = r;
903
+ const s = Math.min(e, 5);
904
+ this._timerHandle = setInterval(this._callback, s * 1e3);
905
+ }
906
+ get expiration() {
907
+ return this._expiration;
908
+ }
909
+ cancel() {
910
+ this._logger.create("cancel"), this._timerHandle && (clearInterval(this._timerHandle), this._timerHandle = null);
911
+ }
912
+ }, fe = class {
913
+ static readParams(e, t = "query") {
914
+ if (!e)
915
+ throw new TypeError("Invalid URL");
916
+ const s = new URL(e, "http://127.0.0.1")[t === "fragment" ? "hash" : "search"];
917
+ return new URLSearchParams(s.slice(1));
918
+ }
919
+ }, pe = ";", B = class extends Error {
920
+ constructor(e, t) {
921
+ var r, s, i;
922
+ if (super(e.error_description || e.error || ""), this.form = t, this.name = "ErrorResponse", !e.error)
923
+ throw m.error("ErrorResponse", "No error passed"), new Error("No error passed");
924
+ this.error = e.error, this.error_description = (r = e.error_description) != null ? r : null, this.error_uri = (s = e.error_uri) != null ? s : null, this.state = e.userState, this.session_state = (i = e.session_state) != null ? i : null, this.url_state = e.url_state;
925
+ }
926
+ }, me = class extends Error {
927
+ constructor(e) {
928
+ super(e), this.name = "ErrorTimeout";
929
+ }
930
+ }, Rt = class {
931
+ constructor(e) {
932
+ this._logger = new m("AccessTokenEvents"), this._expiringTimer = new P("Access token expiring"), this._expiredTimer = new P("Access token expired"), this._expiringNotificationTimeInSeconds = e.expiringNotificationTimeInSeconds;
933
+ }
934
+ load(e) {
935
+ const t = this._logger.create("load");
936
+ if (e.access_token && e.expires_in !== void 0) {
937
+ const r = e.expires_in;
938
+ if (t.debug("access token present, remaining duration:", r), r > 0) {
939
+ let i = r - this._expiringNotificationTimeInSeconds;
940
+ i <= 0 && (i = 1), t.debug("registering expiring timer, raising in", i, "seconds"), this._expiringTimer.init(i);
941
+ } else
942
+ t.debug("canceling existing expiring timer because we're past expiration."), this._expiringTimer.cancel();
943
+ const s = r + 1;
944
+ t.debug("registering expired timer, raising in", s, "seconds"), this._expiredTimer.init(s);
945
+ } else
946
+ this._expiringTimer.cancel(), this._expiredTimer.cancel();
947
+ }
948
+ unload() {
949
+ this._logger.debug("unload: canceling existing access token timers"), this._expiringTimer.cancel(), this._expiredTimer.cancel();
950
+ }
951
+ /**
952
+ * Add callback: Raised prior to the access token expiring.
953
+ */
954
+ addAccessTokenExpiring(e) {
955
+ return this._expiringTimer.addHandler(e);
956
+ }
957
+ /**
958
+ * Remove callback: Raised prior to the access token expiring.
959
+ */
960
+ removeAccessTokenExpiring(e) {
961
+ this._expiringTimer.removeHandler(e);
962
+ }
963
+ /**
964
+ * Add callback: Raised after the access token has expired.
965
+ */
966
+ addAccessTokenExpired(e) {
967
+ return this._expiredTimer.addHandler(e);
968
+ }
969
+ /**
970
+ * Remove callback: Raised after the access token has expired.
971
+ */
972
+ removeAccessTokenExpired(e) {
973
+ this._expiredTimer.removeHandler(e);
974
+ }
975
+ }, Tt = class {
976
+ constructor(e, t, r, s, i) {
977
+ this._callback = e, this._client_id = t, this._intervalInSeconds = s, this._stopOnError = i, this._logger = new m("CheckSessionIFrame"), this._timer = null, this._session_state = null, this._message = (o) => {
978
+ o.origin === this._frame_origin && o.source === this._frame.contentWindow && (o.data === "error" ? (this._logger.error("error message from check session op iframe"), this._stopOnError && this.stop()) : o.data === "changed" ? (this._logger.debug("changed message from check session op iframe"), this.stop(), this._callback()) : this._logger.debug(o.data + " message from check session op iframe"));
979
+ };
980
+ const n = new URL(r);
981
+ this._frame_origin = n.origin, this._frame = window.document.createElement("iframe"), this._frame.style.visibility = "hidden", this._frame.style.position = "fixed", this._frame.style.left = "-1000px", this._frame.style.top = "0", this._frame.width = "0", this._frame.height = "0", this._frame.src = n.href;
982
+ }
983
+ load() {
984
+ return new Promise((e) => {
985
+ this._frame.onload = () => {
986
+ e();
987
+ }, window.document.body.appendChild(this._frame), window.addEventListener("message", this._message, !1);
988
+ });
989
+ }
990
+ start(e) {
991
+ if (this._session_state === e)
992
+ return;
993
+ this._logger.create("start"), this.stop(), this._session_state = e;
994
+ const t = () => {
995
+ !this._frame.contentWindow || !this._session_state || this._frame.contentWindow.postMessage(this._client_id + " " + this._session_state, this._frame_origin);
996
+ };
997
+ t(), this._timer = setInterval(t, this._intervalInSeconds * 1e3);
998
+ }
999
+ stop() {
1000
+ this._logger.create("stop"), this._session_state = null, this._timer && (clearInterval(this._timer), this._timer = null);
1001
+ }
1002
+ }, He = class {
1003
+ constructor() {
1004
+ this._logger = new m("InMemoryWebStorage"), this._data = {};
1005
+ }
1006
+ clear() {
1007
+ this._logger.create("clear"), this._data = {};
1008
+ }
1009
+ getItem(e) {
1010
+ return this._logger.create(`getItem('${e}')`), this._data[e];
1011
+ }
1012
+ setItem(e, t) {
1013
+ this._logger.create(`setItem('${e}')`), this._data[e] = t;
1014
+ }
1015
+ removeItem(e) {
1016
+ this._logger.create(`removeItem('${e}')`), delete this._data[e];
1017
+ }
1018
+ get length() {
1019
+ return Object.getOwnPropertyNames(this._data).length;
1020
+ }
1021
+ key(e) {
1022
+ return Object.getOwnPropertyNames(this._data)[e];
1023
+ }
1024
+ }, Se = class {
1025
+ constructor(e = [], t = null, r = {}) {
1026
+ this._jwtHandler = t, this._extraHeaders = r, this._logger = new m("JsonService"), this._contentTypes = [], this._contentTypes.push(...e, "application/json"), t && this._contentTypes.push("application/jwt");
1027
+ }
1028
+ async fetchWithTimeout(e, t = {}) {
1029
+ const { timeoutInSeconds: r, ...s } = t;
1030
+ if (!r)
1031
+ return await fetch(e, s);
1032
+ const i = new AbortController(), n = setTimeout(() => i.abort(), r * 1e3);
1033
+ try {
1034
+ return await fetch(e, {
1035
+ ...t,
1036
+ signal: i.signal
1037
+ });
1038
+ } catch (o) {
1039
+ throw o instanceof DOMException && o.name === "AbortError" ? new me("Network timed out") : o;
1040
+ } finally {
1041
+ clearTimeout(n);
1042
+ }
1043
+ }
1044
+ async getJson(e, {
1045
+ token: t,
1046
+ credentials: r
1047
+ } = {}) {
1048
+ const s = this._logger.create("getJson"), i = {
1049
+ Accept: this._contentTypes.join(", ")
1050
+ };
1051
+ t && (s.debug("token passed, setting Authorization header"), i.Authorization = "Bearer " + t), this.appendExtraHeaders(i);
1052
+ let n;
1053
+ try {
1054
+ s.debug("url:", e), n = await this.fetchWithTimeout(e, { method: "GET", headers: i, credentials: r });
1055
+ } catch (u) {
1056
+ throw s.error("Network Error"), u;
1057
+ }
1058
+ s.debug("HTTP response received, status", n.status);
1059
+ const o = n.headers.get("Content-Type");
1060
+ if (o && !this._contentTypes.find((u) => o.startsWith(u)) && s.throw(new Error(`Invalid response Content-Type: ${o ?? "undefined"}, from URL: ${e}`)), n.ok && this._jwtHandler && o?.startsWith("application/jwt"))
1061
+ return await this._jwtHandler(await n.text());
1062
+ let l;
1063
+ try {
1064
+ l = await n.json();
1065
+ } catch (u) {
1066
+ throw s.error("Error parsing JSON response", u), n.ok ? u : new Error(`${n.statusText} (${n.status})`);
1067
+ }
1068
+ if (!n.ok)
1069
+ throw s.error("Error from server:", l), l.error ? new B(l) : new Error(`${n.statusText} (${n.status}): ${JSON.stringify(l)}`);
1070
+ return l;
1071
+ }
1072
+ async postForm(e, {
1073
+ body: t,
1074
+ basicAuth: r,
1075
+ timeoutInSeconds: s,
1076
+ initCredentials: i
1077
+ }) {
1078
+ const n = this._logger.create("postForm"), o = {
1079
+ Accept: this._contentTypes.join(", "),
1080
+ "Content-Type": "application/x-www-form-urlencoded"
1081
+ };
1082
+ r !== void 0 && (o.Authorization = "Basic " + r), this.appendExtraHeaders(o);
1083
+ let l;
1084
+ try {
1085
+ n.debug("url:", e), l = await this.fetchWithTimeout(e, { method: "POST", headers: o, body: t, timeoutInSeconds: s, credentials: i });
1086
+ } catch (h) {
1087
+ throw n.error("Network error"), h;
1088
+ }
1089
+ n.debug("HTTP response received, status", l.status);
1090
+ const u = l.headers.get("Content-Type");
1091
+ if (u && !this._contentTypes.find((h) => u.startsWith(h)))
1092
+ throw new Error(`Invalid response Content-Type: ${u ?? "undefined"}, from URL: ${e}`);
1093
+ const g = await l.text();
1094
+ let _ = {};
1095
+ if (g)
1096
+ try {
1097
+ _ = JSON.parse(g);
1098
+ } catch (h) {
1099
+ throw n.error("Error parsing JSON response", h), l.ok ? h : new Error(`${l.statusText} (${l.status})`);
1100
+ }
1101
+ if (!l.ok)
1102
+ throw n.error("Error from server:", _), _.error ? new B(_, t) : new Error(`${l.statusText} (${l.status}): ${JSON.stringify(_)}`);
1103
+ return _;
1104
+ }
1105
+ appendExtraHeaders(e) {
1106
+ const t = this._logger.create("appendExtraHeaders"), r = Object.keys(this._extraHeaders), s = [
1107
+ "authorization",
1108
+ "accept",
1109
+ "content-type"
1110
+ ];
1111
+ r.length !== 0 && r.forEach((i) => {
1112
+ if (s.includes(i.toLocaleLowerCase())) {
1113
+ t.warn("Protected header could not be overridden", i, s);
1114
+ return;
1115
+ }
1116
+ const n = typeof this._extraHeaders[i] == "function" ? this._extraHeaders[i]() : this._extraHeaders[i];
1117
+ n && n !== "" && (e[i] = n);
1118
+ });
1119
+ }
1120
+ }, xt = class {
1121
+ constructor(e) {
1122
+ this._settings = e, this._logger = new m("MetadataService"), this._signingKeys = null, this._metadata = null, this._metadataUrl = this._settings.metadataUrl, this._jsonService = new Se(
1123
+ ["application/jwk-set+json"],
1124
+ null,
1125
+ this._settings.extraHeaders
1126
+ ), this._settings.signingKeys && (this._logger.debug("using signingKeys from settings"), this._signingKeys = this._settings.signingKeys), this._settings.metadata && (this._logger.debug("using metadata from settings"), this._metadata = this._settings.metadata), this._settings.fetchRequestCredentials && (this._logger.debug("using fetchRequestCredentials from settings"), this._fetchRequestCredentials = this._settings.fetchRequestCredentials);
1127
+ }
1128
+ resetSigningKeys() {
1129
+ this._signingKeys = null;
1130
+ }
1131
+ async getMetadata() {
1132
+ const e = this._logger.create("getMetadata");
1133
+ if (this._metadata)
1134
+ return e.debug("using cached values"), this._metadata;
1135
+ if (!this._metadataUrl)
1136
+ throw e.throw(new Error("No authority or metadataUrl configured on settings")), null;
1137
+ e.debug("getting metadata from", this._metadataUrl);
1138
+ const t = await this._jsonService.getJson(this._metadataUrl, { credentials: this._fetchRequestCredentials });
1139
+ return e.debug("merging remote JSON with seed metadata"), this._metadata = Object.assign({}, this._settings.metadataSeed, t), this._metadata;
1140
+ }
1141
+ getIssuer() {
1142
+ return this._getMetadataProperty("issuer");
1143
+ }
1144
+ getAuthorizationEndpoint() {
1145
+ return this._getMetadataProperty("authorization_endpoint");
1146
+ }
1147
+ getUserInfoEndpoint() {
1148
+ return this._getMetadataProperty("userinfo_endpoint");
1149
+ }
1150
+ getTokenEndpoint(e = !0) {
1151
+ return this._getMetadataProperty("token_endpoint", e);
1152
+ }
1153
+ getCheckSessionIframe() {
1154
+ return this._getMetadataProperty("check_session_iframe", !0);
1155
+ }
1156
+ getEndSessionEndpoint() {
1157
+ return this._getMetadataProperty("end_session_endpoint", !0);
1158
+ }
1159
+ getRevocationEndpoint(e = !0) {
1160
+ return this._getMetadataProperty("revocation_endpoint", e);
1161
+ }
1162
+ getKeysEndpoint(e = !0) {
1163
+ return this._getMetadataProperty("jwks_uri", e);
1164
+ }
1165
+ async _getMetadataProperty(e, t = !1) {
1166
+ const r = this._logger.create(`_getMetadataProperty('${e}')`), s = await this.getMetadata();
1167
+ if (r.debug("resolved"), s[e] === void 0) {
1168
+ if (t === !0) {
1169
+ r.warn("Metadata does not contain optional property");
1170
+ return;
1171
+ }
1172
+ r.throw(new Error("Metadata does not contain property " + e));
1173
+ }
1174
+ return s[e];
1175
+ }
1176
+ async getSigningKeys() {
1177
+ const e = this._logger.create("getSigningKeys");
1178
+ if (this._signingKeys)
1179
+ return e.debug("returning signingKeys from cache"), this._signingKeys;
1180
+ const t = await this.getKeysEndpoint(!1);
1181
+ e.debug("got jwks_uri", t);
1182
+ const r = await this._jsonService.getJson(t);
1183
+ if (e.debug("got key set", r), !Array.isArray(r.keys))
1184
+ throw e.throw(new Error("Missing keys on keyset")), null;
1185
+ return this._signingKeys = r.keys, this._signingKeys;
1186
+ }
1187
+ }, ye = class {
1188
+ constructor({
1189
+ prefix: e = "oidc.",
1190
+ store: t = localStorage
1191
+ } = {}) {
1192
+ this._logger = new m("WebStorageStateStore"), this._store = t, this._prefix = e;
1193
+ }
1194
+ async set(e, t) {
1195
+ this._logger.create(`set('${e}')`), e = this._prefix + e, await this._store.setItem(e, t);
1196
+ }
1197
+ async get(e) {
1198
+ return this._logger.create(`get('${e}')`), e = this._prefix + e, await this._store.getItem(e);
1199
+ }
1200
+ async remove(e) {
1201
+ this._logger.create(`remove('${e}')`), e = this._prefix + e;
1202
+ const t = await this._store.getItem(e);
1203
+ return await this._store.removeItem(e), t;
1204
+ }
1205
+ async getAllKeys() {
1206
+ this._logger.create("getAllKeys");
1207
+ const e = await this._store.length, t = [];
1208
+ for (let r = 0; r < e; r++) {
1209
+ const s = await this._store.key(r);
1210
+ s && s.indexOf(this._prefix) === 0 && t.push(s.substr(this._prefix.length));
1211
+ }
1212
+ return t;
1213
+ }
1214
+ }, It = "code", Ct = "openid", Ut = "client_secret_post", At = "query", Ot = 900, Pt = 300, we = class {
1215
+ constructor({
1216
+ // metadata related
1217
+ authority: e,
1218
+ metadataUrl: t,
1219
+ metadata: r,
1220
+ signingKeys: s,
1221
+ metadataSeed: i,
1222
+ // client related
1223
+ client_id: n,
1224
+ client_secret: o,
1225
+ response_type: l = It,
1226
+ scope: u = Ct,
1227
+ redirect_uri: g,
1228
+ post_logout_redirect_uri: _,
1229
+ client_authentication: h = Ut,
1230
+ // optional protocol
1231
+ prompt: b,
1232
+ display: w,
1233
+ max_age: k,
1234
+ ui_locales: p,
1235
+ acr_values: S,
1236
+ resource: T,
1237
+ response_mode: a = At,
1238
+ // behavior flags
1239
+ filterProtocolClaims: d = !0,
1240
+ loadUserInfo: f = !1,
1241
+ staleStateAgeInSeconds: v = Ot,
1242
+ clockSkewInSeconds: E = Pt,
1243
+ userInfoJwtIssuer: R = "OP",
1244
+ mergeClaims: x = !1,
1245
+ disablePKCE: I = !1,
1246
+ // other behavior
1247
+ stateStore: N,
1248
+ refreshTokenCredentials: O,
1249
+ revokeTokenAdditionalContentTypes: q,
1250
+ fetchRequestCredentials: H,
1251
+ refreshTokenAllowedScope: Y,
1252
+ // extra
1253
+ extraQueryParams: W = {},
1254
+ extraTokenParams: F = {},
1255
+ extraHeaders: $ = {}
1256
+ }) {
1257
+ if (this.authority = e, t ? this.metadataUrl = t : (this.metadataUrl = e, e && (this.metadataUrl.endsWith("/") || (this.metadataUrl += "/"), this.metadataUrl += ".well-known/openid-configuration")), this.metadata = r, this.metadataSeed = i, this.signingKeys = s, this.client_id = n, this.client_secret = o, this.response_type = l, this.scope = u, this.redirect_uri = g, this.post_logout_redirect_uri = _, this.client_authentication = h, this.prompt = b, this.display = w, this.max_age = k, this.ui_locales = p, this.acr_values = S, this.resource = T, this.response_mode = a, this.filterProtocolClaims = d ?? !0, this.loadUserInfo = !!f, this.staleStateAgeInSeconds = v, this.clockSkewInSeconds = E, this.userInfoJwtIssuer = R, this.mergeClaims = !!x, this.disablePKCE = !!I, this.revokeTokenAdditionalContentTypes = q, H && O && console.warn("Both fetchRequestCredentials and refreshTokenCredentials is set. Only fetchRequestCredentials will be used."), this.fetchRequestCredentials = H || O || "same-origin", N)
1258
+ this.stateStore = N;
1259
+ else {
1260
+ const z = typeof window < "u" ? window.localStorage : new He();
1261
+ this.stateStore = new ye({ store: z });
1262
+ }
1263
+ this.refreshTokenAllowedScope = Y, this.extraQueryParams = W, this.extraTokenParams = F, this.extraHeaders = $;
1264
+ }
1265
+ }, Nt = class {
1266
+ constructor(e, t) {
1267
+ this._settings = e, this._metadataService = t, this._logger = new m("UserInfoService"), this._getClaimsFromJwt = async (r) => {
1268
+ const s = this._logger.create("_getClaimsFromJwt");
1269
+ try {
1270
+ const i = _e.decode(r);
1271
+ return s.debug("JWT decoding successful"), i;
1272
+ } catch (i) {
1273
+ throw s.error("Error parsing JWT response"), i;
1274
+ }
1275
+ }, this._jsonService = new Se(
1276
+ void 0,
1277
+ this._getClaimsFromJwt,
1278
+ this._settings.extraHeaders
1279
+ );
1280
+ }
1281
+ async getClaims(e) {
1282
+ const t = this._logger.create("getClaims");
1283
+ e || this._logger.throw(new Error("No token passed"));
1284
+ const r = await this._metadataService.getUserInfoEndpoint();
1285
+ t.debug("got userinfo url", r);
1286
+ const s = await this._jsonService.getJson(r, {
1287
+ token: e,
1288
+ credentials: this._settings.fetchRequestCredentials
1289
+ });
1290
+ return t.debug("got claims", s), s;
1291
+ }
1292
+ }, De = class {
1293
+ constructor(e, t) {
1294
+ this._settings = e, this._metadataService = t, this._logger = new m("TokenClient"), this._jsonService = new Se(
1295
+ this._settings.revokeTokenAdditionalContentTypes,
1296
+ null,
1297
+ this._settings.extraHeaders
1298
+ );
1299
+ }
1300
+ /**
1301
+ * Exchange code.
1302
+ *
1303
+ * @see https://www.rfc-editor.org/rfc/rfc6749#section-4.1.3
1304
+ */
1305
+ async exchangeCode({
1306
+ grant_type: e = "authorization_code",
1307
+ redirect_uri: t = this._settings.redirect_uri,
1308
+ client_id: r = this._settings.client_id,
1309
+ client_secret: s = this._settings.client_secret,
1310
+ ...i
1311
+ }) {
1312
+ const n = this._logger.create("exchangeCode");
1313
+ r || n.throw(new Error("A client_id is required")), t || n.throw(new Error("A redirect_uri is required")), i.code || n.throw(new Error("A code is required"));
1314
+ const o = new URLSearchParams({ grant_type: e, redirect_uri: t });
1315
+ for (const [_, h] of Object.entries(i))
1316
+ h != null && o.set(_, h);
1317
+ let l;
1318
+ switch (this._settings.client_authentication) {
1319
+ case "client_secret_basic":
1320
+ if (!s)
1321
+ throw n.throw(new Error("A client_secret is required")), null;
1322
+ l = L.generateBasicAuth(r, s);
1323
+ break;
1324
+ case "client_secret_post":
1325
+ o.append("client_id", r), s && o.append("client_secret", s);
1326
+ break;
1327
+ }
1328
+ const u = await this._metadataService.getTokenEndpoint(!1);
1329
+ n.debug("got token endpoint");
1330
+ const g = await this._jsonService.postForm(u, { body: o, basicAuth: l, initCredentials: this._settings.fetchRequestCredentials });
1331
+ return n.debug("got response"), g;
1332
+ }
1333
+ /**
1334
+ * Exchange credentials.
1335
+ *
1336
+ * @see https://www.rfc-editor.org/rfc/rfc6749#section-4.3.2
1337
+ */
1338
+ async exchangeCredentials({
1339
+ grant_type: e = "password",
1340
+ client_id: t = this._settings.client_id,
1341
+ client_secret: r = this._settings.client_secret,
1342
+ scope: s = this._settings.scope,
1343
+ ...i
1344
+ }) {
1345
+ const n = this._logger.create("exchangeCredentials");
1346
+ t || n.throw(new Error("A client_id is required"));
1347
+ const o = new URLSearchParams({ grant_type: e, scope: s });
1348
+ for (const [_, h] of Object.entries(i))
1349
+ h != null && o.set(_, h);
1350
+ let l;
1351
+ switch (this._settings.client_authentication) {
1352
+ case "client_secret_basic":
1353
+ if (!r)
1354
+ throw n.throw(new Error("A client_secret is required")), null;
1355
+ l = L.generateBasicAuth(t, r);
1356
+ break;
1357
+ case "client_secret_post":
1358
+ o.append("client_id", t), r && o.append("client_secret", r);
1359
+ break;
1360
+ }
1361
+ const u = await this._metadataService.getTokenEndpoint(!1);
1362
+ n.debug("got token endpoint");
1363
+ const g = await this._jsonService.postForm(u, { body: o, basicAuth: l, initCredentials: this._settings.fetchRequestCredentials });
1364
+ return n.debug("got response"), g;
1365
+ }
1366
+ /**
1367
+ * Exchange a refresh token.
1368
+ *
1369
+ * @see https://www.rfc-editor.org/rfc/rfc6749#section-6
1370
+ */
1371
+ async exchangeRefreshToken({
1372
+ grant_type: e = "refresh_token",
1373
+ client_id: t = this._settings.client_id,
1374
+ client_secret: r = this._settings.client_secret,
1375
+ timeoutInSeconds: s,
1376
+ ...i
1377
+ }) {
1378
+ const n = this._logger.create("exchangeRefreshToken");
1379
+ t || n.throw(new Error("A client_id is required")), i.refresh_token || n.throw(new Error("A refresh_token is required"));
1380
+ const o = new URLSearchParams({ grant_type: e });
1381
+ for (const [_, h] of Object.entries(i))
1382
+ Array.isArray(h) ? h.forEach((b) => o.append(_, b)) : h != null && o.set(_, h);
1383
+ let l;
1384
+ switch (this._settings.client_authentication) {
1385
+ case "client_secret_basic":
1386
+ if (!r)
1387
+ throw n.throw(new Error("A client_secret is required")), null;
1388
+ l = L.generateBasicAuth(t, r);
1389
+ break;
1390
+ case "client_secret_post":
1391
+ o.append("client_id", t), r && o.append("client_secret", r);
1392
+ break;
1393
+ }
1394
+ const u = await this._metadataService.getTokenEndpoint(!1);
1395
+ n.debug("got token endpoint");
1396
+ const g = await this._jsonService.postForm(u, { body: o, basicAuth: l, timeoutInSeconds: s, initCredentials: this._settings.fetchRequestCredentials });
1397
+ return n.debug("got response"), g;
1398
+ }
1399
+ /**
1400
+ * Revoke an access or refresh token.
1401
+ *
1402
+ * @see https://datatracker.ietf.org/doc/html/rfc7009#section-2.1
1403
+ */
1404
+ async revoke(e) {
1405
+ var t;
1406
+ const r = this._logger.create("revoke");
1407
+ e.token || r.throw(new Error("A token is required"));
1408
+ const s = await this._metadataService.getRevocationEndpoint(!1);
1409
+ r.debug(`got revocation endpoint, revoking ${(t = e.token_type_hint) != null ? t : "default token type"}`);
1410
+ const i = new URLSearchParams();
1411
+ for (const [n, o] of Object.entries(e))
1412
+ o != null && i.set(n, o);
1413
+ i.set("client_id", this._settings.client_id), this._settings.client_secret && i.set("client_secret", this._settings.client_secret), await this._jsonService.postForm(s, { body: i }), r.debug("got response");
1414
+ }
1415
+ }, qt = class {
1416
+ constructor(e, t, r) {
1417
+ this._settings = e, this._metadataService = t, this._claimsService = r, this._logger = new m("ResponseValidator"), this._userInfoService = new Nt(this._settings, this._metadataService), this._tokenClient = new De(this._settings, this._metadataService);
1418
+ }
1419
+ async validateSigninResponse(e, t) {
1420
+ const r = this._logger.create("validateSigninResponse");
1421
+ this._processSigninState(e, t), r.debug("state processed"), await this._processCode(e, t), r.debug("code processed"), e.isOpenId && this._validateIdTokenAttributes(e), r.debug("tokens validated"), await this._processClaims(e, t?.skipUserInfo, e.isOpenId), r.debug("claims processed");
1422
+ }
1423
+ async validateCredentialsResponse(e, t) {
1424
+ const r = this._logger.create("validateCredentialsResponse");
1425
+ e.isOpenId && e.id_token && this._validateIdTokenAttributes(e), r.debug("tokens validated"), await this._processClaims(e, t, e.isOpenId), r.debug("claims processed");
1426
+ }
1427
+ async validateRefreshResponse(e, t) {
1428
+ var r, s;
1429
+ const i = this._logger.create("validateRefreshResponse");
1430
+ e.userState = t.data, (r = e.session_state) != null || (e.session_state = t.session_state), (s = e.scope) != null || (e.scope = t.scope), e.isOpenId && e.id_token && (this._validateIdTokenAttributes(e, t.id_token), i.debug("ID Token validated")), e.id_token || (e.id_token = t.id_token, e.profile = t.profile);
1431
+ const n = e.isOpenId && !!e.id_token;
1432
+ await this._processClaims(e, !1, n), i.debug("claims processed");
1433
+ }
1434
+ validateSignoutResponse(e, t) {
1435
+ const r = this._logger.create("validateSignoutResponse");
1436
+ if (t.id !== e.state && r.throw(new Error("State does not match")), r.debug("state validated"), e.userState = t.data, e.error)
1437
+ throw r.warn("Response was error", e.error), new B(e);
1438
+ }
1439
+ _processSigninState(e, t) {
1440
+ var r;
1441
+ const s = this._logger.create("_processSigninState");
1442
+ if (t.id !== e.state && s.throw(new Error("State does not match")), t.client_id || s.throw(new Error("No client_id on state")), t.authority || s.throw(new Error("No authority on state")), this._settings.authority !== t.authority && s.throw(new Error("authority mismatch on settings vs. signin state")), this._settings.client_id && this._settings.client_id !== t.client_id && s.throw(new Error("client_id mismatch on settings vs. signin state")), s.debug("state validated"), e.userState = t.data, e.url_state = t.url_state, (r = e.scope) != null || (e.scope = t.scope), e.error)
1443
+ throw s.warn("Response was error", e.error), new B(e);
1444
+ t.code_verifier && !e.code && s.throw(new Error("Expected code in response"));
1445
+ }
1446
+ async _processClaims(e, t = !1, r = !0) {
1447
+ const s = this._logger.create("_processClaims");
1448
+ if (e.profile = this._claimsService.filterProtocolClaims(e.profile), t || !this._settings.loadUserInfo || !e.access_token) {
1449
+ s.debug("not loading user info");
1450
+ return;
1451
+ }
1452
+ s.debug("loading user info");
1453
+ const i = await this._userInfoService.getClaims(e.access_token);
1454
+ s.debug("user info claims received from user info endpoint"), r && i.sub !== e.profile.sub && s.throw(new Error("subject from UserInfo response does not match subject in ID Token")), e.profile = this._claimsService.mergeClaims(e.profile, this._claimsService.filterProtocolClaims(i)), s.debug("user info claims received, updated profile:", e.profile);
1455
+ }
1456
+ async _processCode(e, t) {
1457
+ const r = this._logger.create("_processCode");
1458
+ if (e.code) {
1459
+ r.debug("Validating code");
1460
+ const s = await this._tokenClient.exchangeCode({
1461
+ client_id: t.client_id,
1462
+ client_secret: t.client_secret,
1463
+ code: e.code,
1464
+ redirect_uri: t.redirect_uri,
1465
+ code_verifier: t.code_verifier,
1466
+ ...t.extraTokenParams
1467
+ });
1468
+ Object.assign(e, s);
1469
+ } else
1470
+ r.debug("No code to process");
1471
+ }
1472
+ _validateIdTokenAttributes(e, t) {
1473
+ var r;
1474
+ const s = this._logger.create("_validateIdTokenAttributes");
1475
+ s.debug("decoding ID Token JWT");
1476
+ const i = _e.decode((r = e.id_token) != null ? r : "");
1477
+ if (i.sub || s.throw(new Error("ID Token is missing a subject claim")), t) {
1478
+ const n = _e.decode(t);
1479
+ i.sub !== n.sub && s.throw(new Error("sub in id_token does not match current sub")), i.auth_time && i.auth_time !== n.auth_time && s.throw(new Error("auth_time in id_token does not match original auth_time")), i.azp && i.azp !== n.azp && s.throw(new Error("azp in id_token does not match original azp")), !i.azp && n.azp && s.throw(new Error("azp not in id_token, but present in original id_token"));
1480
+ }
1481
+ e.profile = i;
1482
+ }
1483
+ }, G = class {
1484
+ constructor(e) {
1485
+ this.id = e.id || L.generateUUIDv4(), this.data = e.data, e.created && e.created > 0 ? this.created = e.created : this.created = P.getEpochTime(), this.request_type = e.request_type, this.url_state = e.url_state;
1486
+ }
1487
+ toStorageString() {
1488
+ return new m("State").create("toStorageString"), JSON.stringify({
1489
+ id: this.id,
1490
+ data: this.data,
1491
+ created: this.created,
1492
+ request_type: this.request_type,
1493
+ url_state: this.url_state
1494
+ });
1495
+ }
1496
+ static fromStorageString(e) {
1497
+ return m.createStatic("State", "fromStorageString"), new G(JSON.parse(e));
1498
+ }
1499
+ static async clearStaleState(e, t) {
1500
+ const r = m.createStatic("State", "clearStaleState"), s = P.getEpochTime() - t, i = await e.getAllKeys();
1501
+ r.debug("got keys", i);
1502
+ for (let n = 0; n < i.length; n++) {
1503
+ const o = i[n], l = await e.get(o);
1504
+ let u = !1;
1505
+ if (l)
1506
+ try {
1507
+ const g = G.fromStorageString(l);
1508
+ r.debug("got item from key:", o, g.created), g.created <= s && (u = !0);
1509
+ } catch (g) {
1510
+ r.error("Error parsing state for key:", o, g), u = !0;
1511
+ }
1512
+ else
1513
+ r.debug("no item in storage for key:", o), u = !0;
1514
+ u && (r.debug("removed item for key:", o), e.remove(o));
1515
+ }
1516
+ }
1517
+ }, be = class extends G {
1518
+ constructor(e) {
1519
+ super(e), e.code_verifier === !0 ? this.code_verifier = L.generateCodeVerifier() : e.code_verifier && (this.code_verifier = e.code_verifier), this.code_verifier && (this.code_challenge = L.generateCodeChallenge(this.code_verifier)), this.authority = e.authority, this.client_id = e.client_id, this.redirect_uri = e.redirect_uri, this.scope = e.scope, this.client_secret = e.client_secret, this.extraTokenParams = e.extraTokenParams, this.response_mode = e.response_mode, this.skipUserInfo = e.skipUserInfo;
1520
+ }
1521
+ toStorageString() {
1522
+ return new m("SigninState").create("toStorageString"), JSON.stringify({
1523
+ id: this.id,
1524
+ data: this.data,
1525
+ created: this.created,
1526
+ request_type: this.request_type,
1527
+ url_state: this.url_state,
1528
+ code_verifier: this.code_verifier,
1529
+ authority: this.authority,
1530
+ client_id: this.client_id,
1531
+ redirect_uri: this.redirect_uri,
1532
+ scope: this.scope,
1533
+ client_secret: this.client_secret,
1534
+ extraTokenParams: this.extraTokenParams,
1535
+ response_mode: this.response_mode,
1536
+ skipUserInfo: this.skipUserInfo
1537
+ });
1538
+ }
1539
+ static fromStorageString(e) {
1540
+ m.createStatic("SigninState", "fromStorageString");
1541
+ const t = JSON.parse(e);
1542
+ return new be(t);
1543
+ }
1544
+ }, Mt = class {
1545
+ constructor({
1546
+ // mandatory
1547
+ url: e,
1548
+ authority: t,
1549
+ client_id: r,
1550
+ redirect_uri: s,
1551
+ response_type: i,
1552
+ scope: n,
1553
+ // optional
1554
+ state_data: o,
1555
+ response_mode: l,
1556
+ request_type: u,
1557
+ client_secret: g,
1558
+ nonce: _,
1559
+ url_state: h,
1560
+ resource: b,
1561
+ skipUserInfo: w,
1562
+ extraQueryParams: k,
1563
+ extraTokenParams: p,
1564
+ disablePKCE: S,
1565
+ ...T
1566
+ }) {
1567
+ if (this._logger = new m("SigninRequest"), !e)
1568
+ throw this._logger.error("ctor: No url passed"), new Error("url");
1569
+ if (!r)
1570
+ throw this._logger.error("ctor: No client_id passed"), new Error("client_id");
1571
+ if (!s)
1572
+ throw this._logger.error("ctor: No redirect_uri passed"), new Error("redirect_uri");
1573
+ if (!i)
1574
+ throw this._logger.error("ctor: No response_type passed"), new Error("response_type");
1575
+ if (!n)
1576
+ throw this._logger.error("ctor: No scope passed"), new Error("scope");
1577
+ if (!t)
1578
+ throw this._logger.error("ctor: No authority passed"), new Error("authority");
1579
+ this.state = new be({
1580
+ data: o,
1581
+ request_type: u,
1582
+ url_state: h,
1583
+ code_verifier: !S,
1584
+ client_id: r,
1585
+ authority: t,
1586
+ redirect_uri: s,
1587
+ response_mode: l,
1588
+ client_secret: g,
1589
+ scope: n,
1590
+ extraTokenParams: p,
1591
+ skipUserInfo: w
1592
+ });
1593
+ const a = new URL(e);
1594
+ a.searchParams.append("client_id", r), a.searchParams.append("redirect_uri", s), a.searchParams.append("response_type", i), a.searchParams.append("scope", n), _ && a.searchParams.append("nonce", _);
1595
+ let d = this.state.id;
1596
+ h && (d = `${d}${pe}${h}`), a.searchParams.append("state", d), this.state.code_challenge && (a.searchParams.append("code_challenge", this.state.code_challenge), a.searchParams.append("code_challenge_method", "S256")), b && (Array.isArray(b) ? b : [b]).forEach((v) => a.searchParams.append("resource", v));
1597
+ for (const [f, v] of Object.entries({ response_mode: l, ...T, ...k }))
1598
+ v != null && a.searchParams.append(f, v.toString());
1599
+ this.url = a.href;
1600
+ }
1601
+ }, jt = "openid", he = class {
1602
+ constructor(e) {
1603
+ if (this.access_token = "", this.token_type = "", this.profile = {}, this.state = e.get("state"), this.session_state = e.get("session_state"), this.state) {
1604
+ const t = decodeURIComponent(this.state).split(pe);
1605
+ this.state = t[0], t.length > 1 && (this.url_state = t.slice(1).join(pe));
1606
+ }
1607
+ this.error = e.get("error"), this.error_description = e.get("error_description"), this.error_uri = e.get("error_uri"), this.code = e.get("code");
1608
+ }
1609
+ get expires_in() {
1610
+ if (this.expires_at !== void 0)
1611
+ return this.expires_at - P.getEpochTime();
1612
+ }
1613
+ set expires_in(e) {
1614
+ typeof e == "string" && (e = Number(e)), e !== void 0 && e >= 0 && (this.expires_at = Math.floor(e) + P.getEpochTime());
1615
+ }
1616
+ get isOpenId() {
1617
+ var e;
1618
+ return ((e = this.scope) == null ? void 0 : e.split(" ").includes(jt)) || !!this.id_token;
1619
+ }
1620
+ }, Lt = class {
1621
+ constructor({
1622
+ url: e,
1623
+ state_data: t,
1624
+ id_token_hint: r,
1625
+ post_logout_redirect_uri: s,
1626
+ extraQueryParams: i,
1627
+ request_type: n,
1628
+ client_id: o
1629
+ }) {
1630
+ if (this._logger = new m("SignoutRequest"), !e)
1631
+ throw this._logger.error("ctor: No url passed"), new Error("url");
1632
+ const l = new URL(e);
1633
+ r && l.searchParams.append("id_token_hint", r), o && l.searchParams.append("client_id", o), s && (l.searchParams.append("post_logout_redirect_uri", s), t && (this.state = new G({ data: t, request_type: n }), l.searchParams.append("state", this.state.id)));
1634
+ for (const [u, g] of Object.entries({ ...i }))
1635
+ g != null && l.searchParams.append(u, g.toString());
1636
+ this.url = l.href;
1637
+ }
1638
+ }, Ht = class {
1639
+ constructor(e) {
1640
+ this.state = e.get("state"), this.error = e.get("error"), this.error_description = e.get("error_description"), this.error_uri = e.get("error_uri");
1641
+ }
1642
+ }, Dt = [
1643
+ "nbf",
1644
+ "jti",
1645
+ "auth_time",
1646
+ "nonce",
1647
+ "acr",
1648
+ "amr",
1649
+ "azp",
1650
+ "at_hash"
1651
+ // https://openid.net/specs/openid-connect-core-1_0.html#CodeIDToken
1652
+ ], Wt = ["sub", "iss", "aud", "exp", "iat"], $t = class {
1653
+ constructor(e) {
1654
+ this._settings = e, this._logger = new m("ClaimsService");
1655
+ }
1656
+ filterProtocolClaims(e) {
1657
+ const t = { ...e };
1658
+ if (this._settings.filterProtocolClaims) {
1659
+ let r;
1660
+ Array.isArray(this._settings.filterProtocolClaims) ? r = this._settings.filterProtocolClaims : r = Dt;
1661
+ for (const s of r)
1662
+ Wt.includes(s) || delete t[s];
1663
+ }
1664
+ return t;
1665
+ }
1666
+ mergeClaims(e, t) {
1667
+ const r = { ...e };
1668
+ for (const [s, i] of Object.entries(t))
1669
+ for (const n of Array.isArray(i) ? i : [i]) {
1670
+ const o = r[s];
1671
+ o === void 0 ? r[s] = n : Array.isArray(o) ? o.includes(n) || o.push(n) : r[s] !== n && (typeof n == "object" && this._settings.mergeClaims ? r[s] = this.mergeClaims(o, n) : r[s] = [o, n]);
1672
+ }
1673
+ return r;
1674
+ }
1675
+ }, Bt = class {
1676
+ constructor(e, t) {
1677
+ this._logger = new m("OidcClient"), this.settings = e instanceof we ? e : new we(e), this.metadataService = t ?? new xt(this.settings), this._claimsService = new $t(this.settings), this._validator = new qt(this.settings, this.metadataService, this._claimsService), this._tokenClient = new De(this.settings, this.metadataService);
1678
+ }
1679
+ async createSigninRequest({
1680
+ state: e,
1681
+ request: t,
1682
+ request_uri: r,
1683
+ request_type: s,
1684
+ id_token_hint: i,
1685
+ login_hint: n,
1686
+ skipUserInfo: o,
1687
+ nonce: l,
1688
+ url_state: u,
1689
+ response_type: g = this.settings.response_type,
1690
+ scope: _ = this.settings.scope,
1691
+ redirect_uri: h = this.settings.redirect_uri,
1692
+ prompt: b = this.settings.prompt,
1693
+ display: w = this.settings.display,
1694
+ max_age: k = this.settings.max_age,
1695
+ ui_locales: p = this.settings.ui_locales,
1696
+ acr_values: S = this.settings.acr_values,
1697
+ resource: T = this.settings.resource,
1698
+ response_mode: a = this.settings.response_mode,
1699
+ extraQueryParams: d = this.settings.extraQueryParams,
1700
+ extraTokenParams: f = this.settings.extraTokenParams
1701
+ }) {
1702
+ const v = this._logger.create("createSigninRequest");
1703
+ if (g !== "code")
1704
+ throw new Error("Only the Authorization Code flow (with PKCE) is supported");
1705
+ const E = await this.metadataService.getAuthorizationEndpoint();
1706
+ v.debug("Received authorization endpoint", E);
1707
+ const R = new Mt({
1708
+ url: E,
1709
+ authority: this.settings.authority,
1710
+ client_id: this.settings.client_id,
1711
+ redirect_uri: h,
1712
+ response_type: g,
1713
+ scope: _,
1714
+ state_data: e,
1715
+ url_state: u,
1716
+ prompt: b,
1717
+ display: w,
1718
+ max_age: k,
1719
+ ui_locales: p,
1720
+ id_token_hint: i,
1721
+ login_hint: n,
1722
+ acr_values: S,
1723
+ resource: T,
1724
+ request: t,
1725
+ request_uri: r,
1726
+ extraQueryParams: d,
1727
+ extraTokenParams: f,
1728
+ request_type: s,
1729
+ response_mode: a,
1730
+ client_secret: this.settings.client_secret,
1731
+ skipUserInfo: o,
1732
+ nonce: l,
1733
+ disablePKCE: this.settings.disablePKCE
1734
+ });
1735
+ await this.clearStaleState();
1736
+ const x = R.state;
1737
+ return await this.settings.stateStore.set(x.id, x.toStorageString()), R;
1738
+ }
1739
+ async readSigninResponseState(e, t = !1) {
1740
+ const r = this._logger.create("readSigninResponseState"), s = new he(fe.readParams(e, this.settings.response_mode));
1741
+ if (!s.state)
1742
+ throw r.throw(new Error("No state in response")), null;
1743
+ const i = await this.settings.stateStore[t ? "remove" : "get"](s.state);
1744
+ if (!i)
1745
+ throw r.throw(new Error("No matching state found in storage")), null;
1746
+ return { state: be.fromStorageString(i), response: s };
1747
+ }
1748
+ async processSigninResponse(e) {
1749
+ const t = this._logger.create("processSigninResponse"), { state: r, response: s } = await this.readSigninResponseState(e, !0);
1750
+ return t.debug("received state from storage; validating response"), await this._validator.validateSigninResponse(s, r), s;
1751
+ }
1752
+ async processResourceOwnerPasswordCredentials({
1753
+ username: e,
1754
+ password: t,
1755
+ skipUserInfo: r = !1,
1756
+ extraTokenParams: s = {}
1757
+ }) {
1758
+ const i = await this._tokenClient.exchangeCredentials({ username: e, password: t, ...s }), n = new he(new URLSearchParams());
1759
+ return Object.assign(n, i), await this._validator.validateCredentialsResponse(n, r), n;
1760
+ }
1761
+ async useRefreshToken({
1762
+ state: e,
1763
+ timeoutInSeconds: t,
1764
+ extraTokenParams: r
1765
+ }) {
1766
+ var s;
1767
+ const i = this._logger.create("useRefreshToken");
1768
+ let n;
1769
+ if (this.settings.refreshTokenAllowedScope === void 0)
1770
+ n = e.scope;
1771
+ else {
1772
+ const u = this.settings.refreshTokenAllowedScope.split(" ");
1773
+ n = (((s = e.scope) == null ? void 0 : s.split(" ")) || []).filter((_) => u.includes(_)).join(" ");
1774
+ }
1775
+ const o = await this._tokenClient.exchangeRefreshToken({
1776
+ refresh_token: e.refresh_token,
1777
+ resource: e.resource,
1778
+ // provide the (possible filtered) scope list
1779
+ scope: n,
1780
+ timeoutInSeconds: t,
1781
+ ...r
1782
+ }), l = new he(new URLSearchParams());
1783
+ return Object.assign(l, o), i.debug("validating response", l), await this._validator.validateRefreshResponse(l, {
1784
+ ...e,
1785
+ // overide the scope in the state handed over to the validator
1786
+ // so it can set the granted scope to the requested scope in case none is included in the response
1787
+ scope: n
1788
+ }), l;
1789
+ }
1790
+ async createSignoutRequest({
1791
+ state: e,
1792
+ id_token_hint: t,
1793
+ client_id: r,
1794
+ request_type: s,
1795
+ post_logout_redirect_uri: i = this.settings.post_logout_redirect_uri,
1796
+ extraQueryParams: n = this.settings.extraQueryParams
1797
+ } = {}) {
1798
+ const o = this._logger.create("createSignoutRequest"), l = await this.metadataService.getEndSessionEndpoint();
1799
+ if (!l)
1800
+ throw o.throw(new Error("No end session endpoint")), null;
1801
+ o.debug("Received end session endpoint", l), !r && i && !t && (r = this.settings.client_id);
1802
+ const u = new Lt({
1803
+ url: l,
1804
+ id_token_hint: t,
1805
+ client_id: r,
1806
+ post_logout_redirect_uri: i,
1807
+ state_data: e,
1808
+ extraQueryParams: n,
1809
+ request_type: s
1810
+ });
1811
+ await this.clearStaleState();
1812
+ const g = u.state;
1813
+ return g && (o.debug("Signout request has state to persist"), await this.settings.stateStore.set(g.id, g.toStorageString())), u;
1814
+ }
1815
+ async readSignoutResponseState(e, t = !1) {
1816
+ const r = this._logger.create("readSignoutResponseState"), s = new Ht(fe.readParams(e, this.settings.response_mode));
1817
+ if (!s.state) {
1818
+ if (r.debug("No state in response"), s.error)
1819
+ throw r.warn("Response was error:", s.error), new B(s);
1820
+ return { state: void 0, response: s };
1821
+ }
1822
+ const i = await this.settings.stateStore[t ? "remove" : "get"](s.state);
1823
+ if (!i)
1824
+ throw r.throw(new Error("No matching state found in storage")), null;
1825
+ return { state: G.fromStorageString(i), response: s };
1826
+ }
1827
+ async processSignoutResponse(e) {
1828
+ const t = this._logger.create("processSignoutResponse"), { state: r, response: s } = await this.readSignoutResponseState(e, !0);
1829
+ return r ? (t.debug("Received state from storage; validating response"), this._validator.validateSignoutResponse(s, r)) : t.debug("No state from storage; skipping response validation"), s;
1830
+ }
1831
+ clearStaleState() {
1832
+ return this._logger.create("clearStaleState"), G.clearStaleState(this.settings.stateStore, this.settings.staleStateAgeInSeconds);
1833
+ }
1834
+ async revokeToken(e, t) {
1835
+ return this._logger.create("revokeToken"), await this._tokenClient.revoke({
1836
+ token: e,
1837
+ token_type_hint: t
1838
+ });
1839
+ }
1840
+ }, Ft = class {
1841
+ constructor(e) {
1842
+ this._userManager = e, this._logger = new m("SessionMonitor"), this._start = async (t) => {
1843
+ const r = t.session_state;
1844
+ if (!r)
1845
+ return;
1846
+ const s = this._logger.create("_start");
1847
+ if (t.profile ? (this._sub = t.profile.sub, this._sid = t.profile.sid, s.debug("session_state", r, ", sub", this._sub)) : (this._sub = void 0, this._sid = void 0, s.debug("session_state", r, ", anonymous user")), this._checkSessionIFrame) {
1848
+ this._checkSessionIFrame.start(r);
1849
+ return;
1850
+ }
1851
+ try {
1852
+ const i = await this._userManager.metadataService.getCheckSessionIframe();
1853
+ if (i) {
1854
+ s.debug("initializing check session iframe");
1855
+ const n = this._userManager.settings.client_id, o = this._userManager.settings.checkSessionIntervalInSeconds, l = this._userManager.settings.stopCheckSessionOnError, u = new Tt(this._callback, n, i, o, l);
1856
+ await u.load(), this._checkSessionIFrame = u, u.start(r);
1857
+ } else
1858
+ s.warn("no check session iframe found in the metadata");
1859
+ } catch (i) {
1860
+ s.error("Error from getCheckSessionIframe:", i instanceof Error ? i.message : i);
1861
+ }
1862
+ }, this._stop = () => {
1863
+ const t = this._logger.create("_stop");
1864
+ if (this._sub = void 0, this._sid = void 0, this._checkSessionIFrame && this._checkSessionIFrame.stop(), this._userManager.settings.monitorAnonymousSession) {
1865
+ const r = setInterval(async () => {
1866
+ clearInterval(r);
1867
+ try {
1868
+ const s = await this._userManager.querySessionStatus();
1869
+ if (s) {
1870
+ const i = {
1871
+ session_state: s.session_state,
1872
+ profile: s.sub && s.sid ? {
1873
+ sub: s.sub,
1874
+ sid: s.sid
1875
+ } : null
1876
+ };
1877
+ this._start(i);
1878
+ }
1879
+ } catch (s) {
1880
+ t.error("error from querySessionStatus", s instanceof Error ? s.message : s);
1881
+ }
1882
+ }, 1e3);
1883
+ }
1884
+ }, this._callback = async () => {
1885
+ const t = this._logger.create("_callback");
1886
+ try {
1887
+ const r = await this._userManager.querySessionStatus();
1888
+ let s = !0;
1889
+ r && this._checkSessionIFrame ? r.sub === this._sub ? (s = !1, this._checkSessionIFrame.start(r.session_state), r.sid === this._sid ? t.debug("same sub still logged in at OP, restarting check session iframe; session_state", r.session_state) : (t.debug("same sub still logged in at OP, session state has changed, restarting check session iframe; session_state", r.session_state), this._userManager.events._raiseUserSessionChanged())) : t.debug("different subject signed into OP", r.sub) : t.debug("subject no longer signed into OP"), s ? this._sub ? this._userManager.events._raiseUserSignedOut() : this._userManager.events._raiseUserSignedIn() : t.debug("no change in session detected, no event to raise");
1890
+ } catch (r) {
1891
+ this._sub && (t.debug("Error calling queryCurrentSigninSession; raising signed out event", r), this._userManager.events._raiseUserSignedOut());
1892
+ }
1893
+ }, e || this._logger.throw(new Error("No user manager passed")), this._userManager.events.addUserLoaded(this._start), this._userManager.events.addUserUnloaded(this._stop), this._init().catch((t) => {
1894
+ this._logger.error(t);
1895
+ });
1896
+ }
1897
+ async _init() {
1898
+ this._logger.create("_init");
1899
+ const e = await this._userManager.getUser();
1900
+ if (e)
1901
+ this._start(e);
1902
+ else if (this._userManager.settings.monitorAnonymousSession) {
1903
+ const t = await this._userManager.querySessionStatus();
1904
+ if (t) {
1905
+ const r = {
1906
+ session_state: t.session_state,
1907
+ profile: t.sub && t.sid ? {
1908
+ sub: t.sub,
1909
+ sid: t.sid
1910
+ } : null
1911
+ };
1912
+ this._start(r);
1913
+ }
1914
+ }
1915
+ }
1916
+ }, K = class {
1917
+ constructor(e) {
1918
+ var t;
1919
+ this.id_token = e.id_token, this.session_state = (t = e.session_state) != null ? t : null, this.access_token = e.access_token, this.refresh_token = e.refresh_token, this.token_type = e.token_type, this.scope = e.scope, this.profile = e.profile, this.expires_at = e.expires_at, this.state = e.userState, this.url_state = e.url_state;
1920
+ }
1921
+ /** Computed number of seconds the access token has remaining. */
1922
+ get expires_in() {
1923
+ if (this.expires_at !== void 0)
1924
+ return this.expires_at - P.getEpochTime();
1925
+ }
1926
+ set expires_in(e) {
1927
+ e !== void 0 && (this.expires_at = Math.floor(e) + P.getEpochTime());
1928
+ }
1929
+ /** Computed value indicating if the access token is expired. */
1930
+ get expired() {
1931
+ const e = this.expires_in;
1932
+ if (e !== void 0)
1933
+ return e <= 0;
1934
+ }
1935
+ /** Array representing the parsed values from the `scope`. */
1936
+ get scopes() {
1937
+ var e, t;
1938
+ return (t = (e = this.scope) == null ? void 0 : e.split(" ")) != null ? t : [];
1939
+ }
1940
+ toStorageString() {
1941
+ return new m("User").create("toStorageString"), JSON.stringify({
1942
+ id_token: this.id_token,
1943
+ session_state: this.session_state,
1944
+ access_token: this.access_token,
1945
+ refresh_token: this.refresh_token,
1946
+ token_type: this.token_type,
1947
+ scope: this.scope,
1948
+ profile: this.profile,
1949
+ expires_at: this.expires_at
1950
+ });
1951
+ }
1952
+ static fromStorageString(e) {
1953
+ return m.createStatic("User", "fromStorageString"), new K(JSON.parse(e));
1954
+ }
1955
+ }, Pe = "oidc-client", We = class {
1956
+ constructor() {
1957
+ this._abort = new D("Window navigation aborted"), this._disposeHandlers = /* @__PURE__ */ new Set(), this._window = null;
1958
+ }
1959
+ async navigate(e) {
1960
+ const t = this._logger.create("navigate");
1961
+ if (!this._window)
1962
+ throw new Error("Attempted to navigate on a disposed window");
1963
+ t.debug("setting URL in window"), this._window.location.replace(e.url);
1964
+ const { url: r, keepOpen: s } = await new Promise((i, n) => {
1965
+ const o = (l) => {
1966
+ var u;
1967
+ const g = l.data, _ = (u = e.scriptOrigin) != null ? u : window.location.origin;
1968
+ if (!(l.origin !== _ || g?.source !== Pe)) {
1969
+ try {
1970
+ const h = fe.readParams(g.url, e.response_mode).get("state");
1971
+ if (h || t.warn("no state found in response url"), l.source !== this._window && h !== e.state)
1972
+ return;
1973
+ } catch {
1974
+ this._dispose(), n(new Error("Invalid response from window"));
1975
+ }
1976
+ i(g);
1977
+ }
1978
+ };
1979
+ window.addEventListener("message", o, !1), this._disposeHandlers.add(() => window.removeEventListener("message", o, !1)), this._disposeHandlers.add(this._abort.addHandler((l) => {
1980
+ this._dispose(), n(l);
1981
+ }));
1982
+ });
1983
+ return t.debug("got response from window"), this._dispose(), s || this.close(), { url: r };
1984
+ }
1985
+ _dispose() {
1986
+ this._logger.create("_dispose");
1987
+ for (const e of this._disposeHandlers)
1988
+ e();
1989
+ this._disposeHandlers.clear();
1990
+ }
1991
+ static _notifyParent(e, t, r = !1, s = window.location.origin) {
1992
+ e.postMessage({
1993
+ source: Pe,
1994
+ url: t,
1995
+ keepOpen: r
1996
+ }, s);
1997
+ }
1998
+ }, $e = {
1999
+ location: !1,
2000
+ toolbar: !1,
2001
+ height: 640,
2002
+ closePopupWindowAfterInSeconds: -1
2003
+ }, Be = "_blank", zt = 60, Jt = 2, Fe = 10, Kt = class extends we {
2004
+ constructor(e) {
2005
+ const {
2006
+ popup_redirect_uri: t = e.redirect_uri,
2007
+ popup_post_logout_redirect_uri: r = e.post_logout_redirect_uri,
2008
+ popupWindowFeatures: s = $e,
2009
+ popupWindowTarget: i = Be,
2010
+ redirectMethod: n = "assign",
2011
+ redirectTarget: o = "self",
2012
+ iframeNotifyParentOrigin: l = e.iframeNotifyParentOrigin,
2013
+ iframeScriptOrigin: u = e.iframeScriptOrigin,
2014
+ silent_redirect_uri: g = e.redirect_uri,
2015
+ silentRequestTimeoutInSeconds: _ = Fe,
2016
+ automaticSilentRenew: h = !0,
2017
+ validateSubOnSilentRenew: b = !0,
2018
+ includeIdTokenInSilentRenew: w = !1,
2019
+ monitorSession: k = !1,
2020
+ monitorAnonymousSession: p = !1,
2021
+ checkSessionIntervalInSeconds: S = Jt,
2022
+ query_status_response_type: T = "code",
2023
+ stopCheckSessionOnError: a = !0,
2024
+ revokeTokenTypes: d = ["access_token", "refresh_token"],
2025
+ revokeTokensOnSignout: f = !1,
2026
+ includeIdTokenInSilentSignout: v = !1,
2027
+ accessTokenExpiringNotificationTimeInSeconds: E = zt,
2028
+ userStore: R
2029
+ } = e;
2030
+ if (super(e), this.popup_redirect_uri = t, this.popup_post_logout_redirect_uri = r, this.popupWindowFeatures = s, this.popupWindowTarget = i, this.redirectMethod = n, this.redirectTarget = o, this.iframeNotifyParentOrigin = l, this.iframeScriptOrigin = u, this.silent_redirect_uri = g, this.silentRequestTimeoutInSeconds = _, this.automaticSilentRenew = h, this.validateSubOnSilentRenew = b, this.includeIdTokenInSilentRenew = w, this.monitorSession = k, this.monitorAnonymousSession = p, this.checkSessionIntervalInSeconds = S, this.stopCheckSessionOnError = a, this.query_status_response_type = T, this.revokeTokenTypes = d, this.revokeTokensOnSignout = f, this.includeIdTokenInSilentSignout = v, this.accessTokenExpiringNotificationTimeInSeconds = E, R)
2031
+ this.userStore = R;
2032
+ else {
2033
+ const x = typeof window < "u" ? window.sessionStorage : new He();
2034
+ this.userStore = new ye({ store: x });
2035
+ }
2036
+ }
2037
+ }, ve = class extends We {
2038
+ constructor({
2039
+ silentRequestTimeoutInSeconds: e = Fe
2040
+ }) {
2041
+ super(), this._logger = new m("IFrameWindow"), this._timeoutInSeconds = e, this._frame = ve.createHiddenIframe(), this._window = this._frame.contentWindow;
2042
+ }
2043
+ static createHiddenIframe() {
2044
+ const e = window.document.createElement("iframe");
2045
+ return e.style.visibility = "hidden", e.style.position = "fixed", e.style.left = "-1000px", e.style.top = "0", e.width = "0", e.height = "0", window.document.body.appendChild(e), e;
2046
+ }
2047
+ async navigate(e) {
2048
+ this._logger.debug("navigate: Using timeout of:", this._timeoutInSeconds);
2049
+ const t = setTimeout(() => this._abort.raise(new me("IFrame timed out without a response")), this._timeoutInSeconds * 1e3);
2050
+ return this._disposeHandlers.add(() => clearTimeout(t)), await super.navigate(e);
2051
+ }
2052
+ close() {
2053
+ var e;
2054
+ this._frame && (this._frame.parentNode && (this._frame.addEventListener("load", (t) => {
2055
+ var r;
2056
+ const s = t.target;
2057
+ (r = s.parentNode) == null || r.removeChild(s), this._abort.raise(new Error("IFrame removed from DOM"));
2058
+ }, !0), (e = this._frame.contentWindow) == null || e.location.replace("about:blank")), this._frame = null), this._window = null;
2059
+ }
2060
+ static notifyParent(e, t) {
2061
+ return super._notifyParent(window.parent, e, !1, t);
2062
+ }
2063
+ }, Gt = class {
2064
+ constructor(e) {
2065
+ this._settings = e, this._logger = new m("IFrameNavigator");
2066
+ }
2067
+ async prepare({
2068
+ silentRequestTimeoutInSeconds: e = this._settings.silentRequestTimeoutInSeconds
2069
+ }) {
2070
+ return new ve({ silentRequestTimeoutInSeconds: e });
2071
+ }
2072
+ async callback(e) {
2073
+ this._logger.create("callback"), ve.notifyParent(e, this._settings.iframeNotifyParentOrigin);
2074
+ }
2075
+ }, Yt = 500, Vt = 1e3, Ne = class extends We {
2076
+ constructor({
2077
+ popupWindowTarget: e = Be,
2078
+ popupWindowFeatures: t = {}
2079
+ }) {
2080
+ super(), this._logger = new m("PopupWindow");
2081
+ const r = Oe.center({ ...$e, ...t });
2082
+ this._window = window.open(void 0, e, Oe.serialize(r)), t.closePopupWindowAfterInSeconds && t.closePopupWindowAfterInSeconds > 0 && setTimeout(() => {
2083
+ if (!this._window || typeof this._window.closed != "boolean" || this._window.closed) {
2084
+ this._abort.raise(new Error("Popup blocked by user"));
2085
+ return;
2086
+ }
2087
+ this.close();
2088
+ }, t.closePopupWindowAfterInSeconds * Vt);
2089
+ }
2090
+ async navigate(e) {
2091
+ var t;
2092
+ (t = this._window) == null || t.focus();
2093
+ const r = setInterval(() => {
2094
+ (!this._window || this._window.closed) && this._abort.raise(new Error("Popup closed by user"));
2095
+ }, Yt);
2096
+ return this._disposeHandlers.add(() => clearInterval(r)), await super.navigate(e);
2097
+ }
2098
+ close() {
2099
+ this._window && (this._window.closed || (this._window.close(), this._abort.raise(new Error("Popup closed")))), this._window = null;
2100
+ }
2101
+ static notifyOpener(e, t) {
2102
+ if (!window.opener)
2103
+ throw new Error("No window.opener. Can't complete notification.");
2104
+ return super._notifyParent(window.opener, e, t);
2105
+ }
2106
+ }, Xt = class {
2107
+ constructor(e) {
2108
+ this._settings = e, this._logger = new m("PopupNavigator");
2109
+ }
2110
+ async prepare({
2111
+ popupWindowFeatures: e = this._settings.popupWindowFeatures,
2112
+ popupWindowTarget: t = this._settings.popupWindowTarget
2113
+ }) {
2114
+ return new Ne({ popupWindowFeatures: e, popupWindowTarget: t });
2115
+ }
2116
+ async callback(e, { keepOpen: t = !1 }) {
2117
+ this._logger.create("callback"), Ne.notifyOpener(e, t);
2118
+ }
2119
+ }, Zt = class {
2120
+ constructor(e) {
2121
+ this._settings = e, this._logger = new m("RedirectNavigator");
2122
+ }
2123
+ async prepare({
2124
+ redirectMethod: e = this._settings.redirectMethod,
2125
+ redirectTarget: t = this._settings.redirectTarget
2126
+ }) {
2127
+ var r;
2128
+ this._logger.create("prepare");
2129
+ let s = window.self;
2130
+ t === "top" && (s = (r = window.top) != null ? r : window.self);
2131
+ const i = s.location[e].bind(s.location);
2132
+ let n;
2133
+ return {
2134
+ navigate: async (o) => {
2135
+ this._logger.create("navigate");
2136
+ const l = new Promise((u, g) => {
2137
+ n = g;
2138
+ });
2139
+ return i(o.url), await l;
2140
+ },
2141
+ close: () => {
2142
+ this._logger.create("close"), n?.(new Error("Redirect aborted")), s.stop();
2143
+ }
2144
+ };
2145
+ }
2146
+ async callback() {
2147
+ }
2148
+ }, Qt = class extends Rt {
2149
+ constructor(e) {
2150
+ super({ expiringNotificationTimeInSeconds: e.accessTokenExpiringNotificationTimeInSeconds }), this._logger = new m("UserManagerEvents"), this._userLoaded = new D("User loaded"), this._userUnloaded = new D("User unloaded"), this._silentRenewError = new D("Silent renew error"), this._userSignedIn = new D("User signed in"), this._userSignedOut = new D("User signed out"), this._userSessionChanged = new D("User session changed");
2151
+ }
2152
+ load(e, t = !0) {
2153
+ super.load(e), t && this._userLoaded.raise(e);
2154
+ }
2155
+ unload() {
2156
+ super.unload(), this._userUnloaded.raise();
2157
+ }
2158
+ /**
2159
+ * Add callback: Raised when a user session has been established (or re-established).
2160
+ */
2161
+ addUserLoaded(e) {
2162
+ return this._userLoaded.addHandler(e);
2163
+ }
2164
+ /**
2165
+ * Remove callback: Raised when a user session has been established (or re-established).
2166
+ */
2167
+ removeUserLoaded(e) {
2168
+ return this._userLoaded.removeHandler(e);
2169
+ }
2170
+ /**
2171
+ * Add callback: Raised when a user session has been terminated.
2172
+ */
2173
+ addUserUnloaded(e) {
2174
+ return this._userUnloaded.addHandler(e);
2175
+ }
2176
+ /**
2177
+ * Remove callback: Raised when a user session has been terminated.
2178
+ */
2179
+ removeUserUnloaded(e) {
2180
+ return this._userUnloaded.removeHandler(e);
2181
+ }
2182
+ /**
2183
+ * Add callback: Raised when the automatic silent renew has failed.
2184
+ */
2185
+ addSilentRenewError(e) {
2186
+ return this._silentRenewError.addHandler(e);
2187
+ }
2188
+ /**
2189
+ * Remove callback: Raised when the automatic silent renew has failed.
2190
+ */
2191
+ removeSilentRenewError(e) {
2192
+ return this._silentRenewError.removeHandler(e);
2193
+ }
2194
+ /**
2195
+ * @internal
2196
+ */
2197
+ _raiseSilentRenewError(e) {
2198
+ this._silentRenewError.raise(e);
2199
+ }
2200
+ /**
2201
+ * Add callback: Raised when the user is signed in (when `monitorSession` is set).
2202
+ * @see {@link UserManagerSettings.monitorSession}
2203
+ */
2204
+ addUserSignedIn(e) {
2205
+ return this._userSignedIn.addHandler(e);
2206
+ }
2207
+ /**
2208
+ * Remove callback: Raised when the user is signed in (when `monitorSession` is set).
2209
+ */
2210
+ removeUserSignedIn(e) {
2211
+ this._userSignedIn.removeHandler(e);
2212
+ }
2213
+ /**
2214
+ * @internal
2215
+ */
2216
+ _raiseUserSignedIn() {
2217
+ this._userSignedIn.raise();
2218
+ }
2219
+ /**
2220
+ * Add callback: Raised when the user's sign-in status at the OP has changed (when `monitorSession` is set).
2221
+ * @see {@link UserManagerSettings.monitorSession}
2222
+ */
2223
+ addUserSignedOut(e) {
2224
+ return this._userSignedOut.addHandler(e);
2225
+ }
2226
+ /**
2227
+ * Remove callback: Raised when the user's sign-in status at the OP has changed (when `monitorSession` is set).
2228
+ */
2229
+ removeUserSignedOut(e) {
2230
+ this._userSignedOut.removeHandler(e);
2231
+ }
2232
+ /**
2233
+ * @internal
2234
+ */
2235
+ _raiseUserSignedOut() {
2236
+ this._userSignedOut.raise();
2237
+ }
2238
+ /**
2239
+ * Add callback: Raised when the user session changed (when `monitorSession` is set).
2240
+ * @see {@link UserManagerSettings.monitorSession}
2241
+ */
2242
+ addUserSessionChanged(e) {
2243
+ return this._userSessionChanged.addHandler(e);
2244
+ }
2245
+ /**
2246
+ * Remove callback: Raised when the user session changed (when `monitorSession` is set).
2247
+ */
2248
+ removeUserSessionChanged(e) {
2249
+ this._userSessionChanged.removeHandler(e);
2250
+ }
2251
+ /**
2252
+ * @internal
2253
+ */
2254
+ _raiseUserSessionChanged() {
2255
+ this._userSessionChanged.raise();
2256
+ }
2257
+ }, er = class {
2258
+ constructor(e) {
2259
+ this._userManager = e, this._logger = new m("SilentRenewService"), this._isStarted = !1, this._retryTimer = new P("Retry Silent Renew"), this._tokenExpiring = async () => {
2260
+ const t = this._logger.create("_tokenExpiring");
2261
+ try {
2262
+ await this._userManager.signinSilent(), t.debug("silent token renewal successful");
2263
+ } catch (r) {
2264
+ if (r instanceof me) {
2265
+ t.warn("ErrorTimeout from signinSilent:", r, "retry in 5s"), this._retryTimer.init(5);
2266
+ return;
2267
+ }
2268
+ t.error("Error from signinSilent:", r), this._userManager.events._raiseSilentRenewError(r);
2269
+ }
2270
+ };
2271
+ }
2272
+ async start() {
2273
+ const e = this._logger.create("start");
2274
+ if (!this._isStarted) {
2275
+ this._isStarted = !0, this._userManager.events.addAccessTokenExpiring(this._tokenExpiring), this._retryTimer.addHandler(this._tokenExpiring);
2276
+ try {
2277
+ await this._userManager.getUser();
2278
+ } catch (t) {
2279
+ e.error("getUser error", t);
2280
+ }
2281
+ }
2282
+ }
2283
+ stop() {
2284
+ this._isStarted && (this._retryTimer.cancel(), this._retryTimer.removeHandler(this._tokenExpiring), this._userManager.events.removeAccessTokenExpiring(this._tokenExpiring), this._isStarted = !1);
2285
+ }
2286
+ }, tr = class {
2287
+ constructor(e, t) {
2288
+ this.refresh_token = e.refresh_token, this.id_token = e.id_token, this.session_state = e.session_state, this.scope = e.scope, this.profile = e.profile, this.resource = t, this.data = e.state;
2289
+ }
2290
+ }, rr = class {
2291
+ constructor(e, t, r, s) {
2292
+ this._logger = new m("UserManager"), this.settings = new Kt(e), this._client = new Bt(e), this._redirectNavigator = t ?? new Zt(this.settings), this._popupNavigator = r ?? new Xt(this.settings), this._iframeNavigator = s ?? new Gt(this.settings), this._events = new Qt(this.settings), this._silentRenewService = new er(this), this.settings.automaticSilentRenew && this.startSilentRenew(), this._sessionMonitor = null, this.settings.monitorSession && (this._sessionMonitor = new Ft(this));
2293
+ }
2294
+ /** Returns an object used to register for events raised by the `UserManager`. */
2295
+ get events() {
2296
+ return this._events;
2297
+ }
2298
+ /** Returns an object used to access the metadata configuration of the OIDC provider. */
2299
+ get metadataService() {
2300
+ return this._client.metadataService;
2301
+ }
2302
+ /**
2303
+ * Returns promise to load the `User` object for the currently authenticated user.
2304
+ */
2305
+ async getUser() {
2306
+ const e = this._logger.create("getUser"), t = await this._loadUser();
2307
+ return t ? (e.info("user loaded"), this._events.load(t, !1), t) : (e.info("user not found in storage"), null);
2308
+ }
2309
+ /**
2310
+ * Returns promise to remove from any storage the currently authenticated user.
2311
+ */
2312
+ async removeUser() {
2313
+ const e = this._logger.create("removeUser");
2314
+ await this.storeUser(null), e.info("user removed from storage"), this._events.unload();
2315
+ }
2316
+ /**
2317
+ * Returns promise to trigger a redirect of the current window to the authorization endpoint.
2318
+ */
2319
+ async signinRedirect(e = {}) {
2320
+ this._logger.create("signinRedirect");
2321
+ const {
2322
+ redirectMethod: t,
2323
+ ...r
2324
+ } = e, s = await this._redirectNavigator.prepare({ redirectMethod: t });
2325
+ await this._signinStart({
2326
+ request_type: "si:r",
2327
+ ...r
2328
+ }, s);
2329
+ }
2330
+ /**
2331
+ * Returns promise to process response from the authorization endpoint. The result of the promise is the authenticated `User`.
2332
+ */
2333
+ async signinRedirectCallback(e = window.location.href) {
2334
+ const t = this._logger.create("signinRedirectCallback"), r = await this._signinEnd(e);
2335
+ return r.profile && r.profile.sub ? t.info("success, signed in subject", r.profile.sub) : t.info("no subject"), r;
2336
+ }
2337
+ /**
2338
+ * Returns promise to process the signin with user/password. The result of the promise is the authenticated `User`.
2339
+ *
2340
+ * Throws an ErrorResponse in case of wrong authentication.
2341
+ */
2342
+ async signinResourceOwnerCredentials({
2343
+ username: e,
2344
+ password: t,
2345
+ skipUserInfo: r = !1
2346
+ }) {
2347
+ const s = this._logger.create("signinResourceOwnerCredential"), i = await this._client.processResourceOwnerPasswordCredentials({ username: e, password: t, skipUserInfo: r, extraTokenParams: this.settings.extraTokenParams });
2348
+ s.debug("got signin response");
2349
+ const n = await this._buildUser(i);
2350
+ return n.profile && n.profile.sub ? s.info("success, signed in subject", n.profile.sub) : s.info("no subject"), n;
2351
+ }
2352
+ /**
2353
+ * Returns promise to trigger a request (via a popup window) to the authorization endpoint. The result of the promise is the authenticated `User`.
2354
+ */
2355
+ async signinPopup(e = {}) {
2356
+ const t = this._logger.create("signinPopup"), {
2357
+ popupWindowFeatures: r,
2358
+ popupWindowTarget: s,
2359
+ ...i
2360
+ } = e, n = this.settings.popup_redirect_uri;
2361
+ n || t.throw(new Error("No popup_redirect_uri configured"));
2362
+ const o = await this._popupNavigator.prepare({ popupWindowFeatures: r, popupWindowTarget: s }), l = await this._signin({
2363
+ request_type: "si:p",
2364
+ redirect_uri: n,
2365
+ display: "popup",
2366
+ ...i
2367
+ }, o);
2368
+ return l && (l.profile && l.profile.sub ? t.info("success, signed in subject", l.profile.sub) : t.info("no subject")), l;
2369
+ }
2370
+ /**
2371
+ * Returns promise to notify the opening window of response from the authorization endpoint.
2372
+ */
2373
+ async signinPopupCallback(e = window.location.href, t = !1) {
2374
+ const r = this._logger.create("signinPopupCallback");
2375
+ await this._popupNavigator.callback(e, { keepOpen: t }), r.info("success");
2376
+ }
2377
+ /**
2378
+ * Returns promise to trigger a silent request (via an iframe) to the authorization endpoint.
2379
+ * The result of the promise is the authenticated `User`.
2380
+ */
2381
+ async signinSilent(e = {}) {
2382
+ var t;
2383
+ const r = this._logger.create("signinSilent"), {
2384
+ silentRequestTimeoutInSeconds: s,
2385
+ resource: i,
2386
+ ...n
2387
+ } = e;
2388
+ let o = await this._loadUser();
2389
+ if (o?.refresh_token) {
2390
+ r.debug("using refresh token");
2391
+ const _ = new tr(o, i);
2392
+ return await this._useRefreshToken({ state: _, extraTokenParams: n.extraTokenParams });
2393
+ }
2394
+ const l = this.settings.silent_redirect_uri;
2395
+ l || r.throw(new Error("No silent_redirect_uri configured"));
2396
+ let u;
2397
+ o && this.settings.validateSubOnSilentRenew && (r.debug("subject prior to silent renew:", o.profile.sub), u = o.profile.sub);
2398
+ const g = await this._iframeNavigator.prepare({ silentRequestTimeoutInSeconds: s });
2399
+ return o = await this._signin({
2400
+ request_type: "si:s",
2401
+ redirect_uri: l,
2402
+ prompt: "none",
2403
+ id_token_hint: this.settings.includeIdTokenInSilentRenew ? o?.id_token : void 0,
2404
+ ...n
2405
+ }, g, u), o && ((t = o.profile) != null && t.sub ? r.info("success, signed in subject", o.profile.sub) : r.info("no subject")), o;
2406
+ }
2407
+ async _useRefreshToken(e) {
2408
+ const t = await this._client.useRefreshToken({
2409
+ ...e,
2410
+ timeoutInSeconds: this.settings.silentRequestTimeoutInSeconds
2411
+ }), r = new K({ ...e.state, ...t });
2412
+ return await this.storeUser(r), this._events.load(r), r;
2413
+ }
2414
+ /**
2415
+ * Returns promise to notify the parent window of response from the authorization endpoint.
2416
+ */
2417
+ async signinSilentCallback(e = window.location.href) {
2418
+ const t = this._logger.create("signinSilentCallback");
2419
+ await this._iframeNavigator.callback(e), t.info("success");
2420
+ }
2421
+ async signinCallback(e = window.location.href) {
2422
+ const { state: t } = await this._client.readSigninResponseState(e);
2423
+ switch (t.request_type) {
2424
+ case "si:r":
2425
+ return await this.signinRedirectCallback(e);
2426
+ case "si:p":
2427
+ return await this.signinPopupCallback(e);
2428
+ case "si:s":
2429
+ return await this.signinSilentCallback(e);
2430
+ default:
2431
+ throw new Error("invalid response_type in state");
2432
+ }
2433
+ }
2434
+ async signoutCallback(e = window.location.href, t = !1) {
2435
+ const { state: r } = await this._client.readSignoutResponseState(e);
2436
+ if (r)
2437
+ switch (r.request_type) {
2438
+ case "so:r":
2439
+ return await this.signoutRedirectCallback(e);
2440
+ case "so:p":
2441
+ await this.signoutPopupCallback(e, t);
2442
+ break;
2443
+ case "so:s":
2444
+ await this.signoutSilentCallback(e);
2445
+ break;
2446
+ default:
2447
+ throw new Error("invalid response_type in state");
2448
+ }
2449
+ }
2450
+ /**
2451
+ * Returns promise to query OP for user's current signin status. Returns object with session_state and subject identifier.
2452
+ */
2453
+ async querySessionStatus(e = {}) {
2454
+ const t = this._logger.create("querySessionStatus"), {
2455
+ silentRequestTimeoutInSeconds: r,
2456
+ ...s
2457
+ } = e, i = this.settings.silent_redirect_uri;
2458
+ i || t.throw(new Error("No silent_redirect_uri configured"));
2459
+ const n = await this._loadUser(), o = await this._iframeNavigator.prepare({ silentRequestTimeoutInSeconds: r }), l = await this._signinStart({
2460
+ request_type: "si:s",
2461
+ // this acts like a signin silent
2462
+ redirect_uri: i,
2463
+ prompt: "none",
2464
+ id_token_hint: this.settings.includeIdTokenInSilentRenew ? n?.id_token : void 0,
2465
+ response_type: this.settings.query_status_response_type,
2466
+ scope: "openid",
2467
+ skipUserInfo: !0,
2468
+ ...s
2469
+ }, o);
2470
+ try {
2471
+ const u = await this._client.processSigninResponse(l.url);
2472
+ return t.debug("got signin response"), u.session_state && u.profile.sub ? (t.info("success for subject", u.profile.sub), {
2473
+ session_state: u.session_state,
2474
+ sub: u.profile.sub,
2475
+ sid: u.profile.sid
2476
+ }) : (t.info("success, user not authenticated"), null);
2477
+ } catch (u) {
2478
+ if (this.settings.monitorAnonymousSession && u instanceof B)
2479
+ switch (u.error) {
2480
+ case "login_required":
2481
+ case "consent_required":
2482
+ case "interaction_required":
2483
+ case "account_selection_required":
2484
+ return t.info("success for anonymous user"), {
2485
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2486
+ session_state: u.session_state
2487
+ };
2488
+ }
2489
+ throw u;
2490
+ }
2491
+ }
2492
+ async _signin(e, t, r) {
2493
+ const s = await this._signinStart(e, t);
2494
+ return await this._signinEnd(s.url, r);
2495
+ }
2496
+ async _signinStart(e, t) {
2497
+ const r = this._logger.create("_signinStart");
2498
+ try {
2499
+ const s = await this._client.createSigninRequest(e);
2500
+ return r.debug("got signin request"), await t.navigate({
2501
+ url: s.url,
2502
+ state: s.state.id,
2503
+ response_mode: s.state.response_mode,
2504
+ scriptOrigin: this.settings.iframeScriptOrigin
2505
+ });
2506
+ } catch (s) {
2507
+ throw r.debug("error after preparing navigator, closing navigator window"), t.close(), s;
2508
+ }
2509
+ }
2510
+ async _signinEnd(e, t) {
2511
+ const r = this._logger.create("_signinEnd"), s = await this._client.processSigninResponse(e);
2512
+ return r.debug("got signin response"), await this._buildUser(s, t);
2513
+ }
2514
+ async _buildUser(e, t) {
2515
+ const r = this._logger.create("_buildUser"), s = new K(e);
2516
+ if (t) {
2517
+ if (t !== s.profile.sub)
2518
+ throw r.debug("current user does not match user returned from signin. sub from signin:", s.profile.sub), new B({ ...e, error: "login_required" });
2519
+ r.debug("current user matches user returned from signin");
2520
+ }
2521
+ return await this.storeUser(s), r.debug("user stored"), this._events.load(s), s;
2522
+ }
2523
+ /**
2524
+ * Returns promise to trigger a redirect of the current window to the end session endpoint.
2525
+ */
2526
+ async signoutRedirect(e = {}) {
2527
+ const t = this._logger.create("signoutRedirect"), {
2528
+ redirectMethod: r,
2529
+ ...s
2530
+ } = e, i = await this._redirectNavigator.prepare({ redirectMethod: r });
2531
+ await this._signoutStart({
2532
+ request_type: "so:r",
2533
+ post_logout_redirect_uri: this.settings.post_logout_redirect_uri,
2534
+ ...s
2535
+ }, i), t.info("success");
2536
+ }
2537
+ /**
2538
+ * Returns promise to process response from the end session endpoint.
2539
+ */
2540
+ async signoutRedirectCallback(e = window.location.href) {
2541
+ const t = this._logger.create("signoutRedirectCallback"), r = await this._signoutEnd(e);
2542
+ return t.info("success"), r;
2543
+ }
2544
+ /**
2545
+ * Returns promise to trigger a redirect of a popup window window to the end session endpoint.
2546
+ */
2547
+ async signoutPopup(e = {}) {
2548
+ const t = this._logger.create("signoutPopup"), {
2549
+ popupWindowFeatures: r,
2550
+ popupWindowTarget: s,
2551
+ ...i
2552
+ } = e, n = this.settings.popup_post_logout_redirect_uri, o = await this._popupNavigator.prepare({ popupWindowFeatures: r, popupWindowTarget: s });
2553
+ await this._signout({
2554
+ request_type: "so:p",
2555
+ post_logout_redirect_uri: n,
2556
+ // we're putting a dummy entry in here because we
2557
+ // need a unique id from the state for notification
2558
+ // to the parent window, which is necessary if we
2559
+ // plan to return back to the client after signout
2560
+ // and so we can close the popup after signout
2561
+ state: n == null ? void 0 : {},
2562
+ ...i
2563
+ }, o), t.info("success");
2564
+ }
2565
+ /**
2566
+ * Returns promise to process response from the end session endpoint from a popup window.
2567
+ */
2568
+ async signoutPopupCallback(e = window.location.href, t = !1) {
2569
+ const r = this._logger.create("signoutPopupCallback");
2570
+ await this._popupNavigator.callback(e, { keepOpen: t }), r.info("success");
2571
+ }
2572
+ async _signout(e, t) {
2573
+ const r = await this._signoutStart(e, t);
2574
+ return await this._signoutEnd(r.url);
2575
+ }
2576
+ async _signoutStart(e = {}, t) {
2577
+ var r;
2578
+ const s = this._logger.create("_signoutStart");
2579
+ try {
2580
+ const i = await this._loadUser();
2581
+ s.debug("loaded current user from storage"), this.settings.revokeTokensOnSignout && await this._revokeInternal(i);
2582
+ const n = e.id_token_hint || i && i.id_token;
2583
+ n && (s.debug("setting id_token_hint in signout request"), e.id_token_hint = n), await this.removeUser(), s.debug("user removed, creating signout request");
2584
+ const o = await this._client.createSignoutRequest(e);
2585
+ return s.debug("got signout request"), await t.navigate({
2586
+ url: o.url,
2587
+ state: (r = o.state) == null ? void 0 : r.id,
2588
+ scriptOrigin: this.settings.iframeScriptOrigin
2589
+ });
2590
+ } catch (i) {
2591
+ throw s.debug("error after preparing navigator, closing navigator window"), t.close(), i;
2592
+ }
2593
+ }
2594
+ async _signoutEnd(e) {
2595
+ const t = this._logger.create("_signoutEnd"), r = await this._client.processSignoutResponse(e);
2596
+ return t.debug("got signout response"), r;
2597
+ }
2598
+ /**
2599
+ * Returns promise to trigger a silent request (via an iframe) to the end session endpoint.
2600
+ */
2601
+ async signoutSilent(e = {}) {
2602
+ var t;
2603
+ const r = this._logger.create("signoutSilent"), {
2604
+ silentRequestTimeoutInSeconds: s,
2605
+ ...i
2606
+ } = e, n = this.settings.includeIdTokenInSilentSignout ? (t = await this._loadUser()) == null ? void 0 : t.id_token : void 0, o = this.settings.popup_post_logout_redirect_uri, l = await this._iframeNavigator.prepare({ silentRequestTimeoutInSeconds: s });
2607
+ await this._signout({
2608
+ request_type: "so:s",
2609
+ post_logout_redirect_uri: o,
2610
+ id_token_hint: n,
2611
+ ...i
2612
+ }, l), r.info("success");
2613
+ }
2614
+ /**
2615
+ * Returns promise to notify the parent window of response from the end session endpoint.
2616
+ */
2617
+ async signoutSilentCallback(e = window.location.href) {
2618
+ const t = this._logger.create("signoutSilentCallback");
2619
+ await this._iframeNavigator.callback(e), t.info("success");
2620
+ }
2621
+ async revokeTokens(e) {
2622
+ const t = await this._loadUser();
2623
+ await this._revokeInternal(t, e);
2624
+ }
2625
+ async _revokeInternal(e, t = this.settings.revokeTokenTypes) {
2626
+ const r = this._logger.create("_revokeInternal");
2627
+ if (!e)
2628
+ return;
2629
+ const s = t.filter((i) => typeof e[i] == "string");
2630
+ if (!s.length) {
2631
+ r.debug("no need to revoke due to no token(s)");
2632
+ return;
2633
+ }
2634
+ for (const i of s)
2635
+ await this._client.revokeToken(
2636
+ e[i],
2637
+ // eslint-disable-line @typescript-eslint/no-non-null-assertion
2638
+ i
2639
+ ), r.info(`${i} revoked successfully`), i !== "access_token" && (e[i] = null);
2640
+ await this.storeUser(e), r.debug("user stored"), this._events.load(e);
2641
+ }
2642
+ /**
2643
+ * Enables silent renew for the `UserManager`.
2644
+ */
2645
+ startSilentRenew() {
2646
+ this._logger.create("startSilentRenew"), this._silentRenewService.start();
2647
+ }
2648
+ /**
2649
+ * Disables silent renew for the `UserManager`.
2650
+ */
2651
+ stopSilentRenew() {
2652
+ this._silentRenewService.stop();
2653
+ }
2654
+ get _userStoreKey() {
2655
+ return `user:${this.settings.authority}:${this.settings.client_id}`;
2656
+ }
2657
+ async _loadUser() {
2658
+ const e = this._logger.create("_loadUser"), t = await this.settings.userStore.get(this._userStoreKey);
2659
+ return t ? (e.debug("user storageString loaded"), K.fromStorageString(t)) : (e.debug("no user storageString"), null);
2660
+ }
2661
+ async storeUser(e) {
2662
+ const t = this._logger.create("storeUser");
2663
+ if (e) {
2664
+ t.debug("storing user");
2665
+ const r = e.toStorageString();
2666
+ await this.settings.userStore.set(this._userStoreKey, r);
2667
+ } else
2668
+ this._logger.debug("removing user"), await this.settings.userStore.remove(this._userStoreKey);
2669
+ }
2670
+ /**
2671
+ * Removes stale state entries in storage for incomplete authorize requests.
2672
+ */
2673
+ async clearStaleState() {
2674
+ await this._client.clearStaleState();
2675
+ }
2676
+ };
2677
+ const ze = (e) => {
2678
+ const t = e?.split(".")[1];
2679
+ if (!t) return null;
2680
+ const r = t.replace(/-/g, "+").replace(/_/g, "/"), s = decodeURIComponent(
2681
+ window.atob(r).split("").map(function(i) {
2682
+ return "%" + ("00" + i.charCodeAt(0).toString(16)).slice(-2);
2683
+ }).join("")
2684
+ );
2685
+ return JSON.parse(s);
2686
+ }, sr = (e) => e === null ? !1 : !!e.access_token && !e.expired, ir = () => {
2687
+ try {
2688
+ return window.location !== window.parent.location;
2689
+ } catch {
2690
+ return !0;
2691
+ }
2692
+ }, nr = () => {
2693
+ if (!ir() || !document.referrer) return !1;
2694
+ try {
2695
+ const { host: e } = new URL(document.referrer);
2696
+ return [
2697
+ /^uvadlo-.*\.instructure\.com$/,
2698
+ /^uvadlo-.*\.test\.instructure\.com$/,
2699
+ /^canvas\.instructure\.com$/
2700
+ ].some((t) => t.test(e));
2701
+ } catch {
2702
+ return !1;
2703
+ }
2704
+ }, qe = (e) => {
2705
+ const t = ze(e);
2706
+ if (!t) throw new Error("Error while logging in");
2707
+ const r = new K({
2708
+ access_token: e,
2709
+ token_type: "Bearer",
2710
+ profile: {
2711
+ iss: t.iss ?? "",
2712
+ sub: "",
2713
+ aud: "",
2714
+ exp: t.exp ?? 0,
2715
+ iat: t.iat ?? 0
2716
+ }
2717
+ });
2718
+ return r.expires_at = t.exp, { user: r, target: t.target, locale: t.locale };
2719
+ }, or = () => localStorage.getItem("canvas-token"), pr = (e) => {
2720
+ localStorage.setItem("canvas-token", e);
2721
+ }, V = (e) => e ? Object.assign({}, e) : null, wr = (e) => (ze(e?.access_token ?? "")?.impersonatedid ?? "") !== "", vr = (e) => e.user, mr = (e) => e.isLoading ? "pending" : "fulfilled", Sr = (e) => e.providerType, yr = (e) => e.isAuthenticated, Je = {
2722
+ user: null,
2723
+ providerType: null,
2724
+ isAuthenticated: !1,
2725
+ isLoading: !0,
2726
+ isLoggingOut: !1
2727
+ }, ar = [
2728
+ "auth/INITIALIZED",
2729
+ "auth/USER_LOADED",
2730
+ "auth/LOGOUT",
2731
+ "auth/USER_UNLOADED",
2732
+ "auth/LOGGING_OUT"
2733
+ ];
2734
+ function cr(e) {
2735
+ return ar.includes(e.type);
2736
+ }
2737
+ function lr(e = Je, t) {
2738
+ if (!cr(t))
2739
+ return e;
2740
+ switch (t.type) {
2741
+ case "auth/INITIALIZED":
2742
+ case "auth/USER_LOADED":
2743
+ return {
2744
+ ...e,
2745
+ user: t.user,
2746
+ providerType: t.providerType,
2747
+ isAuthenticated: t.user ? !!t.user.access_token && !t.user.expired : !1,
2748
+ isLoading: !1,
2749
+ isLoggingOut: !1
2750
+ };
2751
+ case "auth/LOGGING_OUT":
2752
+ return {
2753
+ ...e,
2754
+ isLoggingOut: !0
2755
+ };
2756
+ case "auth/LOGOUT":
2757
+ case "auth/USER_UNLOADED":
2758
+ return {
2759
+ ...e,
2760
+ user: null,
2761
+ isAuthenticated: !1,
2762
+ isLoggingOut: !0
2763
+ };
2764
+ default:
2765
+ return e;
2766
+ }
2767
+ }
2768
+ var ee = { exports: {} }, X = {};
2769
+ var Me;
2770
+ function ur() {
2771
+ if (Me) return X;
2772
+ Me = 1;
2773
+ var e = /* @__PURE__ */ Symbol.for("react.transitional.element"), t = /* @__PURE__ */ Symbol.for("react.fragment");
2774
+ function r(s, i, n) {
2775
+ var o = null;
2776
+ if (n !== void 0 && (o = "" + n), i.key !== void 0 && (o = "" + i.key), "key" in i) {
2777
+ n = {};
2778
+ for (var l in i)
2779
+ l !== "key" && (n[l] = i[l]);
2780
+ } else n = i;
2781
+ return i = n.ref, {
2782
+ $$typeof: e,
2783
+ type: s,
2784
+ key: o,
2785
+ ref: i !== void 0 ? i : null,
2786
+ props: n
2787
+ };
2788
+ }
2789
+ return X.Fragment = t, X.jsx = r, X.jsxs = r, X;
2790
+ }
2791
+ var Z = {};
2792
+ var je;
2793
+ function dr() {
2794
+ return je || (je = 1, process.env.NODE_ENV !== "production" && (function() {
2795
+ function e(c) {
2796
+ if (c == null) return null;
2797
+ if (typeof c == "function")
2798
+ return c.$$typeof === O ? null : c.displayName || c.name || null;
2799
+ if (typeof c == "string") return c;
2800
+ switch (c) {
2801
+ case S:
2802
+ return "Fragment";
2803
+ case a:
2804
+ return "Profiler";
2805
+ case T:
2806
+ return "StrictMode";
2807
+ case E:
2808
+ return "Suspense";
2809
+ case R:
2810
+ return "SuspenseList";
2811
+ case N:
2812
+ return "Activity";
2813
+ }
2814
+ if (typeof c == "object")
2815
+ switch (typeof c.tag == "number" && console.error(
2816
+ "Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."
2817
+ ), c.$$typeof) {
2818
+ case p:
2819
+ return "Portal";
2820
+ case f:
2821
+ return c.displayName || "Context";
2822
+ case d:
2823
+ return (c._context.displayName || "Context") + ".Consumer";
2824
+ case v:
2825
+ var y = c.render;
2826
+ return c = c.displayName, c || (c = y.displayName || y.name || "", c = c !== "" ? "ForwardRef(" + c + ")" : "ForwardRef"), c;
2827
+ case x:
2828
+ return y = c.displayName || null, y !== null ? y : e(c.type) || "Memo";
2829
+ case I:
2830
+ y = c._payload, c = c._init;
2831
+ try {
2832
+ return e(c(y));
2833
+ } catch {
2834
+ }
2835
+ }
2836
+ return null;
2837
+ }
2838
+ function t(c) {
2839
+ return "" + c;
2840
+ }
2841
+ function r(c) {
2842
+ try {
2843
+ t(c);
2844
+ var y = !1;
2845
+ } catch {
2846
+ y = !0;
2847
+ }
2848
+ if (y) {
2849
+ y = console;
2850
+ var C = y.error, U = typeof Symbol == "function" && Symbol.toStringTag && c[Symbol.toStringTag] || c.constructor.name || "Object";
2851
+ return C.call(
2852
+ y,
2853
+ "The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",
2854
+ U
2855
+ ), t(c);
2856
+ }
2857
+ }
2858
+ function s(c) {
2859
+ if (c === S) return "<>";
2860
+ if (typeof c == "object" && c !== null && c.$$typeof === I)
2861
+ return "<...>";
2862
+ try {
2863
+ var y = e(c);
2864
+ return y ? "<" + y + ">" : "<...>";
2865
+ } catch {
2866
+ return "<...>";
2867
+ }
2868
+ }
2869
+ function i() {
2870
+ var c = q.A;
2871
+ return c === null ? null : c.getOwner();
2872
+ }
2873
+ function n() {
2874
+ return Error("react-stack-top-frame");
2875
+ }
2876
+ function o(c) {
2877
+ if (H.call(c, "key")) {
2878
+ var y = Object.getOwnPropertyDescriptor(c, "key").get;
2879
+ if (y && y.isReactWarning) return !1;
2880
+ }
2881
+ return c.key !== void 0;
2882
+ }
2883
+ function l(c, y) {
2884
+ function C() {
2885
+ F || (F = !0, console.error(
2886
+ "%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",
2887
+ y
2888
+ ));
2889
+ }
2890
+ C.isReactWarning = !0, Object.defineProperty(c, "key", {
2891
+ get: C,
2892
+ configurable: !0
2893
+ });
2894
+ }
2895
+ function u() {
2896
+ var c = e(this.type);
2897
+ return $[c] || ($[c] = !0, console.error(
2898
+ "Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release."
2899
+ )), c = this.props.ref, c !== void 0 ? c : null;
2900
+ }
2901
+ function g(c, y, C, U, Q, le) {
2902
+ var A = C.ref;
2903
+ return c = {
2904
+ $$typeof: k,
2905
+ type: c,
2906
+ key: y,
2907
+ props: C,
2908
+ _owner: U
2909
+ }, (A !== void 0 ? A : null) !== null ? Object.defineProperty(c, "ref", {
2910
+ enumerable: !1,
2911
+ get: u
2912
+ }) : Object.defineProperty(c, "ref", { enumerable: !1, value: null }), c._store = {}, Object.defineProperty(c._store, "validated", {
2913
+ configurable: !1,
2914
+ enumerable: !1,
2915
+ writable: !0,
2916
+ value: 0
2917
+ }), Object.defineProperty(c, "_debugInfo", {
2918
+ configurable: !1,
2919
+ enumerable: !1,
2920
+ writable: !0,
2921
+ value: null
2922
+ }), Object.defineProperty(c, "_debugStack", {
2923
+ configurable: !1,
2924
+ enumerable: !1,
2925
+ writable: !0,
2926
+ value: Q
2927
+ }), Object.defineProperty(c, "_debugTask", {
2928
+ configurable: !1,
2929
+ enumerable: !1,
2930
+ writable: !0,
2931
+ value: le
2932
+ }), Object.freeze && (Object.freeze(c.props), Object.freeze(c)), c;
2933
+ }
2934
+ function _(c, y, C, U, Q, le) {
2935
+ var A = y.children;
2936
+ if (A !== void 0)
2937
+ if (U)
2938
+ if (Y(A)) {
2939
+ for (U = 0; U < A.length; U++)
2940
+ h(A[U]);
2941
+ Object.freeze && Object.freeze(A);
2942
+ } else
2943
+ console.error(
2944
+ "React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead."
2945
+ );
2946
+ else h(A);
2947
+ if (H.call(y, "key")) {
2948
+ A = e(c);
2949
+ var J = Object.keys(y).filter(function(Ke) {
2950
+ return Ke !== "key";
2951
+ });
2952
+ U = 0 < J.length ? "{key: someKey, " + J.join(": ..., ") + ": ...}" : "{key: someKey}", Re[A + U] || (J = 0 < J.length ? "{" + J.join(": ..., ") + ": ...}" : "{}", console.error(
2953
+ `A props object containing a "key" prop is being spread into JSX:
2954
+ let props = %s;
2955
+ <%s {...props} />
2956
+ React keys must be passed directly to JSX without using spread:
2957
+ let props = %s;
2958
+ <%s key={someKey} {...props} />`,
2959
+ U,
2960
+ A,
2961
+ J,
2962
+ A
2963
+ ), Re[A + U] = !0);
2964
+ }
2965
+ if (A = null, C !== void 0 && (r(C), A = "" + C), o(y) && (r(y.key), A = "" + y.key), "key" in y) {
2966
+ C = {};
2967
+ for (var ue in y)
2968
+ ue !== "key" && (C[ue] = y[ue]);
2969
+ } else C = y;
2970
+ return A && l(
2971
+ C,
2972
+ typeof c == "function" ? c.displayName || c.name || "Unknown" : c
2973
+ ), g(
2974
+ c,
2975
+ A,
2976
+ C,
2977
+ i(),
2978
+ Q,
2979
+ le
2980
+ );
2981
+ }
2982
+ function h(c) {
2983
+ b(c) ? c._store && (c._store.validated = 1) : typeof c == "object" && c !== null && c.$$typeof === I && (c._payload.status === "fulfilled" ? b(c._payload.value) && c._payload.value._store && (c._payload.value._store.validated = 1) : c._store && (c._store.validated = 1));
2984
+ }
2985
+ function b(c) {
2986
+ return typeof c == "object" && c !== null && c.$$typeof === k;
2987
+ }
2988
+ var w = Ge, k = /* @__PURE__ */ Symbol.for("react.transitional.element"), p = /* @__PURE__ */ Symbol.for("react.portal"), S = /* @__PURE__ */ Symbol.for("react.fragment"), T = /* @__PURE__ */ Symbol.for("react.strict_mode"), a = /* @__PURE__ */ Symbol.for("react.profiler"), d = /* @__PURE__ */ Symbol.for("react.consumer"), f = /* @__PURE__ */ Symbol.for("react.context"), v = /* @__PURE__ */ Symbol.for("react.forward_ref"), E = /* @__PURE__ */ Symbol.for("react.suspense"), R = /* @__PURE__ */ Symbol.for("react.suspense_list"), x = /* @__PURE__ */ Symbol.for("react.memo"), I = /* @__PURE__ */ Symbol.for("react.lazy"), N = /* @__PURE__ */ Symbol.for("react.activity"), O = /* @__PURE__ */ Symbol.for("react.client.reference"), q = w.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, H = Object.prototype.hasOwnProperty, Y = Array.isArray, W = console.createTask ? console.createTask : function() {
2989
+ return null;
2990
+ };
2991
+ w = {
2992
+ react_stack_bottom_frame: function(c) {
2993
+ return c();
2994
+ }
2995
+ };
2996
+ var F, $ = {}, z = w.react_stack_bottom_frame.bind(
2997
+ w,
2998
+ n
2999
+ )(), Ee = W(s(n)), Re = {};
3000
+ Z.Fragment = S, Z.jsx = function(c, y, C) {
3001
+ var U = 1e4 > q.recentlyCreatedOwnerStacks++;
3002
+ return _(
3003
+ c,
3004
+ y,
3005
+ C,
3006
+ !1,
3007
+ U ? Error("react-stack-top-frame") : z,
3008
+ U ? W(s(c)) : Ee
3009
+ );
3010
+ }, Z.jsxs = function(c, y, C) {
3011
+ var U = 1e4 > q.recentlyCreatedOwnerStacks++;
3012
+ return _(
3013
+ c,
3014
+ y,
3015
+ C,
3016
+ !0,
3017
+ U ? Error("react-stack-top-frame") : z,
3018
+ U ? W(s(c)) : Ee
3019
+ );
3020
+ };
3021
+ })()), Z;
3022
+ }
3023
+ var Le;
3024
+ function hr() {
3025
+ return Le || (Le = 1, process.env.NODE_ENV === "production" ? ee.exports = ur() : ee.exports = dr()), ee.exports;
3026
+ }
3027
+ var gr = hr();
3028
+ const ke = Ye(void 0);
3029
+ ke.displayName = "AuthContext";
3030
+ class _r {
3031
+ initialized = !1;
3032
+ loginInProgress = !1;
3033
+ logoutUri;
3034
+ updateState;
3035
+ userManager;
3036
+ constructor(t) {
3037
+ this.logoutUri = t.logoutUri, this.userManager = new rr({
3038
+ authority: t.authority,
3039
+ // With silent renew enabled it would redirect to the callback URL on token-expiry, which we don't support right now.
3040
+ automaticSilentRenew: !1,
3041
+ client_id: t.clientId,
3042
+ redirect_uri: t.redirectUri,
3043
+ response_type: "code",
3044
+ scope: "openid profile",
3045
+ // Use `localStorage` for storage instead of the default `sessionStorage`. `sessionStorage` is unique between tabs
3046
+ // which means that the user needs to log in for every open tab.
3047
+ userStore: new ye({ store: localStorage })
3048
+ });
3049
+ }
3050
+ async initialize(t, r) {
3051
+ if (!this.initialized)
3052
+ if (this.updateState = t, this.initEvents(r), this.initialized = !0, nr()) {
3053
+ const s = this.initCanvasUser();
3054
+ this.updateState({ type: "auth/INITIALIZED", user: s, providerType: "canvas" }), s && r.onUserLoaded?.(s);
3055
+ } else {
3056
+ const [s] = await Promise.all([
3057
+ this.userManager.getUser(),
3058
+ this.userManager.clearStaleState()
3059
+ ]), i = s && !s.expired ? s : null;
3060
+ this.updateState({
3061
+ type: "auth/INITIALIZED",
3062
+ user: V(i),
3063
+ providerType: "surf"
3064
+ }), i && r.onUserLoaded?.(i);
3065
+ }
3066
+ }
3067
+ surfStartLogin = async (t) => {
3068
+ if (!this.loginInProgress) {
3069
+ this.loginInProgress = !0;
3070
+ try {
3071
+ await this.userManager.signinRedirect({ state: t });
3072
+ } catch (r) {
3073
+ throw this.loginInProgress = !1, r;
3074
+ }
3075
+ }
3076
+ };
3077
+ surfCompleteLogin = () => this.userManager.signinRedirectCallback();
3078
+ canvasCompleteLogin = (t) => {
3079
+ const r = qe(t);
3080
+ return this.updateState?.({
3081
+ type: "auth/USER_LOADED",
3082
+ user: V(r.user),
3083
+ providerType: "canvas"
3084
+ }), r;
3085
+ };
3086
+ surfRenewLogin = async (t) => {
3087
+ await this.userManager.removeUser(), await this.surfStartLogin(t);
3088
+ };
3089
+ surfLogout = async () => {
3090
+ this.updateState?.({ type: "auth/LOGGING_OUT" }), await this.userManager.removeUser(), this.logoutUri && (window.location.href = this.logoutUri);
3091
+ };
3092
+ impersonateSurfUser = async (t) => {
3093
+ const r = await this.userManager.getUser();
3094
+ if (!r) return;
3095
+ const s = new K({ ...r, access_token: t });
3096
+ await this.userManager.storeUser(s), this.updateState?.({
3097
+ type: "auth/USER_LOADED",
3098
+ user: V(s),
3099
+ // As the OIDC client is only used for SURF, any USER_LOADED event must be for SURF
3100
+ providerType: "surf"
3101
+ });
3102
+ };
3103
+ initCanvasUser = () => {
3104
+ const t = or();
3105
+ if (!t) return null;
3106
+ const { user: r } = qe(t);
3107
+ return r.expired ? null : V(r);
3108
+ };
3109
+ initEvents(t) {
3110
+ t.onAccessTokenExpired && this.userManager.events.addAccessTokenExpired(t.onAccessTokenExpired), t.onAccessTokenExpiring && this.userManager.events.addAccessTokenExpiring(t.onAccessTokenExpiring), t.onSilentRenewError && this.userManager.events.addSilentRenewError(t.onSilentRenewError), this.userManager.events.addUserLoaded((r) => {
3111
+ sr(r) && this.updateState?.({
3112
+ type: "auth/USER_LOADED",
3113
+ user: V(r),
3114
+ // As the OIDC client is only used for SURF, any USER_LOADED event must be for SURF
3115
+ providerType: "surf"
3116
+ }), t?.onUserLoaded?.(r);
3117
+ }), t.onUserSessionChanged && this.userManager.events.addUserSessionChanged(t.onUserSessionChanged), t.onUserSignedIn && this.userManager.events.addUserSignedIn(t.onUserSignedIn), t.onUserSignedOut && this.userManager.events.addUserSignedOut(t.onUserSignedOut), this.userManager.events.addUserUnloaded(() => {
3118
+ this.updateState?.({ type: "auth/USER_UNLOADED" }), t?.onUserUnloaded?.();
3119
+ });
3120
+ }
3121
+ }
3122
+ const br = (e) => {
3123
+ const [t] = Ve(() => new _r(e.config)), [r, s] = Xe(lr, Je), i = Ze(!1);
3124
+ Qe(() => {
3125
+ !t || i.current || (i.current = !0, (async () => await t.initialize((o) => s(o), e.events))());
3126
+ }, [t, e.events]);
3127
+ const n = et(() => ({
3128
+ ...r,
3129
+ surfStartLogin: t.surfStartLogin,
3130
+ surfCompleteLogin: t.surfCompleteLogin,
3131
+ canvasCompleteLogin: t.canvasCompleteLogin,
3132
+ surfRenewLogin: t.surfRenewLogin,
3133
+ surfLogout: t.surfLogout,
3134
+ impersonateSurfUser: t.impersonateSurfUser
3135
+ }), [r, t]);
3136
+ return /* @__PURE__ */ gr.jsx(ke.Provider, { value: n, children: e.children });
3137
+ }, kr = () => {
3138
+ const e = tt(ke);
3139
+ if (!e)
3140
+ throw new Error("useAuth must be used within an <AuthProvider>.");
3141
+ return e;
3142
+ };
3143
+ export {
3144
+ br as AuthProvider,
3145
+ _r as AuthService,
3146
+ lr as authReducer,
3147
+ V as convertUserToObject,
3148
+ or as getCanvasTokenFromLocalStorage,
3149
+ ze as getDataFromToken,
3150
+ qe as getUserAndMetadataForCanvasToken,
3151
+ ir as isEmbedded,
3152
+ nr as isEmbeddedInCanvas,
3153
+ wr as isImpersonating,
3154
+ sr as isUserAuthenticated,
3155
+ Sr as selectAuthProviderType,
3156
+ mr as selectAuthStatus,
3157
+ vr as selectAuthUser,
3158
+ yr as selectIsAuthenticated,
3159
+ pr as setCanvasTokenInLocalStorage,
3160
+ kr as useAuth
3161
+ };