@opensourcekd/ng-common-libs 1.2.3 → 1.2.5

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.
package/dist/index.cjs CHANGED
@@ -3,7 +3,6 @@
3
3
  var rxjs = require('rxjs');
4
4
  var operators = require('rxjs/operators');
5
5
  var core = require('@angular/core');
6
- var router = require('@angular/router');
7
6
  var http = require('@angular/common/http');
8
7
 
9
8
  /**
@@ -63,531 +62,6 @@ class EventBus {
63
62
  }
64
63
  }
65
64
 
66
- /**
67
- * TokenManager - Manages authentication tokens
68
- * Framework-agnostic implementation using browser storage APIs
69
- * Handles storage, retrieval, and validation of JWT tokens
70
- *
71
- * @example
72
- * ```typescript
73
- * const tokenManager = new TokenManager();
74
- *
75
- * // Store a token
76
- * tokenManager.setToken('your-jwt-token');
77
- *
78
- * // Check if authenticated
79
- * if (tokenManager.isAuthenticated()) {
80
- * const userData = tokenManager.getUserFromToken();
81
- * }
82
- * ```
83
- */
84
- class TokenManager {
85
- TOKEN_KEY = 'auth_token';
86
- REFRESH_TOKEN_KEY = 'refresh_token';
87
- useSessionStorage = false;
88
- /**
89
- * Configure token manager
90
- */
91
- configure(config) {
92
- if (config.tokenKey) {
93
- this.TOKEN_KEY = config.tokenKey;
94
- }
95
- if (config.refreshTokenKey) {
96
- this.REFRESH_TOKEN_KEY = config.refreshTokenKey;
97
- }
98
- if (config.useSessionStorage !== undefined) {
99
- this.useSessionStorage = config.useSessionStorage;
100
- }
101
- }
102
- /**
103
- * Get the storage mechanism based on configuration
104
- */
105
- getStorage() {
106
- return this.useSessionStorage ? sessionStorage : localStorage;
107
- }
108
- /**
109
- * Set authentication token
110
- */
111
- setToken(token) {
112
- this.getStorage().setItem(this.TOKEN_KEY, token);
113
- }
114
- /**
115
- * Get authentication token
116
- */
117
- getToken() {
118
- return this.getStorage().getItem(this.TOKEN_KEY);
119
- }
120
- /**
121
- * Remove authentication token
122
- */
123
- removeToken() {
124
- this.getStorage().removeItem(this.TOKEN_KEY);
125
- }
126
- /**
127
- * Set refresh token
128
- */
129
- setRefreshToken(token) {
130
- this.getStorage().setItem(this.REFRESH_TOKEN_KEY, token);
131
- }
132
- /**
133
- * Get refresh token
134
- */
135
- getRefreshToken() {
136
- return this.getStorage().getItem(this.REFRESH_TOKEN_KEY);
137
- }
138
- /**
139
- * Remove refresh token
140
- */
141
- removeRefreshToken() {
142
- this.getStorage().removeItem(this.REFRESH_TOKEN_KEY);
143
- }
144
- /**
145
- * Clear all tokens
146
- */
147
- clearTokens() {
148
- this.removeToken();
149
- this.removeRefreshToken();
150
- }
151
- /**
152
- * Check if token exists
153
- */
154
- hasToken() {
155
- return !!this.getToken();
156
- }
157
- /**
158
- * Decode JWT token (without verification)
159
- * @param token - JWT token to decode
160
- * @returns Decoded token payload or null if invalid
161
- */
162
- decodeToken(token) {
163
- const tokenToDecode = token || this.getToken();
164
- if (!tokenToDecode)
165
- return null;
166
- try {
167
- const parts = tokenToDecode.split('.');
168
- if (parts.length !== 3)
169
- return null;
170
- const payload = parts[1];
171
- const decoded = JSON.parse(atob(payload.replace(/-/g, '+').replace(/_/g, '/')));
172
- return decoded;
173
- }
174
- catch (error) {
175
- console.error('Error decoding token:', error);
176
- return null;
177
- }
178
- }
179
- /**
180
- * Check if token is expired
181
- * @param token - Optional token to check (defaults to stored token)
182
- * @returns true if token is expired or invalid
183
- */
184
- isTokenExpired(token) {
185
- const decoded = this.decodeToken(token);
186
- if (!decoded || !decoded.exp)
187
- return true;
188
- const expirationDate = new Date(decoded.exp * 1000);
189
- return expirationDate <= new Date();
190
- }
191
- /**
192
- * Check if user is authenticated (has valid, non-expired token)
193
- */
194
- isAuthenticated() {
195
- return this.hasToken() && !this.isTokenExpired();
196
- }
197
- /**
198
- * Get token expiration date
199
- */
200
- getTokenExpirationDate(token) {
201
- const decoded = this.decodeToken(token);
202
- if (!decoded || !decoded.exp)
203
- return null;
204
- return new Date(decoded.exp * 1000);
205
- }
206
- /**
207
- * Get user data from token
208
- */
209
- getUserFromToken(token) {
210
- return this.decodeToken(token);
211
- }
212
- }
213
-
214
- /**
215
- * StorageManager - Type-safe wrapper for browser storage
216
- * Framework-agnostic implementation using browser storage APIs
217
- * Provides JSON serialization/deserialization and error handling
218
- *
219
- * @example
220
- * ```typescript
221
- * const storage = new StorageManager();
222
- *
223
- * // Store data
224
- * storage.setLocal('user-prefs', { theme: 'dark', lang: 'en' });
225
- *
226
- * // Retrieve data
227
- * const prefs = storage.getLocal('user-prefs');
228
- *
229
- * // With expiration
230
- * storage.setWithExpiration('temp-data', someData, 3600000); // 1 hour
231
- * ```
232
- */
233
- class StorageManager {
234
- /**
235
- * Set item in localStorage with JSON serialization
236
- */
237
- setLocal(key, value) {
238
- try {
239
- const serialized = JSON.stringify(value);
240
- localStorage.setItem(key, serialized);
241
- return true;
242
- }
243
- catch (error) {
244
- console.error('Error setting localStorage item:', error);
245
- return false;
246
- }
247
- }
248
- /**
249
- * Get item from localStorage with JSON deserialization
250
- */
251
- getLocal(key, defaultValue) {
252
- try {
253
- const item = localStorage.getItem(key);
254
- if (item === null) {
255
- return defaultValue !== undefined ? defaultValue : null;
256
- }
257
- return JSON.parse(item);
258
- }
259
- catch (error) {
260
- console.error('Error getting localStorage item:', error);
261
- return defaultValue !== undefined ? defaultValue : null;
262
- }
263
- }
264
- /**
265
- * Remove item from localStorage
266
- */
267
- removeLocal(key) {
268
- try {
269
- localStorage.removeItem(key);
270
- }
271
- catch (error) {
272
- console.error('Error removing localStorage item:', error);
273
- }
274
- }
275
- /**
276
- * Clear all localStorage items
277
- */
278
- clearLocal() {
279
- try {
280
- localStorage.clear();
281
- }
282
- catch (error) {
283
- console.error('Error clearing localStorage:', error);
284
- }
285
- }
286
- /**
287
- * Check if key exists in localStorage
288
- */
289
- hasLocal(key) {
290
- try {
291
- return localStorage.getItem(key) !== null;
292
- }
293
- catch (error) {
294
- console.error('Error checking localStorage key:', error);
295
- return false;
296
- }
297
- }
298
- /**
299
- * Get all localStorage keys
300
- */
301
- getLocalKeys() {
302
- try {
303
- return Object.keys(localStorage);
304
- }
305
- catch (error) {
306
- console.error('Error getting localStorage keys:', error);
307
- return [];
308
- }
309
- }
310
- /**
311
- * Set item in sessionStorage with JSON serialization
312
- */
313
- setSession(key, value) {
314
- try {
315
- const serialized = JSON.stringify(value);
316
- sessionStorage.setItem(key, serialized);
317
- return true;
318
- }
319
- catch (error) {
320
- console.error('Error setting sessionStorage item:', error);
321
- return false;
322
- }
323
- }
324
- /**
325
- * Get item from sessionStorage with JSON deserialization
326
- */
327
- getSession(key, defaultValue) {
328
- try {
329
- const item = sessionStorage.getItem(key);
330
- if (item === null) {
331
- return defaultValue !== undefined ? defaultValue : null;
332
- }
333
- return JSON.parse(item);
334
- }
335
- catch (error) {
336
- console.error('Error getting sessionStorage item:', error);
337
- return defaultValue !== undefined ? defaultValue : null;
338
- }
339
- }
340
- /**
341
- * Remove item from sessionStorage
342
- */
343
- removeSession(key) {
344
- try {
345
- sessionStorage.removeItem(key);
346
- }
347
- catch (error) {
348
- console.error('Error removing sessionStorage item:', error);
349
- }
350
- }
351
- /**
352
- * Clear all sessionStorage items
353
- */
354
- clearSession() {
355
- try {
356
- sessionStorage.clear();
357
- }
358
- catch (error) {
359
- console.error('Error clearing sessionStorage:', error);
360
- }
361
- }
362
- /**
363
- * Check if key exists in sessionStorage
364
- */
365
- hasSession(key) {
366
- try {
367
- return sessionStorage.getItem(key) !== null;
368
- }
369
- catch (error) {
370
- console.error('Error checking sessionStorage key:', error);
371
- return false;
372
- }
373
- }
374
- /**
375
- * Get all sessionStorage keys
376
- */
377
- getSessionKeys() {
378
- try {
379
- return Object.keys(sessionStorage);
380
- }
381
- catch (error) {
382
- console.error('Error getting sessionStorage keys:', error);
383
- return [];
384
- }
385
- }
386
- /**
387
- * Set item with expiration time
388
- * @param key - Storage key
389
- * @param value - Value to store
390
- * @param expirationMs - Expiration time in milliseconds
391
- * @param useSession - Use sessionStorage instead of localStorage
392
- */
393
- setWithExpiration(key, value, expirationMs, useSession = false) {
394
- const item = {
395
- value,
396
- expiration: Date.now() + expirationMs
397
- };
398
- return useSession
399
- ? this.setSession(key, item)
400
- : this.setLocal(key, item);
401
- }
402
- /**
403
- * Get item with expiration check
404
- * Returns null if item is expired
405
- */
406
- getWithExpiration(key, useSession = false) {
407
- const item = useSession
408
- ? this.getSession(key)
409
- : this.getLocal(key);
410
- if (!item)
411
- return null;
412
- if (Date.now() > item.expiration) {
413
- // Item expired, remove it
414
- if (useSession) {
415
- this.removeSession(key);
416
- }
417
- else {
418
- this.removeLocal(key);
419
- }
420
- return null;
421
- }
422
- return item.value;
423
- }
424
- }
425
-
426
- /**
427
- * Log level enum
428
- */
429
- exports.LogLevel = void 0;
430
- (function (LogLevel) {
431
- LogLevel[LogLevel["DEBUG"] = 0] = "DEBUG";
432
- LogLevel[LogLevel["INFO"] = 1] = "INFO";
433
- LogLevel[LogLevel["WARN"] = 2] = "WARN";
434
- LogLevel[LogLevel["ERROR"] = 3] = "ERROR";
435
- LogLevel[LogLevel["NONE"] = 4] = "NONE";
436
- })(exports.LogLevel || (exports.LogLevel = {}));
437
- /**
438
- * Logger - Centralized logging utility
439
- * Framework-agnostic implementation using browser console APIs
440
- * Supports different log levels and can be configured globally
441
- *
442
- * @example
443
- * ```typescript
444
- * const logger = new Logger();
445
- *
446
- * // Configure
447
- * logger.configure({
448
- * level: LogLevel.DEBUG,
449
- * enableTimestamp: true,
450
- * prefix: 'MyApp'
451
- * });
452
- *
453
- * // Use
454
- * logger.info('User logged in', { userId: '123' });
455
- * logger.error('Failed to load data', error);
456
- * ```
457
- */
458
- class Logger {
459
- config = {
460
- level: exports.LogLevel.INFO,
461
- enableTimestamp: true,
462
- enableStackTrace: false,
463
- prefix: ''
464
- };
465
- /**
466
- * Configure the logger
467
- */
468
- configure(config) {
469
- this.config = { ...this.config, ...config };
470
- }
471
- /**
472
- * Set log level
473
- */
474
- setLevel(level) {
475
- this.config.level = level;
476
- }
477
- /**
478
- * Get current log level
479
- */
480
- getLevel() {
481
- return this.config.level;
482
- }
483
- /**
484
- * Format log message with timestamp and prefix
485
- */
486
- formatMessage(message, level) {
487
- const parts = [];
488
- if (this.config.enableTimestamp) {
489
- parts.push(`[${new Date().toISOString()}]`);
490
- }
491
- if (this.config.prefix) {
492
- parts.push(`[${this.config.prefix}]`);
493
- }
494
- parts.push(`[${level}]`);
495
- parts.push(message);
496
- return parts.join(' ');
497
- }
498
- /**
499
- * Check if log level should be logged
500
- */
501
- shouldLog(level) {
502
- return level >= this.config.level;
503
- }
504
- /**
505
- * Log debug message
506
- */
507
- debug(message, ...args) {
508
- if (this.shouldLog(exports.LogLevel.DEBUG)) {
509
- console.debug(this.formatMessage(message, 'DEBUG'), ...args);
510
- }
511
- }
512
- /**
513
- * Log info message
514
- */
515
- info(message, ...args) {
516
- if (this.shouldLog(exports.LogLevel.INFO)) {
517
- console.info(this.formatMessage(message, 'INFO'), ...args);
518
- }
519
- }
520
- /**
521
- * Log warning message
522
- */
523
- warn(message, ...args) {
524
- if (this.shouldLog(exports.LogLevel.WARN)) {
525
- console.warn(this.formatMessage(message, 'WARN'), ...args);
526
- }
527
- }
528
- /**
529
- * Log error message
530
- */
531
- error(message, error, ...args) {
532
- if (this.shouldLog(exports.LogLevel.ERROR)) {
533
- console.error(this.formatMessage(message, 'ERROR'), ...args);
534
- if (error) {
535
- console.error(error);
536
- if (this.config.enableStackTrace && error?.stack) {
537
- console.error('Stack trace:', error.stack);
538
- }
539
- }
540
- }
541
- }
542
- /**
543
- * Log a group of messages
544
- */
545
- group(label, callback) {
546
- if (this.shouldLog(exports.LogLevel.INFO)) {
547
- console.group(this.formatMessage(label, 'GROUP'));
548
- callback();
549
- console.groupEnd();
550
- }
551
- }
552
- /**
553
- * Log a collapsed group of messages
554
- */
555
- groupCollapsed(label, callback) {
556
- if (this.shouldLog(exports.LogLevel.INFO)) {
557
- console.groupCollapsed(this.formatMessage(label, 'GROUP'));
558
- callback();
559
- console.groupEnd();
560
- }
561
- }
562
- /**
563
- * Log a table (useful for arrays of objects)
564
- */
565
- table(data, columns) {
566
- if (this.shouldLog(exports.LogLevel.INFO)) {
567
- console.table(data, columns);
568
- }
569
- }
570
- /**
571
- * Log execution time of a function
572
- */
573
- async time(label, fn) {
574
- const start = performance.now();
575
- try {
576
- const result = await fn();
577
- const end = performance.now();
578
- const duration = (end - start).toFixed(2);
579
- this.info(`${label} completed in ${duration}ms`);
580
- return result;
581
- }
582
- catch (error) {
583
- const end = performance.now();
584
- const duration = (end - start).toFixed(2);
585
- this.error(`${label} failed after ${duration}ms`, error);
586
- throw error;
587
- }
588
- }
589
- }
590
-
591
65
  /******************************************************************************
592
66
  Copyright (c) Microsoft Corporation.
593
67
 
@@ -621,657 +95,650 @@ typeof SuppressedError === "function" ? SuppressedError : function (error, suppr
621
95
  return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
622
96
  };
623
97
 
98
+ function mitt(n){return {all:n=n||new Map,on:function(t,e){var i=n.get(t);i?i.push(e):n.set(t,[e]);},off:function(t,e){var i=n.get(t);i&&(e?i.splice(i.indexOf(e)>>>0,1):n.set(t,[]));},emit:function(t,e){var i=n.get(t);i&&i.slice().map(function(n){n(e);}),(i=n.get("*"))&&i.slice().map(function(n){n(t,e);});}}}
99
+
624
100
  /**
625
- * NgEventEmitter - Angular service wrapper for EventBus
626
- * Provides Angular dependency injection support for the framework-agnostic EventBus
101
+ * EventBusService - Angular service for cross-application event communication
102
+ * Uses mitt library for efficient event handling and RxJS ReplaySubject for observable stream
103
+ *
104
+ * This service is designed for MicroFrontend architectures where different apps need to communicate
105
+ * The ReplaySubject keeps last 100 events in memory for late subscribers
627
106
  *
628
107
  * @example
629
108
  * ```typescript
630
- * import { Component, inject } from '@angular/core';
631
- * import { NgEventEmitter } from 'common-libs';
109
+ * import { Component, inject, OnInit } from '@angular/core';
110
+ * import { EventBusService } from '@opensourcekd/ng-common-libs';
632
111
  *
633
112
  * @Component({
634
113
  * selector: 'app-example',
635
114
  * template: '...'
636
115
  * })
637
- * export class ExampleComponent {
638
- * private eventEmitter = inject(NgEventEmitter);
116
+ * export class ExampleComponent implements OnInit {
117
+ * private eventBus = inject(EventBusService);
639
118
  *
640
119
  * ngOnInit() {
641
- * this.eventEmitter.on('user:login').subscribe(data => {
642
- * console.log('User logged in:', data);
120
+ * // Subscribe to all events
121
+ * this.eventBus.onePlusNEvents.subscribe(event => {
122
+ * console.log('Event received:', event);
643
123
  * });
644
124
  * }
645
125
  *
646
- * login() {
647
- * this.eventEmitter.emit('user:login', { userId: '123' });
126
+ * sendCustomEvent() {
127
+ * // Send a custom event
128
+ * this.eventBus.sendEvent('user:action');
129
+ *
130
+ * // Or send structured event with data
131
+ * this.eventBus.sendEvent(JSON.stringify({
132
+ * type: 'user:login',
133
+ * payload: { userId: '123' },
134
+ * timestamp: new Date().toISOString()
135
+ * }));
648
136
  * }
649
137
  * }
650
138
  * ```
651
139
  */
652
- exports.NgEventEmitter = class NgEventEmitter extends EventBus {
140
+ exports.EventBusService = class EventBusService {
141
+ /**
142
+ * ReplaySubject that buffers the last 100 events for late subscribers
143
+ * Subscribe to this observable to receive all events
144
+ */
145
+ onePlusNEvents;
146
+ /**
147
+ * mitt event emitter instance
148
+ * Lightweight event emitter library
149
+ */
150
+ emitter = mitt();
653
151
  constructor() {
654
- super();
152
+ // DEBUG_LOG: EventBusService initialized
153
+ console.log('[EventBusService] Service initialized');
154
+ const e = new Event('EventBusServiceCreated');
155
+ this.onePlusNEvents = new rxjs.ReplaySubject(100);
156
+ this.onePlusNEvents.next(e.type);
157
+ this.emitter.on('*', (event) => {
158
+ // DEBUG_LOG: Event received
159
+ console.log('[EventBusService] Event received and forwarded to ReplaySubject:', event);
160
+ this.onePlusNEvents.next(event);
161
+ });
162
+ // DEBUG_LOG: Event listener registered
163
+ console.log('[EventBusService] Event listener registered for all events');
164
+ }
165
+ /**
166
+ * Send an event through the event bus
167
+ * The event will be forwarded to all subscribers via the ReplaySubject
168
+ *
169
+ * @param s - Event string, can be a simple event name or JSON stringified structured data
170
+ *
171
+ * @example
172
+ * ```typescript
173
+ * // Simple event
174
+ * eventBus.sendEvent('user:logout');
175
+ *
176
+ * // Structured event
177
+ * eventBus.sendEvent(JSON.stringify({
178
+ * type: 'auth:token_updated',
179
+ * payload: { token: 'abc123' },
180
+ * timestamp: new Date().toISOString()
181
+ * }));
182
+ * ```
183
+ */
184
+ sendEvent(s) {
185
+ // DEBUG_LOG: Sending event
186
+ console.log('[EventBusService] sendEvent() called with:', s);
187
+ this.emitter.emit(s);
188
+ // DEBUG_LOG: Event emitted
189
+ console.log('[EventBusService] Event emitted successfully');
655
190
  }
656
191
  };
657
- exports.NgEventEmitter = __decorate([
658
- core.Injectable({
659
- providedIn: 'root'
660
- }),
192
+ exports.EventBusService = __decorate([
193
+ core.Injectable({ providedIn: 'root' }),
661
194
  __metadata("design:paramtypes", [])
662
- ], exports.NgEventEmitter);
195
+ ], exports.EventBusService);
196
+
197
+ function e(e,t){var n={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(n[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(o=Object.getOwnPropertySymbols(e);r<o.length;r++)t.indexOf(o[r])<0&&Object.prototype.propertyIsEnumerable.call(e,o[r])&&(n[o[r]]=e[o[r]]);}return n}"function"==typeof SuppressedError&&SuppressedError;var t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},n={},o={};Object.defineProperty(o,"__esModule",{value:true});var r=function(){function e(){var e=this;this.locked=new Map,this.addToLocked=function(t,n){var o=e.locked.get(t);void 0===o?void 0===n?e.locked.set(t,[]):e.locked.set(t,[n]):void 0!==n&&(o.unshift(n),e.locked.set(t,o));},this.isLocked=function(t){return e.locked.has(t)},this.lock=function(t){return new Promise((function(n,o){e.isLocked(t)?e.addToLocked(t,n):(e.addToLocked(t),n());}))},this.unlock=function(t){var n=e.locked.get(t);if(void 0!==n&&0!==n.length){var o=n.pop();e.locked.set(t,n),void 0!==o&&setTimeout(o,0);}else e.locked.delete(t);};}return e.getInstance=function(){return void 0===e.instance&&(e.instance=new e),e.instance},e}();o.default=function(){return r.getInstance()};var i=t&&t.__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(r,i){function a(e){try{c(o.next(e));}catch(e){i(e);}}function s(e){try{c(o.throw(e));}catch(e){i(e);}}function c(e){e.done?r(e.value):new n((function(t){t(e.value);})).then(a,s);}c((o=o.apply(e,t||[])).next());}))},a=t&&t.__generator||function(e,t){var n,o,r,i,a={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,o&&(r=2&i[0]?o.return:i[0]?o.throw||((r=o.return)&&r.call(o),0):o.next)&&!(r=r.call(o,i[1])).done)return r;switch(o=0,r&&(i=[2&i[0],r.value]),i[0]){case 0:case 1:r=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,o=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!(r=a.trys,(r=r.length>0&&r[r.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!r||i[1]>r[0]&&i[1]<r[3])){a.label=i[1];break}if(6===i[0]&&a.label<r[1]){a.label=r[1],r=i;break}if(r&&a.label<r[2]){a.label=r[2],a.ops.push(i);break}r[2]&&a.ops.pop(),a.trys.pop();continue}i=t.call(e,a);}catch(e){i=[6,e],o=0;}finally{n=r=0;}if(5&i[0])throw i[1];return {value:i[0]?i[1]:void 0,done:true}}([i,s])}}},s=t;Object.defineProperty(n,"__esModule",{value:true});var c=o,u={key:function(e){return i(s,void 0,void 0,(function(){return a(this,(function(e){throw new Error("Unsupported")}))}))},getItem:function(e){return i(s,void 0,void 0,(function(){return a(this,(function(e){throw new Error("Unsupported")}))}))},clear:function(){return i(s,void 0,void 0,(function(){return a(this,(function(e){return [2,window.localStorage.clear()]}))}))},removeItem:function(e){return i(s,void 0,void 0,(function(){return a(this,(function(e){throw new Error("Unsupported")}))}))},setItem:function(e,t){return i(s,void 0,void 0,(function(){return a(this,(function(e){throw new Error("Unsupported")}))}))},keySync:function(e){return window.localStorage.key(e)},getItemSync:function(e){return window.localStorage.getItem(e)},clearSync:function(){return window.localStorage.clear()},removeItemSync:function(e){return window.localStorage.removeItem(e)},setItemSync:function(e,t){return window.localStorage.setItem(e,t)}};function l(e){return new Promise((function(t){return setTimeout(t,e)}))}function d(e){for(var t="0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz",n="",o=0;o<e;o++){n+=t[Math.floor(Math.random()*t.length)];}return n}var h=function(){function e(t){this.acquiredIatSet=new Set,this.storageHandler=void 0,this.id=Date.now().toString()+d(15),this.acquireLock=this.acquireLock.bind(this),this.releaseLock=this.releaseLock.bind(this),this.releaseLock__private__=this.releaseLock__private__.bind(this),this.waitForSomethingToChange=this.waitForSomethingToChange.bind(this),this.refreshLockWhileAcquired=this.refreshLockWhileAcquired.bind(this),this.storageHandler=t,void 0===e.waiters&&(e.waiters=[]);}return e.prototype.acquireLock=function(t,n){return void 0===n&&(n=5e3),i(this,void 0,void 0,(function(){var o,r,i,s,c,h,p;return a(this,(function(a){switch(a.label){case 0:o=Date.now()+d(4),r=Date.now()+n,i="browser-tabs-lock-key-"+t,s=void 0===this.storageHandler?u:this.storageHandler,a.label=1;case 1:return Date.now()<r?[4,l(30)]:[3,8];case 2:return a.sent(),null!==s.getItemSync(i)?[3,5]:(c=this.id+"-"+t+"-"+o,[4,l(Math.floor(25*Math.random()))]);case 3:return a.sent(),s.setItemSync(i,JSON.stringify({id:this.id,iat:o,timeoutKey:c,timeAcquired:Date.now(),timeRefreshed:Date.now()})),[4,l(30)];case 4:return a.sent(),null!==(h=s.getItemSync(i))&&(p=JSON.parse(h)).id===this.id&&p.iat===o?(this.acquiredIatSet.add(o),this.refreshLockWhileAcquired(i,o),[2,true]):[3,7];case 5:return e.lockCorrector(void 0===this.storageHandler?u:this.storageHandler),[4,this.waitForSomethingToChange(r)];case 6:a.sent(),a.label=7;case 7:return o=Date.now()+d(4),[3,1];case 8:return [2,false]}}))}))},e.prototype.refreshLockWhileAcquired=function(e,t){return i(this,void 0,void 0,(function(){var n=this;return a(this,(function(o){return setTimeout((function(){return i(n,void 0,void 0,(function(){var n,o,r;return a(this,(function(i){switch(i.label){case 0:return [4,c.default().lock(t)];case 1:return i.sent(),this.acquiredIatSet.has(t)?(n=void 0===this.storageHandler?u:this.storageHandler,null===(o=n.getItemSync(e))?(c.default().unlock(t),[2]):((r=JSON.parse(o)).timeRefreshed=Date.now(),n.setItemSync(e,JSON.stringify(r)),c.default().unlock(t),this.refreshLockWhileAcquired(e,t),[2])):(c.default().unlock(t),[2])}}))}))}),1e3),[2]}))}))},e.prototype.waitForSomethingToChange=function(t){return i(this,void 0,void 0,(function(){return a(this,(function(n){switch(n.label){case 0:return [4,new Promise((function(n){var o=false,r=Date.now(),i=false;function a(){if(i||(window.removeEventListener("storage",a),e.removeFromWaiting(a),clearTimeout(s),i=true),!o){o=true;var t=50-(Date.now()-r);t>0?setTimeout(n,t):n(null);}}window.addEventListener("storage",a),e.addToWaiting(a);var s=setTimeout(a,Math.max(0,t-Date.now()));}))];case 1:return n.sent(),[2]}}))}))},e.addToWaiting=function(t){this.removeFromWaiting(t),void 0!==e.waiters&&e.waiters.push(t);},e.removeFromWaiting=function(t){ void 0!==e.waiters&&(e.waiters=e.waiters.filter((function(e){return e!==t})));},e.notifyWaiters=function(){ void 0!==e.waiters&&e.waiters.slice().forEach((function(e){return e()}));},e.prototype.releaseLock=function(e){return i(this,void 0,void 0,(function(){return a(this,(function(t){switch(t.label){case 0:return [4,this.releaseLock__private__(e)];case 1:return [2,t.sent()]}}))}))},e.prototype.releaseLock__private__=function(t){return i(this,void 0,void 0,(function(){var n,o,r,i;return a(this,(function(a){switch(a.label){case 0:return n=void 0===this.storageHandler?u:this.storageHandler,o="browser-tabs-lock-key-"+t,null===(r=n.getItemSync(o))?[2]:(i=JSON.parse(r)).id!==this.id?[3,2]:[4,c.default().lock(i.iat)];case 1:a.sent(),this.acquiredIatSet.delete(i.iat),n.removeItemSync(o),c.default().unlock(i.iat),e.notifyWaiters(),a.label=2;case 2:return [2]}}))}))},e.lockCorrector=function(t){for(var n=Date.now()-5e3,o=t,r=[],i=0;;){var a=o.keySync(i);if(null===a)break;r.push(a),i++;}for(var s=false,c=0;c<r.length;c++){var u=r[c];if(u.includes("browser-tabs-lock-key")){var l=o.getItemSync(u);if(null!==l){var d=JSON.parse(l);(void 0===d.timeRefreshed&&d.timeAcquired<n||void 0!==d.timeRefreshed&&d.timeRefreshed<n)&&(o.removeItemSync(u),s=true);}}}s&&e.notifyWaiters();},e.waiters=void 0,e}(),p=n.default=h;const f={timeoutInSeconds:60},m={name:"auth0-spa-js",version:"2.13.0"},y=()=>Date.now();class w extends Error{constructor(e,t){super(t),this.error=e,this.error_description=t,Object.setPrototypeOf(this,w.prototype);}static fromPayload(e){let{error:t,error_description:n}=e;return new w(t,n)}}class g extends w{constructor(e,t,n){let o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null;super(e,t),this.state=n,this.appState=o,Object.setPrototypeOf(this,g.prototype);}}class v extends w{constructor(e,t,n,o){let r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null;super(e,t),this.connection=n,this.state=o,this.appState=r,Object.setPrototypeOf(this,v.prototype);}}class b extends w{constructor(){super("timeout","Timeout"),Object.setPrototypeOf(this,b.prototype);}}class _ extends b{constructor(e){super(),this.popup=e,Object.setPrototypeOf(this,_.prototype);}}class k extends w{constructor(e){super("cancelled","Popup closed"),this.popup=e,Object.setPrototypeOf(this,k.prototype);}}class S extends w{constructor(){super("popup_open","Unable to open a popup for loginWithPopup - window.open returned `null`"),Object.setPrototypeOf(this,S.prototype);}}class E extends w{constructor(e,t,n,o){super(e,t),this.mfa_token=n,this.mfa_requirements=o,Object.setPrototypeOf(this,E.prototype);}}class A extends w{constructor(e,t){super("missing_refresh_token","Missing Refresh Token (audience: '".concat(R(e,["default"]),"', scope: '").concat(R(t),"')")),this.audience=e,this.scope=t,Object.setPrototypeOf(this,A.prototype);}}class T extends w{constructor(e,t){super("missing_scopes","Missing requested scopes after refresh (audience: '".concat(R(e,["default"]),"', missing scope: '").concat(R(t),"')")),this.audience=e,this.scope=t,Object.setPrototypeOf(this,T.prototype);}}class P extends w{constructor(e){super("use_dpop_nonce","Server rejected DPoP proof: wrong nonce"),this.newDpopNonce=e,Object.setPrototypeOf(this,P.prototype);}}function R(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];return e&&!t.includes(e)?e:""}const I=()=>window.crypto,O=()=>{const e="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.";let t="";return Array.from(I().getRandomValues(new Uint8Array(43))).forEach((n=>t+=e[n%e.length])),t},x=e=>btoa(e),C=[{key:"name",type:["string"]},{key:"version",type:["string","number"]},{key:"env",type:["object"]}],j=function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return Object.keys(e).reduce(((n,o)=>{if(t&&"env"===o)return n;const r=C.find((e=>e.key===o));return r&&r.type.includes(typeof e[o])&&(n[o]=e[o]),n}),{})},D=t=>{var{clientId:n}=t,o=e(t,["clientId"]);return new URLSearchParams((e=>Object.keys(e).filter((t=>void 0!==e[t])).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:e[n]})),{}))(Object.assign({client_id:n},o))).toString()},K=async e=>{const t=I().subtle.digest({name:"SHA-256"},(new TextEncoder).encode(e));return await t},L=e=>(e=>decodeURIComponent(atob(e).split("").map((e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2))).join("")))(e.replace(/_/g,"/").replace(/-/g,"+")),U=e=>{const t=new Uint8Array(e);return (e=>{const t={"+":"-","/":"_","=":""};return e.replace(/[+/=]/g,(e=>t[e]))})(window.btoa(String.fromCharCode(...Array.from(t))))},N=new TextEncoder,W=new TextDecoder;function z(e){return "string"==typeof e?N.encode(e):W.decode(e)}function H(e){if("number"!=typeof e.modulusLength||e.modulusLength<2048)throw new G(`${e.name} modulusLength must be at least 2048 bits`)}async function M(e,t,n){if(false===n.usages.includes("sign"))throw new TypeError('private CryptoKey instances used for signing assertions must include "sign" in their "usages"');const o=`${V(z(JSON.stringify(e)))}.${V(z(JSON.stringify(t)))}`;return `${o}.${V(await crypto.subtle.sign(function(e){switch(e.algorithm.name){case "ECDSA":return {name:e.algorithm.name,hash:"SHA-256"};case "RSA-PSS":return H(e.algorithm),{name:e.algorithm.name,saltLength:32};case "RSASSA-PKCS1-v1_5":return H(e.algorithm),{name:e.algorithm.name};case "Ed25519":return {name:e.algorithm.name}}throw new F}(n),n,z(o)))}`}let J;if(Uint8Array.prototype.toBase64)J=e=>(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e.toBase64({alphabet:"base64url",omitPadding:true}));else {const e=32768;J=t=>{t instanceof ArrayBuffer&&(t=new Uint8Array(t));const n=[];for(let o=0;o<t.byteLength;o+=e)n.push(String.fromCharCode.apply(null,t.subarray(o,o+e)));return btoa(n.join("")).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")};}function V(e){return J(e)}class F extends Error{constructor(e){var t;super(null!=e?e:"operation not supported"),this.name=this.constructor.name,null===(t=Error.captureStackTrace)||void 0===t||t.call(Error,this,this.constructor);}}class G extends Error{constructor(e){var t;super(e),this.name=this.constructor.name,null===(t=Error.captureStackTrace)||void 0===t||t.call(Error,this,this.constructor);}}function Z(e){switch(e.algorithm.name){case "RSA-PSS":return function(e){if("SHA-256"===e.algorithm.hash.name)return "PS256";throw new F("unsupported RsaHashedKeyAlgorithm hash name")}(e);case "RSASSA-PKCS1-v1_5":return function(e){if("SHA-256"===e.algorithm.hash.name)return "RS256";throw new F("unsupported RsaHashedKeyAlgorithm hash name")}(e);case "ECDSA":return function(e){if("P-256"===e.algorithm.namedCurve)return "ES256";throw new F("unsupported EcKeyAlgorithm namedCurve")}(e);case "Ed25519":return "Ed25519";default:throw new F("unsupported CryptoKey algorithm name")}}function q(e){return e instanceof CryptoKey}function B(e){return q(e)&&"public"===e.type}async function X(e,t,n,o,r,i){const a=null==e?void 0:e.privateKey,s=null==e?void 0:e.publicKey;if(!q(c=a)||"private"!==c.type)throw new TypeError('"keypair.privateKey" must be a private CryptoKey');var c;if(!B(s))throw new TypeError('"keypair.publicKey" must be a public CryptoKey');if(true!==s.extractable)throw new TypeError('"keypair.publicKey.extractable" must be true');if("string"!=typeof t)throw new TypeError('"htu" must be a string');if("string"!=typeof n)throw new TypeError('"htm" must be a string');if(void 0!==o&&"string"!=typeof o)throw new TypeError('"nonce" must be a string or undefined');if(void 0!==r&&"string"!=typeof r)throw new TypeError('"accessToken" must be a string or undefined');return M({alg:Z(a),typ:"dpop+jwt",jwk:await Y(s)},Object.assign(Object.assign({},i),{iat:Math.floor(Date.now()/1e3),jti:crypto.randomUUID(),htm:n,nonce:o,htu:t,ath:r?V(await crypto.subtle.digest("SHA-256",z(r))):void 0}),a)}async function Y(e){const{kty:t,e:n,n:o,x:r,y:i,crv:a}=await crypto.subtle.exportKey("jwk",e);return {kty:t,crv:a,e:n,n:o,x:r,y:i}}const Q=["authorization_code","refresh_token","urn:ietf:params:oauth:grant-type:token-exchange","http://auth0.com/oauth/grant-type/mfa-oob","http://auth0.com/oauth/grant-type/mfa-otp","http://auth0.com/oauth/grant-type/mfa-recovery-code"];function $(){return async function(e,t){var n;let o;if(0===e.length)throw new TypeError('"alg" must be a non-empty string');switch(e){case "PS256":o={name:"RSA-PSS",hash:"SHA-256",modulusLength:2048,publicExponent:new Uint8Array([1,0,1])};break;case "RS256":o={name:"RSASSA-PKCS1-v1_5",hash:"SHA-256",modulusLength:2048,publicExponent:new Uint8Array([1,0,1])};break;case "ES256":o={name:"ECDSA",namedCurve:"P-256"};break;case "Ed25519":o={name:"Ed25519"};break;default:throw new F}return crypto.subtle.generateKey(o,null!==(n=null==t?void 0:t.extractable)&&void 0!==n&&n,["sign","verify"])}("ES256",{extractable:false})}function ee(e){return async function(e){if(!B(e))throw new TypeError('"publicKey" must be a public CryptoKey');if(true!==e.extractable)throw new TypeError('"publicKey.extractable" must be true');const t=await Y(e);let n;switch(t.kty){case "EC":n={crv:t.crv,kty:t.kty,x:t.x,y:t.y};break;case "OKP":n={crv:t.crv,kty:t.kty,x:t.x};break;case "RSA":n={e:t.e,kty:t.kty,n:t.n};break;default:throw new F("unsupported JWK kty")}return V(await crypto.subtle.digest({name:"SHA-256"},z(JSON.stringify(n))))}(e.publicKey)}function te(e){let{keyPair:t,url:n,method:o,nonce:r,accessToken:i}=e;const a=function(e){const t=new URL(e);return t.search="",t.hash="",t.href}(n);return X(t,a,o,r,i)}const ne=async(e,t)=>{const n=await fetch(e,t);return {ok:n.ok,json:await n.json(),headers:(o=n.headers,[...o].reduce(((e,t)=>{let[n,o]=t;return e[n]=o,e}),{}))};var o;},oe=async(e,t,n)=>{const o=new AbortController;let r;return t.signal=o.signal,Promise.race([ne(e,t),new Promise(((e,t)=>{r=setTimeout((()=>{o.abort(),t(new Error("Timeout when executing 'fetch'"));}),n);}))]).finally((()=>{clearTimeout(r);}))},re=async(e,t,n,o,r,i,a,s)=>((e,t)=>new Promise((function(n,o){const r=new MessageChannel;r.port1.onmessage=function(e){e.data.error?o(new Error(e.data.error)):n(e.data),r.port1.close();},t.postMessage(e,[r.port2]);})))({auth:{audience:t,scope:n},timeout:r,fetchUrl:e,fetchOptions:o,useFormData:a,useMrrt:s},i),ie=async function(e,t,n,o,r,i){let a=arguments.length>6&&void 0!==arguments[6]?arguments[6]:1e4,s=arguments.length>7?arguments[7]:void 0;return r?re(e,t,n,o,a,r,i,s):oe(e,o,a)};async function ae(t,n,o,r,i,a,s,c,u,l){if(u){const e=await u.generateProof({url:t,method:i.method||"GET",nonce:await u.getNonce()});i.headers=Object.assign(Object.assign({},i.headers),{dpop:e});}let d,h=null;for(let e=0;e<3;e++)try{d=await ie(t,o,r,i,a,s,n,c),h=null;break}catch(e){h=e;}if(h)throw h;const p=d.json,{error:f,error_description:m}=p,y=e(p,["error","error_description"]),{headers:g,ok:v}=d;let b;if(u&&(b=g["dpop-nonce"],b&&await u.setNonce(b)),!v){const e=m||"HTTP error. Unable to fetch ".concat(t);if("mfa_required"===f)throw new E(f,e,y.mfa_token,y.mfa_requirements);if("missing_refresh_token"===f)throw new A(o,r);if("use_dpop_nonce"===f){if(!u||!b||l)throw new P(b);return ae(t,n,o,r,i,a,s,c,u,true)}throw new w(f||"request_error",e)}return y}async function se(t,n){var{baseUrl:o,timeout:r,audience:i,scope:a,auth0Client:s,useFormData:c,useMrrt:u,dpop:l}=t,d=e(t,["baseUrl","timeout","audience","scope","auth0Client","useFormData","useMrrt","dpop"]);const h="urn:ietf:params:oauth:grant-type:token-exchange"===d.grant_type,p="refresh_token"===d.grant_type&&u,f=Object.assign(Object.assign(Object.assign(Object.assign({},d),h&&i&&{audience:i}),h&&a&&{scope:a}),p&&{audience:i,scope:a}),y=c?D(f):JSON.stringify(f),w=(g=d.grant_type,Q.includes(g));var g;return await ae("".concat(o,"/oauth/token"),r,i||"default",a,{method:"POST",body:y,headers:{"Content-Type":c?"application/x-www-form-urlencoded":"application/json","Auth0-Client":btoa(JSON.stringify(j(s||m)))}},n,c,u,w?l:void 0)}const ce=e=>Array.from(new Set(e)),ue=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return ce(t.filter(Boolean).join(" ").trim().split(/\s+/)).join(" ")},le=(e,t,n)=>{let o;return n&&(o=e[n]),o||(o=e.default),ue(o,t)};class de{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"@@auth0spajs@@",n=arguments.length>2?arguments[2]:void 0;this.prefix=t,this.suffix=n,this.clientId=e.clientId,this.scope=e.scope,this.audience=e.audience;}toKey(){return [this.prefix,this.clientId,this.audience,this.scope,this.suffix].filter(Boolean).join("::")}static fromKey(e){const[t,n,o,r]=e.split("::");return new de({clientId:n,scope:r,audience:o},t)}static fromCacheEntry(e){const{scope:t,audience:n,client_id:o}=e;return new de({scope:t,audience:n,clientId:o})}}class he{set(e,t){localStorage.setItem(e,JSON.stringify(t));}get(e){const t=window.localStorage.getItem(e);if(t)try{return JSON.parse(t)}catch(e){return}}remove(e){localStorage.removeItem(e);}allKeys(){return Object.keys(window.localStorage).filter((e=>e.startsWith("@@auth0spajs@@")))}}class pe{constructor(){this.enclosedCache=function(){let e={};return {set(t,n){e[t]=n;},get(t){const n=e[t];if(n)return n},remove(t){delete e[t];},allKeys:()=>Object.keys(e)}}();}}class fe{constructor(e,t,n){this.cache=e,this.keyManifest=t,this.nowProvider=n||y;}async setIdToken(e,t,n){var o;const r=this.getIdTokenCacheKey(e);await this.cache.set(r,{id_token:t,decodedToken:n}),await(null===(o=this.keyManifest)||void 0===o?void 0:o.add(r));}async getIdToken(e){const t=await this.cache.get(this.getIdTokenCacheKey(e.clientId));if(!t&&e.scope&&e.audience){const t=await this.get(e);if(!t)return;if(!t.id_token||!t.decodedToken)return;return {id_token:t.id_token,decodedToken:t.decodedToken}}if(t)return {id_token:t.id_token,decodedToken:t.decodedToken}}async get(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],o=arguments.length>3?arguments[3]:void 0;var r;let i=await this.cache.get(e.toKey());if(!i){const t=await this.getCacheKeys();if(!t)return;const r=this.matchExistingCacheKey(e,t);if(r&&(i=await this.cache.get(r)),!i&&n&&"cache-only"!==o)return this.getEntryWithRefreshToken(e,t)}if(!i)return;const a=await this.nowProvider(),s=Math.floor(a/1e3);return i.expiresAt-t<s?i.body.refresh_token?this.modifiedCachedEntry(i,e):(await this.cache.remove(e.toKey()),void await(null===(r=this.keyManifest)||void 0===r?void 0:r.remove(e.toKey()))):i.body}async modifiedCachedEntry(e,t){return e.body={refresh_token:e.body.refresh_token,audience:e.body.audience,scope:e.body.scope},await this.cache.set(t.toKey(),e),{refresh_token:e.body.refresh_token,audience:e.body.audience,scope:e.body.scope}}async set(e){var t;const n=new de({clientId:e.client_id,scope:e.scope,audience:e.audience}),o=await this.wrapCacheEntry(e);await this.cache.set(n.toKey(),o),await(null===(t=this.keyManifest)||void 0===t?void 0:t.add(n.toKey()));}async remove(e,t,n){const o=new de({clientId:e,scope:n,audience:t});await this.cache.remove(o.toKey());}async clear(e){var t;const n=await this.getCacheKeys();n&&(await n.filter((t=>!e||t.includes(e))).reduce((async(e,t)=>{await e,await this.cache.remove(t);}),Promise.resolve()),await(null===(t=this.keyManifest)||void 0===t?void 0:t.clear()));}async wrapCacheEntry(e){const t=await this.nowProvider();return {body:e,expiresAt:Math.floor(t/1e3)+e.expires_in}}async getCacheKeys(){var e;return this.keyManifest?null===(e=await this.keyManifest.get())||void 0===e?void 0:e.keys:this.cache.allKeys?this.cache.allKeys():void 0}getIdTokenCacheKey(e){return new de({clientId:e},"@@auth0spajs@@","@@user@@").toKey()}matchExistingCacheKey(e,t){return t.filter((t=>{var n;const o=de.fromKey(t),r=new Set(o.scope&&o.scope.split(" ")),i=(null===(n=e.scope)||void 0===n?void 0:n.split(" "))||[],a=o.scope&&i.reduce(((e,t)=>e&&r.has(t)),true);return "@@auth0spajs@@"===o.prefix&&o.clientId===e.clientId&&o.audience===e.audience&&a}))[0]}async getEntryWithRefreshToken(e,t){var n;for(const o of t){const t=de.fromKey(o);if("@@auth0spajs@@"===t.prefix&&t.clientId===e.clientId){const t=await this.cache.get(o);if(null===(n=null==t?void 0:t.body)||void 0===n?void 0:n.refresh_token)return this.modifiedCachedEntry(t,e)}}}async updateEntry(e,t){var n;const o=await this.getCacheKeys();if(o)for(const r of o){const o=await this.cache.get(r);if((null===(n=null==o?void 0:o.body)||void 0===n?void 0:n.refresh_token)===e){const e=Object.assign(Object.assign({},o.body),{refresh_token:t});await this.set(e);}}}}class me{constructor(e,t,n){this.storage=e,this.clientId=t,this.cookieDomain=n,this.storageKey="".concat("a0.spajs.txs",".").concat(this.clientId);}create(e){this.storage.save(this.storageKey,e,{daysUntilExpire:1,cookieDomain:this.cookieDomain});}get(){return this.storage.get(this.storageKey)}remove(){this.storage.remove(this.storageKey,{cookieDomain:this.cookieDomain});}}const ye=e=>"number"==typeof e,we=["iss","aud","exp","nbf","iat","jti","azp","nonce","auth_time","at_hash","c_hash","acr","amr","sub_jwk","cnf","sip_from_tag","sip_date","sip_callid","sip_cseq_num","sip_via_branch","orig","dest","mky","events","toe","txn","rph","sid","vot","vtm"],ge=e=>{if(!e.id_token)throw new Error("ID token is required but missing");const t=(e=>{const t=e.split("."),[n,o,r]=t;if(3!==t.length||!n||!o||!r)throw new Error("ID token could not be decoded");const i=JSON.parse(L(o)),a={__raw:e},s={};return Object.keys(i).forEach((e=>{a[e]=i[e],we.includes(e)||(s[e]=i[e]);})),{encoded:{header:n,payload:o,signature:r},header:JSON.parse(L(n)),claims:a,user:s}})(e.id_token);if(!t.claims.iss)throw new Error("Issuer (iss) claim must be a string present in the ID token");if(t.claims.iss!==e.iss)throw new Error('Issuer (iss) claim mismatch in the ID token; expected "'.concat(e.iss,'", found "').concat(t.claims.iss,'"'));if(!t.user.sub)throw new Error("Subject (sub) claim must be a string present in the ID token");if("RS256"!==t.header.alg)throw new Error('Signature algorithm of "'.concat(t.header.alg,'" is not supported. Expected the ID token to be signed with "RS256".'));if(!t.claims.aud||"string"!=typeof t.claims.aud&&!Array.isArray(t.claims.aud))throw new Error("Audience (aud) claim must be a string or array of strings present in the ID token");if(Array.isArray(t.claims.aud)){if(!t.claims.aud.includes(e.aud))throw new Error('Audience (aud) claim mismatch in the ID token; expected "'.concat(e.aud,'" but was not one of "').concat(t.claims.aud.join(", "),'"'));if(t.claims.aud.length>1){if(!t.claims.azp)throw new Error("Authorized Party (azp) claim must be a string present in the ID token when Audience (aud) claim has multiple values");if(t.claims.azp!==e.aud)throw new Error('Authorized Party (azp) claim mismatch in the ID token; expected "'.concat(e.aud,'", found "').concat(t.claims.azp,'"'))}}else if(t.claims.aud!==e.aud)throw new Error('Audience (aud) claim mismatch in the ID token; expected "'.concat(e.aud,'" but found "').concat(t.claims.aud,'"'));if(e.nonce){if(!t.claims.nonce)throw new Error("Nonce (nonce) claim must be a string present in the ID token");if(t.claims.nonce!==e.nonce)throw new Error('Nonce (nonce) claim mismatch in the ID token; expected "'.concat(e.nonce,'", found "').concat(t.claims.nonce,'"'))}if(e.max_age&&!ye(t.claims.auth_time))throw new Error("Authentication Time (auth_time) claim must be a number present in the ID token when Max Age (max_age) is specified");if(null==t.claims.exp||!ye(t.claims.exp))throw new Error("Expiration Time (exp) claim must be a number present in the ID token");if(!ye(t.claims.iat))throw new Error("Issued At (iat) claim must be a number present in the ID token");const n=e.leeway||60,o=new Date(e.now||Date.now()),r=new Date(0);if(r.setUTCSeconds(t.claims.exp+n),o>r)throw new Error("Expiration Time (exp) claim error in the ID token; current time (".concat(o,") is after expiration time (").concat(r,")"));if(null!=t.claims.nbf&&ye(t.claims.nbf)){const e=new Date(0);if(e.setUTCSeconds(t.claims.nbf-n),o<e)throw new Error("Not Before time (nbf) claim in the ID token indicates that this token can't be used just yet. Current time (".concat(o,") is before ").concat(e))}if(null!=t.claims.auth_time&&ye(t.claims.auth_time)){const r=new Date(0);if(r.setUTCSeconds(parseInt(t.claims.auth_time)+e.max_age+n),o>r)throw new Error("Authentication Time (auth_time) claim in the ID token indicates that too much time has passed since the last end-user authentication. Current time (".concat(o,") is after last auth at ").concat(r))}if(e.organization){const n=e.organization.trim();if(n.startsWith("org_")){const e=n;if(!t.claims.org_id)throw new Error("Organization ID (org_id) claim must be a string present in the ID token");if(e!==t.claims.org_id)throw new Error('Organization ID (org_id) claim mismatch in the ID token; expected "'.concat(e,'", found "').concat(t.claims.org_id,'"'))}else {const e=n.toLowerCase();if(!t.claims.org_name)throw new Error("Organization Name (org_name) claim must be a string present in the ID token");if(e!==t.claims.org_name)throw new Error('Organization Name (org_name) claim mismatch in the ID token; expected "'.concat(e,'", found "').concat(t.claims.org_name,'"'))}}return t};var ve=t&&t.__assign||function(){return ve=Object.assign||function(e){for(var t,n=1,o=arguments.length;n<o;n++)for(var r in t=arguments[n])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},ve.apply(this,arguments)};function be(e,t){if(!t)return "";var n="; "+e;return true===t?n:n+"="+t}function _e(e,t,n){return encodeURIComponent(e).replace(/%(23|24|26|2B|5E|60|7C)/g,decodeURIComponent).replace(/\(/g,"%28").replace(/\)/g,"%29")+"="+encodeURIComponent(t).replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g,decodeURIComponent)+function(e){if("number"==typeof e.expires){var t=new Date;t.setMilliseconds(t.getMilliseconds()+864e5*e.expires),e.expires=t;}return be("Expires",e.expires?e.expires.toUTCString():"")+be("Domain",e.domain)+be("Path",e.path)+be("Secure",e.secure)+be("SameSite",e.sameSite)}(n)}function ke(){return function(e){for(var t={},n=e?e.split("; "):[],o=/(%[\dA-F]{2})+/gi,r=0;r<n.length;r++){var i=n[r].split("="),a=i.slice(1).join("=");'"'===a.charAt(0)&&(a=a.slice(1,-1));try{t[i[0].replace(o,decodeURIComponent)]=a.replace(o,decodeURIComponent);}catch(e){}}return t}(document.cookie)}var Se=function(e){return ke()[e]};function Ee(e,t,n){document.cookie=_e(e,t,ve({path:"/"},n));}var Ae=Ee;var Te=function(e,t){Ee(e,"",ve(ve({},t),{expires:-1}));};const Pe={get(e){const t=Se(e);if(void 0!==t)return JSON.parse(t)},save(e,t,n){let o={};"https:"===window.location.protocol&&(o={secure:true,sameSite:"none"}),(null==n?void 0:n.daysUntilExpire)&&(o.expires=n.daysUntilExpire),(null==n?void 0:n.cookieDomain)&&(o.domain=n.cookieDomain),Ae(e,JSON.stringify(t),o);},remove(e,t){let n={};(null==t?void 0:t.cookieDomain)&&(n.domain=t.cookieDomain),Te(e,n);}},Re={get(e){const t=Pe.get(e);return t||Pe.get("".concat("_legacy_").concat(e))},save(e,t,n){let o={};"https:"===window.location.protocol&&(o={secure:true}),(null==n?void 0:n.daysUntilExpire)&&(o.expires=n.daysUntilExpire),(null==n?void 0:n.cookieDomain)&&(o.domain=n.cookieDomain),Ae("".concat("_legacy_").concat(e),JSON.stringify(t),o),Pe.save(e,t,n);},remove(e,t){let n={};(null==t?void 0:t.cookieDomain)&&(n.domain=t.cookieDomain),Te(e,n),Pe.remove(e,t),Pe.remove("".concat("_legacy_").concat(e),t);}},Ie={get(e){if("undefined"==typeof sessionStorage)return;const t=sessionStorage.getItem(e);return null!=t?JSON.parse(t):void 0},save(e,t){sessionStorage.setItem(e,JSON.stringify(t));},remove(e){sessionStorage.removeItem(e);}};var Oe;!function(e){e.Code="code",e.ConnectCode="connect_code";}(Oe||(Oe={}));function Ce(e,t,n){var o=void 0===t?null:t,r=function(e,t){var n=atob(e);if(t){for(var o=new Uint8Array(n.length),r=0,i=n.length;r<i;++r)o[r]=n.charCodeAt(r);return String.fromCharCode.apply(null,new Uint16Array(o.buffer))}return n}(e,void 0!==n&&n),i=r.indexOf("\n",10)+1,a=r.substring(i)+(o?"//# sourceMappingURL="+o:""),s=new Blob([a],{type:"application/javascript"});return URL.createObjectURL(s)}var je,De,Ke,Le,Ue=(je="Lyogcm9sbHVwLXBsdWdpbi13ZWItd29ya2VyLWxvYWRlciAqLwohZnVuY3Rpb24oKXsidXNlIHN0cmljdCI7Y2xhc3MgZSBleHRlbmRzIEVycm9ye2NvbnN0cnVjdG9yKHQscil7c3VwZXIociksdGhpcy5lcnJvcj10LHRoaXMuZXJyb3JfZGVzY3JpcHRpb249cixPYmplY3Quc2V0UHJvdG90eXBlT2YodGhpcyxlLnByb3RvdHlwZSl9c3RhdGljIGZyb21QYXlsb2FkKHQpe2xldHtlcnJvcjpyLGVycm9yX2Rlc2NyaXB0aW9uOnN9PXQ7cmV0dXJuIG5ldyBlKHIscyl9fWNsYXNzIHQgZXh0ZW5kcyBle2NvbnN0cnVjdG9yKGUscyl7c3VwZXIoIm1pc3NpbmdfcmVmcmVzaF90b2tlbiIsIk1pc3NpbmcgUmVmcmVzaCBUb2tlbiAoYXVkaWVuY2U6ICciLmNvbmNhdChyKGUsWyJkZWZhdWx0Il0pLCInLCBzY29wZTogJyIpLmNvbmNhdChyKHMpLCInKSIpKSx0aGlzLmF1ZGllbmNlPWUsdGhpcy5zY29wZT1zLE9iamVjdC5zZXRQcm90b3R5cGVPZih0aGlzLHQucHJvdG90eXBlKX19ZnVuY3Rpb24gcihlKXtsZXQgdD1hcmd1bWVudHMubGVuZ3RoPjEmJnZvaWQgMCE9PWFyZ3VtZW50c1sxXT9hcmd1bWVudHNbMV06W107cmV0dXJuIGUmJiF0LmluY2x1ZGVzKGUpP2U6IiJ9ImZ1bmN0aW9uIj09dHlwZW9mIFN1cHByZXNzZWRFcnJvciYmU3VwcHJlc3NlZEVycm9yO2NvbnN0IHM9ZT0+e3ZhcntjbGllbnRJZDp0fT1lLHI9ZnVuY3Rpb24oZSx0KXt2YXIgcj17fTtmb3IodmFyIHMgaW4gZSlPYmplY3QucHJvdG90eXBlLmhhc093blByb3BlcnR5LmNhbGwoZSxzKSYmdC5pbmRleE9mKHMpPDAmJihyW3NdPWVbc10pO2lmKG51bGwhPWUmJiJmdW5jdGlvbiI9PXR5cGVvZiBPYmplY3QuZ2V0T3duUHJvcGVydHlTeW1ib2xzKXt2YXIgbz0wO2ZvcihzPU9iamVjdC5nZXRPd25Qcm9wZXJ0eVN5bWJvbHMoZSk7bzxzLmxlbmd0aDtvKyspdC5pbmRleE9mKHNbb10pPDAmJk9iamVjdC5wcm90b3R5cGUucHJvcGVydHlJc0VudW1lcmFibGUuY2FsbChlLHNbb10pJiYocltzW29dXT1lW3Nbb11dKX1yZXR1cm4gcn0oZSxbImNsaWVudElkIl0pO3JldHVybiBuZXcgVVJMU2VhcmNoUGFyYW1zKChlPT5PYmplY3Qua2V5cyhlKS5maWx0ZXIoKHQ9PnZvaWQgMCE9PWVbdF0pKS5yZWR1Y2UoKCh0LHIpPT5PYmplY3QuYXNzaWduKE9iamVjdC5hc3NpZ24oe30sdCkse1tyXTplW3JdfSkpLHt9KSkoT2JqZWN0LmFzc2lnbih7Y2xpZW50X2lkOnR9LHIpKSkudG9TdHJpbmcoKX07bGV0IG89e307Y29uc3Qgbj0oZSx0KT0+IiIuY29uY2F0KGUsInwiKS5jb25jYXQodCk7YWRkRXZlbnRMaXN0ZW5lcigibWVzc2FnZSIsKGFzeW5jIGU9PntsZXQgcixjLHtkYXRhOnt0aW1lb3V0OmksYXV0aDphLGZldGNoVXJsOmYsZmV0Y2hPcHRpb25zOmwsdXNlRm9ybURhdGE6cCx1c2VNcnJ0Omh9LHBvcnRzOlt1XX09ZSxkPXt9O2NvbnN0e2F1ZGllbmNlOmcsc2NvcGU6eX09YXx8e307dHJ5e2NvbnN0IGU9cD8oZT0+e2NvbnN0IHQ9bmV3IFVSTFNlYXJjaFBhcmFtcyhlKSxyPXt9O3JldHVybiB0LmZvckVhY2goKChlLHQpPT57clt0XT1lfSkpLHJ9KShsLmJvZHkpOkpTT04ucGFyc2UobC5ib2R5KTtpZighZS5yZWZyZXNoX3Rva2VuJiYicmVmcmVzaF90b2tlbiI9PT1lLmdyYW50X3R5cGUpe2lmKGM9KChlLHQpPT5vW24oZSx0KV0pKGcseSksIWMmJmgpe2NvbnN0IGU9by5sYXRlc3RfcmVmcmVzaF90b2tlbix0PSgoZSx0KT0+e2NvbnN0IHI9T2JqZWN0LmtleXMobykuZmluZCgocj0+e2lmKCJsYXRlc3RfcmVmcmVzaF90b2tlbiIhPT1yKXtjb25zdCBzPSgoZSx0KT0+dC5zdGFydHNXaXRoKCIiLmNvbmNhdChlLCJ8IikpKSh0LHIpLG89ci5zcGxpdCgifCIpWzFdLnNwbGl0KCIgIiksbj1lLnNwbGl0KCIgIikuZXZlcnkoKGU9Pm8uaW5jbHVkZXMoZSkpKTtyZXR1cm4gcyYmbn19KSk7cmV0dXJuISFyfSkoeSxnKTtlJiYhdCYmKGM9ZSl9aWYoIWMpdGhyb3cgbmV3IHQoZyx5KTtsLmJvZHk9cD9zKE9iamVjdC5hc3NpZ24oT2JqZWN0LmFzc2lnbih7fSxlKSx7cmVmcmVzaF90b2tlbjpjfSkpOkpTT04uc3RyaW5naWZ5KE9iamVjdC5hc3NpZ24oT2JqZWN0LmFzc2lnbih7fSxlKSx7cmVmcmVzaF90b2tlbjpjfSkpfWxldCBhLGs7ImZ1bmN0aW9uIj09dHlwZW9mIEFib3J0Q29udHJvbGxlciYmKGE9bmV3IEFib3J0Q29udHJvbGxlcixsLnNpZ25hbD1hLnNpZ25hbCk7dHJ5e2s9YXdhaXQgUHJvbWlzZS5yYWNlKFsoaj1pLG5ldyBQcm9taXNlKChlPT5zZXRUaW1lb3V0KGUsaikpKSksZmV0Y2goZixPYmplY3QuYXNzaWduKHt9LGwpKV0pfWNhdGNoKGUpe3JldHVybiB2b2lkIHUucG9zdE1lc3NhZ2Uoe2Vycm9yOmUubWVzc2FnZX0pfWlmKCFrKXJldHVybiBhJiZhLmFib3J0KCksdm9pZCB1LnBvc3RNZXNzYWdlKHtlcnJvcjoiVGltZW91dCB3aGVuIGV4ZWN1dGluZyAnZmV0Y2gnIn0pO189ay5oZWFkZXJzLGQ9Wy4uLl9dLnJlZHVjZSgoKGUsdCk9PntsZXRbcixzXT10O3JldHVybiBlW3JdPXMsZX0pLHt9KSxyPWF3YWl0IGsuanNvbigpLHIucmVmcmVzaF90b2tlbj8oaCYmKG8ubGF0ZXN0X3JlZnJlc2hfdG9rZW49ci5yZWZyZXNoX3Rva2VuLE89YyxiPXIucmVmcmVzaF90b2tlbixPYmplY3QuZW50cmllcyhvKS5mb3JFYWNoKChlPT57bGV0W3Qscl09ZTtyPT09TyYmKG9bdF09Yil9KSkpLCgoZSx0LHIpPT57b1tuKHQscildPWV9KShyLnJlZnJlc2hfdG9rZW4sZyx5KSxkZWxldGUgci5yZWZyZXNoX3Rva2VuKTooKGUsdCk9PntkZWxldGUgb1tuKGUsdCldfSkoZyx5KSx1LnBvc3RNZXNzYWdlKHtvazprLm9rLGpzb246cixoZWFkZXJzOmR9KX1jYXRjaChlKXt1LnBvc3RNZXNzYWdlKHtvazohMSxqc29uOntlcnJvcjplLmVycm9yLGVycm9yX2Rlc2NyaXB0aW9uOmUubWVzc2FnZX0saGVhZGVyczpkfSl9dmFyIE8sYixfLGp9KSl9KCk7Cgo=",De=null,Ke=false,function(e){return Le=Le||Ce(je,De,Ke),new Worker(Le,e)});const Ne={},We=async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:3;for(let n=0;n<t;n++)if(await e())return true;return false};class ze{constructor(e,t){this.cache=e,this.clientId=t,this.manifestKey=this.createManifestKeyFrom(this.clientId);}async add(e){var t;const n=new Set((null===(t=await this.cache.get(this.manifestKey))||void 0===t?void 0:t.keys)||[]);n.add(e),await this.cache.set(this.manifestKey,{keys:[...n]});}async remove(e){const t=await this.cache.get(this.manifestKey);if(t){const n=new Set(t.keys);return n.delete(e),n.size>0?await this.cache.set(this.manifestKey,{keys:[...n]}):await this.cache.remove(this.manifestKey)}}get(){return this.cache.get(this.manifestKey)}clear(){return this.cache.remove(this.manifestKey)}createManifestKeyFrom(e){return "".concat("@@auth0spajs@@","::").concat(e)}}const He={memory:()=>(new pe).enclosedCache,localstorage:()=>new he},Me=e=>He[e],Je=t=>{const{openUrl:n,onRedirect:o}=t,r=e(t,["openUrl","onRedirect"]);return Object.assign(Object.assign({},r),{openUrl:false===n||n?n:o})},Ve=(e,t)=>{const n=(null==t?void 0:t.split(" "))||[];return ((null==e?void 0:e.split(" "))||[]).every((e=>n.includes(e)))},Fe={NONCE:"nonce",KEYPAIR:"keypair"};class Ge{constructor(e){this.clientId=e;}getVersion(){return 1}createDbHandle(){const e=window.indexedDB.open("auth0-spa-js",this.getVersion());return new Promise(((t,n)=>{e.onupgradeneeded=()=>Object.values(Fe).forEach((t=>e.result.createObjectStore(t))),e.onerror=()=>n(e.error),e.onsuccess=()=>t(e.result);}))}async getDbHandle(){return this.dbHandle||(this.dbHandle=await this.createDbHandle()),this.dbHandle}async executeDbRequest(e,t,n){const o=n((await this.getDbHandle()).transaction(e,t).objectStore(e));return new Promise(((e,t)=>{o.onsuccess=()=>e(o.result),o.onerror=()=>t(o.error);}))}buildKey(e){const t=e?"_".concat(e):"auth0";return "".concat(this.clientId,"::").concat(t)}setNonce(e,t){return this.save(Fe.NONCE,this.buildKey(t),e)}setKeyPair(e){return this.save(Fe.KEYPAIR,this.buildKey(),e)}async save(e,t,n){await this.executeDbRequest(e,"readwrite",(e=>e.put(n,t)));}findNonce(e){return this.find(Fe.NONCE,this.buildKey(e))}findKeyPair(){return this.find(Fe.KEYPAIR,this.buildKey())}find(e,t){return this.executeDbRequest(e,"readonly",(e=>e.get(t)))}async deleteBy(e,t){const n=await this.executeDbRequest(e,"readonly",(e=>e.getAllKeys()));null==n||n.filter(t).map((t=>this.executeDbRequest(e,"readwrite",(e=>e.delete(t)))));}deleteByClientId(e,t){return this.deleteBy(e,(e=>"string"==typeof e&&e.startsWith("".concat(t,"::"))))}clearNonces(){return this.deleteByClientId(Fe.NONCE,this.clientId)}clearKeyPairs(){return this.deleteByClientId(Fe.KEYPAIR,this.clientId)}}class Ze{constructor(e){this.storage=new Ge(e);}getNonce(e){return this.storage.findNonce(e)}setNonce(e,t){return this.storage.setNonce(e,t)}async getOrGenerateKeyPair(){let e=await this.storage.findKeyPair();return e||(e=await $(),await this.storage.setKeyPair(e)),e}async generateProof(e){const t=await this.getOrGenerateKeyPair();return te(Object.assign({keyPair:t},e))}async calculateThumbprint(){return ee(await this.getOrGenerateKeyPair())}async clear(){await Promise.all([this.storage.clearNonces(),this.storage.clearKeyPairs()]);}}var qe;!function(e){e.Bearer="Bearer",e.DPoP="DPoP";}(qe||(qe={}));class Be{constructor(e,t){this.hooks=t,this.config=Object.assign(Object.assign({},e),{fetch:e.fetch||("undefined"==typeof window?fetch:window.fetch.bind(window))});}isAbsoluteUrl(e){return /^(https?:)?\/\//i.test(e)}buildUrl(e,t){if(t){if(this.isAbsoluteUrl(t))return t;if(e)return "".concat(e.replace(/\/?\/$/,""),"/").concat(t.replace(/^\/+/,""))}throw new TypeError("`url` must be absolute or `baseUrl` non-empty.")}getAccessToken(e){return this.config.getAccessToken?this.config.getAccessToken(e):this.hooks.getAccessToken(e)}extractUrl(e){return "string"==typeof e?e:e instanceof URL?e.href:e.url}buildBaseRequest(e,t){if(!this.config.baseUrl)return new Request(e,t);const n=this.buildUrl(this.config.baseUrl,this.extractUrl(e)),o=e instanceof Request?new Request(n,e):n;return new Request(o,t)}setAuthorizationHeader(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:qe.Bearer;e.headers.set("authorization","".concat(n," ").concat(t));}async setDpopProofHeader(e,t){if(!this.config.dpopNonceId)return;const n=await this.hooks.getDpopNonce(),o=await this.hooks.generateDpopProof({accessToken:t,method:e.method,nonce:n,url:e.url});e.headers.set("dpop",o);}async prepareRequest(e,t){const n=await this.getAccessToken(t);let o,r;"string"==typeof n?(o=this.config.dpopNonceId?qe.DPoP:qe.Bearer,r=n):(o=n.token_type,r=n.access_token),this.setAuthorizationHeader(e,r,o),o===qe.DPoP&&await this.setDpopProofHeader(e,r);}getHeader(e,t){return Array.isArray(e)?new Headers(e).get(t)||"":"function"==typeof e.get?e.get(t)||"":e[t]||""}hasUseDpopNonceError(e){if(401!==e.status)return false;const t=this.getHeader(e.headers,"www-authenticate");return t.includes("invalid_dpop_nonce")||t.includes("use_dpop_nonce")}async handleResponse(e,t){const n=this.getHeader(e.headers,"dpop-nonce");if(n&&await this.hooks.setDpopNonce(n),!this.hasUseDpopNonceError(e))return e;if(!n||!t.onUseDpopNonceError)throw new P(n);return t.onUseDpopNonceError()}async internalFetchWithAuth(e,t,n,o){const r=this.buildBaseRequest(e,t);await this.prepareRequest(r,o);const i=await this.config.fetch(r);return this.handleResponse(i,n)}fetchWithAuth(e,t,n){const o={onUseDpopNonceError:()=>this.internalFetchWithAuth(e,t,Object.assign(Object.assign({},o),{onUseDpopNonceError:void 0}),n)};return this.internalFetchWithAuth(e,t,o,n)}}class Xe{constructor(e,t){this.myAccountFetcher=e,this.apiBase=t;}async connectAccount(e){const t=await this.myAccountFetcher.fetchWithAuth("".concat(this.apiBase,"v1/connected-accounts/connect"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});return this._handleResponse(t)}async completeAccount(e){const t=await this.myAccountFetcher.fetchWithAuth("".concat(this.apiBase,"v1/connected-accounts/complete"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});return this._handleResponse(t)}async _handleResponse(e){let t;try{t=await e.text(),t=JSON.parse(t);}catch(n){throw new Ye({type:"invalid_json",status:e.status,title:"Invalid JSON response",detail:t||String(n)})}if(e.ok)return t;throw new Ye(t)}}class Ye extends Error{constructor(e){let{type:t,status:n,title:o,detail:r,validation_errors:i}=e;super(r),this.name="MyAccountApiError",this.type=t,this.status=n,this.title=o,this.detail=r,this.validation_errors=i,Object.setPrototypeOf(this,Ye.prototype);}}const Qe={otp:{authenticatorTypes:["otp"]},sms:{authenticatorTypes:["oob"],oobChannels:["sms"]},email:{authenticatorTypes:["oob"],oobChannels:["email"]},push:{authenticatorTypes:["oob"],oobChannels:["auth0"]},voice:{authenticatorTypes:["oob"],oobChannels:["voice"]}},$e="http://auth0.com/oauth/grant-type/mfa-otp",et="http://auth0.com/oauth/grant-type/mfa-oob",tt="http://auth0.com/oauth/grant-type/mfa-recovery-code";function nt(e,t){this.v=e,this.k=t;}function ot(e,t,n){if("function"==typeof e?e===t:e.has(t))return arguments.length<3?t:n;throw new TypeError("Private element is not present on this object")}function rt(e){return new nt(e,0)}function it(e,t){if(t.has(e))throw new TypeError("Cannot initialize the same private elements twice on an object")}function at(e,t){return e.get(ot(e,t))}function st(e,t,n){it(e,t),t.set(e,n);}function ct(e,t,n){return e.set(ot(e,t),n),n}function ut(e,t,n){return (t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var o=n.call(e,t);if("object"!=typeof o)return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return ("string"===t?String:Number)(e)}(e,"string");return "symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:true,configurable:true,writable:true}):e[t]=n,e}function lt(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);t&&(o=o.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,o);}return n}function dt(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?lt(Object(n),true).forEach((function(t){ut(e,t,n[t]);})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):lt(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t));}));}return e}function ht(e,t){if(null==e)return {};var n,o,r=function(e,t){if(null==e)return {};var n={};for(var o in e)if({}.hasOwnProperty.call(e,o)){if(-1!==t.indexOf(o))continue;n[o]=e[o];}return n}(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(o=0;o<i.length;o++)n=i[o],-1===t.indexOf(n)&&{}.propertyIsEnumerable.call(e,n)&&(r[n]=e[n]);}return r}function pt(e){return function(){return new ft(e.apply(this,arguments))}}function ft(e){var t,n;function o(t,n){try{var i=e[t](n),a=i.value,s=a instanceof nt;Promise.resolve(s?a.v:a).then((function(n){if(s){var c="return"===t?"return":"next";if(!a.k||n.done)return o(c,n);n=e[c](n).value;}r(i.done?"return":"normal",n);}),(function(e){o("throw",e);}));}catch(e){r("throw",e);}}function r(e,r){switch(e){case "return":t.resolve({value:r,done:true});break;case "throw":t.reject(r);break;default:t.resolve({value:r,done:false});}(t=t.next)?o(t.key,t.arg):n=null;}this._invoke=function(e,r){return new Promise((function(i,a){var s={key:e,arg:r,resolve:i,reject:a,next:null};n?n=n.next=s:(t=n=s,o(e,r));}))},"function"!=typeof e.return&&(this.return=void 0);}var mt,yt;let wt;if(ft.prototype["function"==typeof Symbol&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this},ft.prototype.next=function(e){return this._invoke("next",e)},ft.prototype.throw=function(e){return this._invoke("throw",e)},ft.prototype.return=function(e){return this._invoke("return",e)},"undefined"==typeof navigator||null===(mt=navigator.userAgent)||void 0===mt||null===(yt=mt.startsWith)||void 0===yt||!yt.call(mt,"Mozilla/5.0 ")){const e="v3.8.3";wt="".concat("oauth4webapi","/").concat(e);}function gt(e,t){if(null==e)return false;try{return e instanceof t||Object.getPrototypeOf(e)[Symbol.toStringTag]===t.prototype[Symbol.toStringTag]}catch(e){return false}}function vt(e,t,n){const o=new TypeError(e,{cause:n});return Object.assign(o,{code:t}),o}const bt=Symbol(),_t=Symbol(),kt=Symbol(),St=Symbol(),At=Symbol(),Tt=new TextEncoder,Pt=new TextDecoder;function Rt(e){return "string"==typeof e?Tt.encode(e):Pt.decode(e)}let It,Ot;if(Uint8Array.prototype.toBase64)It=e=>(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e.toBase64({alphabet:"base64url",omitPadding:true}));else {const e=32768;It=t=>{t instanceof ArrayBuffer&&(t=new Uint8Array(t));const n=[];for(let o=0;o<t.byteLength;o+=e)n.push(String.fromCharCode.apply(null,t.subarray(o,o+e)));return btoa(n.join("")).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")};}function xt(e){return "string"==typeof e?Ot(e):It(e)}Ot=Uint8Array.fromBase64?e=>{try{return Uint8Array.fromBase64(e,{alphabet:"base64url"})}catch(e){throw vt("The input to be decoded is not correctly encoded.","ERR_INVALID_ARG_VALUE",e)}}:e=>{try{const t=atob(e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"")),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}catch(e){throw vt("The input to be decoded is not correctly encoded.","ERR_INVALID_ARG_VALUE",e)}};class Ct extends Error{constructor(e,t){var n;super(e,t),ut(this,"code",void 0),this.name=this.constructor.name,this.code=Cn,null===(n=Error.captureStackTrace)||void 0===n||n.call(Error,this,this.constructor);}}class jt extends Error{constructor(e,t){var n;super(e,t),ut(this,"code",void 0),this.name=this.constructor.name,null!=t&&t.code&&(this.code=null==t?void 0:t.code),null===(n=Error.captureStackTrace)||void 0===n||n.call(Error,this,this.constructor);}}function Dt(e,t,n){return new jt(e,{code:t,cause:n})}function Kt(e,t){if(function(e,t){if(!(e instanceof CryptoKey))throw vt("".concat(t," must be a CryptoKey"),"ERR_INVALID_ARG_TYPE")}(e,t),"private"!==e.type)throw vt("".concat(t," must be a private CryptoKey"),"ERR_INVALID_ARG_VALUE")}function Lt(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function Ut(e){gt(e,Headers)&&(e=Object.fromEntries(e.entries()));const t=new Headers(null!=e?e:{});if(wt&&!t.has("user-agent")&&t.set("user-agent",wt),t.has("authorization"))throw vt('"options.headers" must not include the "authorization" header name',"ERR_INVALID_ARG_VALUE");return t}function Nt(e,t){if(void 0!==t){if("function"==typeof t&&(t=t(e.href)),!(t instanceof AbortSignal))throw vt('"options.signal" must return or be an instance of AbortSignal',"ERR_INVALID_ARG_TYPE");return t}}function Wt(e){return e.includes("//")?e.replace("//","/"):e}async function zt(e,t){return async function(e,t,n,o){if(!(e instanceof URL))throw vt('"'.concat(t,'" must be an instance of URL'),"ERR_INVALID_ARG_TYPE");en(e,true!==(null==o?void 0:o[bt]));const r=n(new URL(e.href)),i=Ut(null==o?void 0:o.headers);return i.set("accept","application/json"),((null==o?void 0:o[St])||fetch)(r.href,{body:void 0,headers:Object.fromEntries(i.entries()),method:"GET",redirect:"manual",signal:Nt(r,null==o?void 0:o.signal)})}(e,"issuerIdentifier",(e=>{switch(null==t?void 0:t.algorithm){case void 0:case "oidc":!function(e,t){e.pathname=Wt("".concat(e.pathname,"/").concat(t));}(e,".well-known/openid-configuration");break;case "oauth2":!function(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];"/"===e.pathname?e.pathname=t:e.pathname=Wt("".concat(t,"/").concat(n?e.pathname:e.pathname.replace(/(\/)$/,"")));}(e,".well-known/oauth-authorization-server");break;default:throw vt('"options.algorithm" must be "oidc" (default), or "oauth2"',"ERR_INVALID_ARG_VALUE")}return e}),t)}function Ht(e,t,n,o,r){try{if("number"!=typeof e||!Number.isFinite(e))throw vt("".concat(n," must be a number"),"ERR_INVALID_ARG_TYPE",r);if(e>0)return;if(t){if(0!==e)throw vt("".concat(n," must be a non-negative number"),"ERR_INVALID_ARG_VALUE",r);return}throw vt("".concat(n," must be a positive number"),"ERR_INVALID_ARG_VALUE",r)}catch(e){if(o)throw Dt(e.message,o,r);throw e}}function Mt(e,t,n,o){try{if("string"!=typeof e)throw vt("".concat(t," must be a string"),"ERR_INVALID_ARG_TYPE",o);if(0===e.length)throw vt("".concat(t," must not be empty"),"ERR_INVALID_ARG_VALUE",o)}catch(e){if(n)throw Dt(e.message,n,o);throw e}}function Jt(e){!function(e,t){if(fn(e)!==t)throw function(e){let t='"response" content-type must be ';for(var n=arguments.length,o=new Array(n>1?n-1:0),r=1;r<n;r++)o[r-1]=arguments[r];if(o.length>2){const e=o.pop();t+="".concat(o.join(", "),", or ").concat(e);}else 2===o.length?t+="".concat(o[0]," or ").concat(o[1]):t+=o[0];return Dt(t,Ln,e)}(e,t)}(e,"application/json");}function Vt(){return xt(crypto.getRandomValues(new Uint8Array(32)))}function Ft(e){switch(e.algorithm.name){case "RSA-PSS":return function(e){switch(e.algorithm.hash.name){case "SHA-256":return "PS256";case "SHA-384":return "PS384";case "SHA-512":return "PS512";default:throw new Ct("unsupported RsaHashedKeyAlgorithm hash name",{cause:e})}}(e);case "RSASSA-PKCS1-v1_5":return function(e){switch(e.algorithm.hash.name){case "SHA-256":return "RS256";case "SHA-384":return "RS384";case "SHA-512":return "RS512";default:throw new Ct("unsupported RsaHashedKeyAlgorithm hash name",{cause:e})}}(e);case "ECDSA":return function(e){switch(e.algorithm.namedCurve){case "P-256":return "ES256";case "P-384":return "ES384";case "P-521":return "ES512";default:throw new Ct("unsupported EcKeyAlgorithm namedCurve",{cause:e})}}(e);case "Ed25519":case "ML-DSA-44":case "ML-DSA-65":case "ML-DSA-87":return e.algorithm.name;case "EdDSA":return "Ed25519";default:throw new Ct("unsupported CryptoKey algorithm name",{cause:e})}}function Gt(e){const t=null==e?void 0:e[_t];return "number"==typeof t&&Number.isFinite(t)?t:0}function Zt(e){const t=null==e?void 0:e[kt];return "number"==typeof t&&Number.isFinite(t)&&-1!==Math.sign(t)?t:30}function qt(){return Math.floor(Date.now()/1e3)}function Bt(e){if("object"!=typeof e||null===e)throw vt('"as" must be an object',"ERR_INVALID_ARG_TYPE");Mt(e.issuer,'"as.issuer"');}function Xt(e){if("object"!=typeof e||null===e)throw vt('"client" must be an object',"ERR_INVALID_ARG_TYPE");Mt(e.client_id,'"client.client_id"');}function Yt(e){return Mt(e,'"clientSecret"'),(t,n,o,r)=>{o.set("client_id",n.client_id),o.set("client_secret",e);}}function Qt(e,t){const{key:n,kid:o}=(r=e)instanceof CryptoKey?{key:r}:(null==r?void 0:r.key)instanceof CryptoKey?(void 0!==r.kid&&Mt(r.kid,'"kid"'),{key:r.key,kid:r.kid}):{};var r;return Kt(n,'"clientPrivateKey.key"'),async(e,r,i,a)=>{const c={alg:Ft(n),kid:o},u=function(e,t){const n=qt()+Gt(t);return {jti:Vt(),aud:e.issuer,exp:n+60,iat:n,nbf:n,iss:t.client_id,sub:t.client_id}}(e,r);i.set("client_id",r.client_id),i.set("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),i.set("client_assertion",await async function(e,t,n){if(!n.usages.includes("sign"))throw vt('CryptoKey instances used for signing assertions must include "sign" in their "usages"',"ERR_INVALID_ARG_VALUE");const o="".concat(xt(Rt(JSON.stringify(e))),".").concat(xt(Rt(JSON.stringify(t)))),r=xt(await crypto.subtle.sign(function(e){switch(e.algorithm.name){case "ECDSA":return {name:e.algorithm.name,hash:Zn(e)};case "RSA-PSS":switch(Gn(e),e.algorithm.hash.name){case "SHA-256":case "SHA-384":case "SHA-512":return {name:e.algorithm.name,saltLength:parseInt(e.algorithm.hash.name.slice(-3),10)>>3};default:throw new Ct("unsupported RSA-PSS hash name",{cause:e})}case "RSASSA-PKCS1-v1_5":return Gn(e),e.algorithm.name;case "ML-DSA-44":case "ML-DSA-65":case "ML-DSA-87":case "Ed25519":return e.algorithm.name}throw new Ct("unsupported CryptoKey algorithm name",{cause:e})}(n),n,Rt(o)));return "".concat(o,".").concat(r)}(c,u,n));}}const $t=URL.parse?(e,t)=>URL.parse(e,t):(e,t)=>{try{return new URL(e,t)}catch(e){return null}};function en(e,t){if(t&&"https:"!==e.protocol)throw Dt("only requests to HTTPS are allowed",Nn,e);if("https:"!==e.protocol&&"http:"!==e.protocol)throw Dt("only HTTP and HTTPS requests are allowed",Wn,e)}function tn(e,t,n,o){let r;if("string"!=typeof e||!(r=$t(e)))throw Dt("authorization server metadata does not contain a valid ".concat(n?'"as.mtls_endpoint_aliases.'.concat(t,'"'):'"as.'.concat(t,'"')),void 0===e?Jn:Vn,{attribute:n?"mtls_endpoint_aliases.".concat(t):t});return en(r,o),r}function nn(e,t,n,o){return n&&e.mtls_endpoint_aliases&&t in e.mtls_endpoint_aliases?tn(e.mtls_endpoint_aliases[t],t,n,o):tn(e[t],t,n,o)}class on extends Error{constructor(e,t){var n;super(e,t),ut(this,"cause",void 0),ut(this,"code",void 0),ut(this,"error",void 0),ut(this,"status",void 0),ut(this,"error_description",void 0),ut(this,"response",void 0),this.name=this.constructor.name,this.code=xn,this.cause=t.cause,this.error=t.cause.error,this.status=t.response.status,this.error_description=t.cause.error_description,Object.defineProperty(this,"response",{enumerable:false,value:t.response}),null===(n=Error.captureStackTrace)||void 0===n||n.call(Error,this,this.constructor);}}class rn extends Error{constructor(e,t){var n,o;super(e,t),ut(this,"cause",void 0),ut(this,"code",void 0),ut(this,"error",void 0),ut(this,"error_description",void 0),this.name=this.constructor.name,this.code=jn,this.cause=t.cause,this.error=t.cause.get("error"),this.error_description=null!==(n=t.cause.get("error_description"))&&void 0!==n?n:void 0,null===(o=Error.captureStackTrace)||void 0===o||o.call(Error,this,this.constructor);}}class an extends Error{constructor(e,t){var n;super(e,t),ut(this,"cause",void 0),ut(this,"code",void 0),ut(this,"response",void 0),ut(this,"status",void 0),this.name=this.constructor.name,this.code=On,this.cause=t.cause,this.status=t.response.status,this.response=t.response,Object.defineProperty(this,"response",{enumerable:false}),null===(n=Error.captureStackTrace)||void 0===n||n.call(Error,this,this.constructor);}}const sn="[a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+",cn=new RegExp("^[,\\s]*("+sn+")"),un=new RegExp('^[,\\s]*([a-zA-Z0-9!#$%&\\\'\\*\\+\\-\\.\\^_`\\|~]+)\\s*=\\s*"((?:[^"\\\\]|\\\\[\\s\\S])*)"[,\\s]*(.*)'),ln=new RegExp("^[,\\s]*([a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+)\\s*=\\s*([a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+)[,\\s]*(.*)"),dn=new RegExp("^([a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2})(?:$|[,\\s])(.*)");async function hn(e,t,n){if(e.status!==t){let t;var o;if(function(e){let t;if(t=function(e){if(!gt(e,Response))throw vt('"response" must be an instance of Response',"ERR_INVALID_ARG_TYPE");const t=e.headers.get("www-authenticate");if(null===t)return;const n=[];let o=t;for(;o;){var r;let e=o.match(cn);const t=null===(r=e)||void 0===r?void 0:r[1].toLowerCase();if(!t)return;const i=o.substring(e[0].length);if(i&&!i.match(/^[\s,]/))return;const a=i.match(/^\s+(.*)$/),s=!!a;o=a?a[1]:void 0;const c={};let u;if(s)for(;o;){let t,n;if(e=o.match(un)){if([,t,n,o]=e,n.includes("\\"))try{n=JSON.parse('"'.concat(n,'"'));}catch(e){}c[t.toLowerCase()]=n;}else {if(!(e=o.match(ln))){if(e=o.match(dn)){if(Object.keys(c).length)break;[,u,o]=e;break}return}[,t,n,o]=e,c[t.toLowerCase()]=n;}}else o=i||void 0;const l={scheme:t,parameters:c};u&&(l.token68=u),n.push(l);}return n.length?n:void 0}(e))throw new an("server responded with a challenge in the WWW-Authenticate HTTP Header",{cause:t,response:e})}(e),t=await async function(e){if(e.status>399&&e.status<500){Fn(e),Jt(e);try{const t=await e.clone().json();if(Lt(t)&&"string"==typeof t.error&&t.error.length)return t}catch(e){}}}(e))throw await(null===(o=e.body)||void 0===o?void 0:o.cancel()),new on("server responded with an error in the response body",{cause:t,response:e});throw Dt('"response" is not a conform '.concat(n," response (unexpected HTTP status code)"),Un,e)}}function pn(e){if(!Sn.has(e))throw vt('"options.DPoP" is not a valid DPoPHandle',"ERR_INVALID_ARG_VALUE")}function fn(e){var t;return null===(t=e.headers.get("content-type"))||void 0===t?void 0:t.split(";")[0]}async function mn(e,t,n,o,r,i,a){return await n(e,t,r,i),i.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"),((null==a?void 0:a[St])||fetch)(o.href,{body:r,headers:Object.fromEntries(i.entries()),method:"POST",redirect:"manual",signal:Nt(o,null==a?void 0:a.signal)})}async function yn(e,t,n,o,r,i){var a;const s=nn(e,"token_endpoint",t.use_mtls_endpoint_aliases,true!==(null==i?void 0:i[bt]));r.set("grant_type",o);const c=Ut(null==i?void 0:i.headers);c.set("accept","application/json"),void 0!==(null==i?void 0:i.DPoP)&&(pn(i.DPoP),await i.DPoP.addProof(s,c,"POST"));const u=await mn(e,t,n,s,r,c,i);return null==i||null===(a=i.DPoP)||void 0===a||a.cacheNonce(u,s),u}const wn=new WeakMap,gn=new WeakMap;function vn(e){if(!e.id_token)return;const t=wn.get(e);if(!t)throw vt('"ref" was already garbage collected or did not resolve from the proper sources',"ERR_INVALID_ARG_VALUE");return t}async function bn(e,t,n,o,r,i){if(Bt(e),Xt(t),!gt(n,Response))throw vt('"response" must be an instance of Response',"ERR_INVALID_ARG_TYPE");await hn(n,200,"Token Endpoint"),Fn(n);const a=await eo(n);if(Mt(a.access_token,'"response" body "access_token" property',Kn,{body:a}),Mt(a.token_type,'"response" body "token_type" property',Kn,{body:a}),a.token_type=a.token_type.toLowerCase(),void 0!==a.expires_in){let e="number"!=typeof a.expires_in?parseFloat(a.expires_in):a.expires_in;Ht(e,true,'"response" body "expires_in" property',Kn,{body:a}),a.expires_in=e;}if(void 0!==a.refresh_token&&Mt(a.refresh_token,'"response" body "refresh_token" property',Kn,{body:a}),void 0!==a.scope&&"string"!=typeof a.scope)throw Dt('"response" body "scope" property must be a string',Kn,{body:a});if(void 0!==a.id_token){Mt(a.id_token,'"response" body "id_token" property',Kn,{body:a});const i=["aud","exp","iat","iss","sub"];true===t.require_auth_time&&i.push("auth_time"),void 0!==t.default_max_age&&(Ht(t.default_max_age,true,'"client.default_max_age"'),i.push("auth_time")),null!=o&&o.length&&i.push(...o);const{claims:s,jwt:c}=await async function(e,t,n,o,r){let i,a,{0:s,1:c,length:u}=e.split(".");if(5===u){if(void 0===r)throw new Ct("JWE decryption is not configured",{cause:e});e=await r(e),({0:s,1:c,length:u}=e.split("."));}if(3!==u)throw Dt("Invalid JWT",Kn,e);try{i=JSON.parse(Rt(xt(s)));}catch(e){throw Dt("failed to parse JWT Header body as base64url encoded JSON",Dn,e)}if(!Lt(i))throw Dt("JWT Header must be a top level object",Kn,e);if(t(i),void 0!==i.crit)throw new Ct('no JWT "crit" header parameter extensions are supported',{cause:{header:i}});try{a=JSON.parse(Rt(xt(c)));}catch(e){throw Dt("failed to parse JWT Payload body as base64url encoded JSON",Dn,e)}if(!Lt(a))throw Dt("JWT Payload must be a top level object",Kn,e);const l=qt()+n;if(void 0!==a.exp){if("number"!=typeof a.exp)throw Dt('unexpected JWT "exp" (expiration time) claim type',Kn,{claims:a});if(a.exp<=l-o)throw Dt('unexpected JWT "exp" (expiration time) claim value, expiration is past current timestamp',zn,{claims:a,now:l,tolerance:o,claim:"exp"})}if(void 0!==a.iat&&"number"!=typeof a.iat)throw Dt('unexpected JWT "iat" (issued at) claim type',Kn,{claims:a});if(void 0!==a.iss&&"string"!=typeof a.iss)throw Dt('unexpected JWT "iss" (issuer) claim type',Kn,{claims:a});if(void 0!==a.nbf){if("number"!=typeof a.nbf)throw Dt('unexpected JWT "nbf" (not before) claim type',Kn,{claims:a});if(a.nbf>l+o)throw Dt('unexpected JWT "nbf" (not before) claim value',zn,{claims:a,now:l,tolerance:o,claim:"nbf"})}if(void 0!==a.aud&&"string"!=typeof a.aud&&!Array.isArray(a.aud))throw Dt('unexpected JWT "aud" (audience) claim type',Kn,{claims:a});return {header:i,claims:a,jwt:e}}(a.id_token,Bn.bind(void 0,t.id_token_signed_response_alg,e.id_token_signing_alg_values_supported,"RS256"),Gt(t),Zt(t),r).then(Tn.bind(void 0,i)).then(kn.bind(void 0,e)).then(_n.bind(void 0,t.client_id));if(Array.isArray(s.aud)&&1!==s.aud.length){if(void 0===s.azp)throw Dt('ID Token "aud" (audience) claim includes additional untrusted audiences',Hn,{claims:s,claim:"aud"});if(s.azp!==t.client_id)throw Dt('unexpected ID Token "azp" (authorized party) claim value',Hn,{expected:t.client_id,claims:s,claim:"azp"})} void 0!==s.auth_time&&Ht(s.auth_time,true,'ID Token "auth_time" (authentication time)',Kn,{claims:s}),gn.set(n,c),wn.set(a,s);}if(void 0!==(null==i?void 0:i[a.token_type]))i[a.token_type](n,a);else if("dpop"!==a.token_type&&"bearer"!==a.token_type)throw new Ct("unsupported `token_type` value",{cause:{body:a}});return a}function _n(e,t){if(Array.isArray(t.claims.aud)){if(!t.claims.aud.includes(e))throw Dt('unexpected JWT "aud" (audience) claim value',Hn,{expected:e,claims:t.claims,claim:"aud"})}else if(t.claims.aud!==e)throw Dt('unexpected JWT "aud" (audience) claim value',Hn,{expected:e,claims:t.claims,claim:"aud"});return t}function kn(e,t){var n,o;const r=null!==(n=null===(o=e[no])||void 0===o?void 0:o.call(e,t))&&void 0!==n?n:e.issuer;if(t.claims.iss!==r)throw Dt('unexpected JWT "iss" (issuer) claim value',Hn,{expected:r,claims:t.claims,claim:"iss"});return t}const Sn=new WeakSet;const En=Symbol();const An={aud:"audience",c_hash:"code hash",client_id:"client id",exp:"expiration time",iat:"issued at",iss:"issuer",jti:"jwt id",nonce:"nonce",s_hash:"state hash",sub:"subject",ath:"access token hash",htm:"http method",htu:"http uri",cnf:"confirmation",auth_time:"authentication time"};function Tn(e,t){for(const n of e)if(void 0===t.claims[n])throw Dt('JWT "'.concat(n,'" (').concat(An[n],") claim missing"),Kn,{claims:t.claims});return t}const Pn=Symbol(),Rn=Symbol();async function In(e,t,n,o){return "string"==typeof(null==o?void 0:o.expectedNonce)||"number"==typeof(null==o?void 0:o.maxAge)||null!=o&&o.requireIdToken?async function(e,t,n,o,r,i,a){const s=[];switch(o){case void 0:o=Pn;break;case Pn:break;default:Mt(o,'"expectedNonce" argument'),s.push("nonce");}switch(null!=r||(r=t.default_max_age),r){case void 0:r=Rn;break;case Rn:break;default:Ht(r,true,'"maxAge" argument'),s.push("auth_time");}const c=await bn(e,t,n,s,i,a);Mt(c.id_token,'"response" body "id_token" property',Kn,{body:c});const u=vn(c);if(r!==Rn){const e=qt()+Gt(t),n=Zt(t);if(u.auth_time+r<e-n)throw Dt("too much time has elapsed since the last End-User authentication",zn,{claims:u,now:e,tolerance:n,claim:"auth_time"})}if(o===Pn){if(void 0!==u.nonce)throw Dt('unexpected ID Token "nonce" claim value',Hn,{expected:void 0,claims:u,claim:"nonce"})}else if(u.nonce!==o)throw Dt('unexpected ID Token "nonce" claim value',Hn,{expected:o,claims:u,claim:"nonce"});return c}(e,t,n,o.expectedNonce,o.maxAge,o[At],o.recognizedTokenTypes):async function(e,t,n,o,r){const i=await bn(e,t,n,void 0,o,r),a=vn(i);if(a){if(void 0!==t.default_max_age){Ht(t.default_max_age,true,'"client.default_max_age"');const e=qt()+Gt(t),n=Zt(t);if(a.auth_time+t.default_max_age<e-n)throw Dt("too much time has elapsed since the last End-User authentication",zn,{claims:a,now:e,tolerance:n,claim:"auth_time"})}if(void 0!==a.nonce)throw Dt('unexpected ID Token "nonce" claim value',Hn,{expected:void 0,claims:a,claim:"nonce"})}return i}(e,t,n,null==o?void 0:o[At],null==o?void 0:o.recognizedTokenTypes)}const On="OAUTH_WWW_AUTHENTICATE_CHALLENGE",xn="OAUTH_RESPONSE_BODY_ERROR",Cn="OAUTH_UNSUPPORTED_OPERATION",jn="OAUTH_AUTHORIZATION_RESPONSE_ERROR",Dn="OAUTH_PARSE_ERROR",Kn="OAUTH_INVALID_RESPONSE",Ln="OAUTH_RESPONSE_IS_NOT_JSON",Un="OAUTH_RESPONSE_IS_NOT_CONFORM",Nn="OAUTH_HTTP_REQUEST_FORBIDDEN",Wn="OAUTH_REQUEST_PROTOCOL_FORBIDDEN",zn="OAUTH_JWT_TIMESTAMP_CHECK_FAILED",Hn="OAUTH_JWT_CLAIM_COMPARISON_FAILED",Mn="OAUTH_JSON_ATTRIBUTE_COMPARISON_FAILED",Jn="OAUTH_MISSING_SERVER_METADATA",Vn="OAUTH_INVALID_SERVER_METADATA";function Fn(e){if(e.bodyUsed)throw vt('"response" body has been used already',"ERR_INVALID_ARG_VALUE")}function Gn(e){const{algorithm:t}=e;if("number"!=typeof t.modulusLength||t.modulusLength<2048)throw new Ct("unsupported ".concat(t.name," modulusLength"),{cause:e})}function Zn(e){const{algorithm:t}=e;switch(t.namedCurve){case "P-256":return "SHA-256";case "P-384":return "SHA-384";case "P-521":return "SHA-512";default:throw new Ct("unsupported ECDSA namedCurve",{cause:e})}}async function qn(e){if("POST"!==e.method)throw vt("form_post responses are expected to use the POST method","ERR_INVALID_ARG_VALUE",{cause:e});if("application/x-www-form-urlencoded"!==fn(e))throw vt("form_post responses are expected to use the application/x-www-form-urlencoded content-type","ERR_INVALID_ARG_VALUE",{cause:e});return async function(e){if(e.bodyUsed)throw vt("form_post Request instances must contain a readable body","ERR_INVALID_ARG_VALUE",{cause:e});return e.text()}(e)}function Bn(e,t,n,o){if(void 0===e)if(Array.isArray(t)){if(!t.includes(o.alg))throw Dt('unexpected JWT "alg" header parameter',Kn,{header:o,expected:t,reason:"authorization server metadata"})}else {if(void 0===n)throw Dt('missing client or server configuration to verify used JWT "alg" header parameter',void 0,{client:e,issuer:t,fallback:n});if("string"==typeof n?o.alg!==n:"function"==typeof n?!n(o.alg):!n.includes(o.alg))throw Dt('unexpected JWT "alg" header parameter',Kn,{header:o,expected:n,reason:"default value"})}else if("string"==typeof e?o.alg!==e:!e.includes(o.alg))throw Dt('unexpected JWT "alg" header parameter',Kn,{header:o,expected:e,reason:"client configuration"})}function Xn(e,t){const{0:n,length:o}=e.getAll(t);if(o>1)throw Dt('"'.concat(t,'" parameter must be provided only once'),Kn);return n}const Yn=Symbol(),Qn=Symbol();function $n(e,t,n,o){if(Bt(e),Xt(t),n instanceof URL&&(n=n.searchParams),!(n instanceof URLSearchParams))throw vt('"parameters" must be an instance of URLSearchParams, or URL',"ERR_INVALID_ARG_TYPE");if(Xn(n,"response"))throw Dt('"parameters" contains a JARM response, use validateJwtAuthResponse() instead of validateAuthResponse()',Kn,{parameters:n});const r=Xn(n,"iss"),i=Xn(n,"state");if(!r&&e.authorization_response_iss_parameter_supported)throw Dt('response parameter "iss" (issuer) missing',Kn,{parameters:n});if(r&&r!==e.issuer)throw Dt('unexpected "iss" (issuer) response parameter value',Kn,{expected:e.issuer,parameters:n});switch(o){case void 0:case Qn:if(void 0!==i)throw Dt('unexpected "state" response parameter encountered',Kn,{expected:void 0,parameters:n});break;case Yn:break;default:if(Mt(o,'"expectedState" argument'),i!==o)throw Dt(void 0===i?'response parameter "state" missing':'unexpected "state" response parameter value',Kn,{expected:o,parameters:n})}if(Xn(n,"error"))throw new rn("authorization response from the server is an error",{cause:n});const a=Xn(n,"id_token"),s=Xn(n,"token");if(void 0!==a||void 0!==s)throw new Ct("implicit and hybrid flows are not supported");return c=new URLSearchParams(n),Sn.add(c),c;var c;}async function eo(e){let t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Jt;try{t=await e.json();}catch(t){throw n(e),Dt('failed to parse "response" body as JSON',Dn,t)}if(!Lt(t))throw Dt('"response" body must be a top level object',Kn,{body:t});return t}const to=Symbol(),no=Symbol(),oo=new TextEncoder,ro=new TextDecoder;function io(e){const t=new Uint8Array(e.length);for(let n=0;n<e.length;n++){const o=e.charCodeAt(n);if(o>127)throw new TypeError("non-ASCII string encountered in encode()");t[n]=o;}return t}function ao(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);const t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function so(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64("string"==typeof e?e:ro.decode(e),{alphabet:"base64url"});let t=e;t instanceof Uint8Array&&(t=ro.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/");try{return ao(t)}catch(e){throw new TypeError("The input to be decoded is not correctly encoded.")}}class co extends Error{constructor(e,t){var n;super(e,t),ut(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,null===(n=Error.captureStackTrace)||void 0===n||n.call(Error,this,this.constructor);}}ut(co,"code","ERR_JOSE_GENERIC");class uo extends co{constructor(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"unspecified",o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"unspecified";super(e,{cause:{claim:n,reason:o,payload:t}}),ut(this,"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),ut(this,"claim",void 0),ut(this,"reason",void 0),ut(this,"payload",void 0),this.claim=n,this.reason=o,this.payload=t;}}ut(uo,"code","ERR_JWT_CLAIM_VALIDATION_FAILED");class lo extends co{constructor(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"unspecified",o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"unspecified";super(e,{cause:{claim:n,reason:o,payload:t}}),ut(this,"code","ERR_JWT_EXPIRED"),ut(this,"claim",void 0),ut(this,"reason",void 0),ut(this,"payload",void 0),this.claim=n,this.reason=o,this.payload=t;}}ut(lo,"code","ERR_JWT_EXPIRED");class ho extends co{constructor(){super(...arguments),ut(this,"code","ERR_JOSE_ALG_NOT_ALLOWED");}}ut(ho,"code","ERR_JOSE_ALG_NOT_ALLOWED");class po extends co{constructor(){super(...arguments),ut(this,"code","ERR_JOSE_NOT_SUPPORTED");}}ut(po,"code","ERR_JOSE_NOT_SUPPORTED");ut(class extends co{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"decryption operation failed",arguments.length>1?arguments[1]:void 0),ut(this,"code","ERR_JWE_DECRYPTION_FAILED");}},"code","ERR_JWE_DECRYPTION_FAILED");ut(class extends co{constructor(){super(...arguments),ut(this,"code","ERR_JWE_INVALID");}},"code","ERR_JWE_INVALID");class fo extends co{constructor(){super(...arguments),ut(this,"code","ERR_JWS_INVALID");}}ut(fo,"code","ERR_JWS_INVALID");class mo extends co{constructor(){super(...arguments),ut(this,"code","ERR_JWT_INVALID");}}ut(mo,"code","ERR_JWT_INVALID");ut(class extends co{constructor(){super(...arguments),ut(this,"code","ERR_JWK_INVALID");}},"code","ERR_JWK_INVALID");class yo extends co{constructor(){super(...arguments),ut(this,"code","ERR_JWKS_INVALID");}}ut(yo,"code","ERR_JWKS_INVALID");class wo extends co{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"no applicable key found in the JSON Web Key Set",arguments.length>1?arguments[1]:void 0),ut(this,"code","ERR_JWKS_NO_MATCHING_KEY");}}ut(wo,"code","ERR_JWKS_NO_MATCHING_KEY");class go extends co{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"multiple matching keys found in the JSON Web Key Set",arguments.length>1?arguments[1]:void 0),ut(this,Symbol.asyncIterator,void 0),ut(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");}}ut(go,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");class vo extends co{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"request timed out",arguments.length>1?arguments[1]:void 0),ut(this,"code","ERR_JWKS_TIMEOUT");}}ut(vo,"code","ERR_JWKS_TIMEOUT");class bo extends co{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"signature verification failed",arguments.length>1?arguments[1]:void 0),ut(this,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");}}ut(bo,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");const _o=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"algorithm.name";return new TypeError("CryptoKey does not support this operation, its ".concat(t," must be ").concat(e))},ko=(e,t)=>e.name===t;function So(e){return parseInt(e.name.slice(4),10)}function Eo(e,t,n){switch(t){case "HS256":case "HS384":case "HS512":{if(!ko(e.algorithm,"HMAC"))throw _o("HMAC");const n=parseInt(t.slice(2),10);if(So(e.algorithm.hash)!==n)throw _o("SHA-".concat(n),"algorithm.hash");break}case "RS256":case "RS384":case "RS512":{if(!ko(e.algorithm,"RSASSA-PKCS1-v1_5"))throw _o("RSASSA-PKCS1-v1_5");const n=parseInt(t.slice(2),10);if(So(e.algorithm.hash)!==n)throw _o("SHA-".concat(n),"algorithm.hash");break}case "PS256":case "PS384":case "PS512":{if(!ko(e.algorithm,"RSA-PSS"))throw _o("RSA-PSS");const n=parseInt(t.slice(2),10);if(So(e.algorithm.hash)!==n)throw _o("SHA-".concat(n),"algorithm.hash");break}case "Ed25519":case "EdDSA":if(!ko(e.algorithm,"Ed25519"))throw _o("Ed25519");break;case "ML-DSA-44":case "ML-DSA-65":case "ML-DSA-87":if(!ko(e.algorithm,t))throw _o(t);break;case "ES256":case "ES384":case "ES512":{if(!ko(e.algorithm,"ECDSA"))throw _o("ECDSA");const n=function(e){switch(e){case "ES256":return "P-256";case "ES384":return "P-384";case "ES512":return "P-521";default:throw new Error("unreachable")}}(t);if(e.algorithm.namedCurve!==n)throw _o(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}!function(e,t){if(!e.usages.includes(t))throw new TypeError("CryptoKey does not support this operation, its usages must include ".concat(t,"."))}(e,n);}function Ao(e,t){for(var n=arguments.length,o=new Array(n>2?n-2:0),r=2;r<n;r++)o[r-2]=arguments[r];if((o=o.filter(Boolean)).length>2){const t=o.pop();e+="one of type ".concat(o.join(", "),", or ").concat(t,".");}else 2===o.length?e+="one of type ".concat(o[0]," or ").concat(o[1],"."):e+="of type ".concat(o[0],".");if(null==t)e+=" Received ".concat(t);else if("function"==typeof t&&t.name)e+=" Received function ".concat(t.name);else if("object"==typeof t&&null!=t){var i;null!==(i=t.constructor)&&void 0!==i&&i.name&&(e+=" Received an instance of ".concat(t.constructor.name));}return e}const To=function(e,t){for(var n=arguments.length,o=new Array(n>2?n-2:0),r=2;r<n;r++)o[r-2]=arguments[r];return Ao("Key for the ".concat(e," algorithm must be "),t,...o)},Po=e=>{if("CryptoKey"===(null==e?void 0:e[Symbol.toStringTag]))return true;try{return e instanceof CryptoKey}catch(e){return false}},Ro=e=>"KeyObject"===(null==e?void 0:e[Symbol.toStringTag]),Io=e=>Po(e)||Ro(e);function Oo(e){if("object"!=typeof(t=e)||null===t||"[object Object]"!==Object.prototype.toString.call(e))return false;var t;if(null===Object.getPrototypeOf(e))return true;let n=e;for(;null!==Object.getPrototypeOf(n);)n=Object.getPrototypeOf(n);return Object.getPrototypeOf(e)===n}const xo=(e,t)=>{if(e.byteLength!==t.length)return false;for(let n=0;n<e.byteLength;n++)if(e[n]!==t[n])return false;return true},Co=e=>{const t=e.data[e.pos++];if(128&t){const n=127&t;let o=0;for(let t=0;t<n;t++)o=o<<8|e.data[e.pos++];return o}return t},jo=(e,t,n)=>{if(e.data[e.pos++]!==t)throw new Error(n)},Do=(e,t)=>{const n=e.data.subarray(e.pos,e.pos+t);return e.pos+=t,n};const Ko=e=>{const t=(e=>{jo(e,6,"Expected algorithm OID");const t=Co(e);return Do(e,t)})(e);if(xo(t,[43,101,110]))return "X25519";if(!xo(t,[42,134,72,206,61,2,1]))throw new Error("Unsupported key algorithm");jo(e,6,"Expected curve OID");const n=Co(e),o=Do(e,n);for(const{name:e,oid:t}of [{name:"P-256",oid:[42,134,72,206,61,3,1,7]},{name:"P-384",oid:[43,129,4,0,34]},{name:"P-521",oid:[43,129,4,0,35]}])if(xo(o,t))return e;throw new Error("Unsupported named curve")},Lo=async(e,t,n,o)=>{var r;let i,a;const c=()=>["sign"];switch(n){case "PS256":case "PS384":case "PS512":i={name:"RSA-PSS",hash:"SHA-".concat(n.slice(-3))},a=c();break;case "RS256":case "RS384":case "RS512":i={name:"RSASSA-PKCS1-v1_5",hash:"SHA-".concat(n.slice(-3))},a=c();break;case "RSA-OAEP":case "RSA-OAEP-256":case "RSA-OAEP-384":case "RSA-OAEP-512":i={name:"RSA-OAEP",hash:"SHA-".concat(parseInt(n.slice(-3),10)||1)},a=["decrypt","unwrapKey"];break;case "ES256":case "ES384":case "ES512":i={name:"ECDSA",namedCurve:{ES256:"P-256",ES384:"P-384",ES512:"P-521"}[n]},a=c();break;case "ECDH-ES":case "ECDH-ES+A128KW":case "ECDH-ES+A192KW":case "ECDH-ES+A256KW":try{const e=o.getNamedCurve(t);i="X25519"===e?{name:"X25519"}:{name:"ECDH",namedCurve:e};}catch(e){throw new po("Invalid or unsupported key format")}a=["deriveBits"];break;case "Ed25519":case "EdDSA":i={name:"Ed25519"},a=c();break;case "ML-DSA-44":case "ML-DSA-65":case "ML-DSA-87":i={name:n},a=c();break;default:throw new po('Invalid or unsupported "alg" (Algorithm) value')}return crypto.subtle.importKey(e,t,i,null!==(r=null==o?void 0:o.extractable)&&void 0!==r?r:false,a)},Uo=(e,t,n)=>{var o;const r=((e,t)=>ao(e.replace(t,"")))(e,/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g);let i=n;return null!=t&&null!==(o=t.startsWith)&&void 0!==o&&o.call(t,"ECDH-ES")&&(i||(i={}),i.getNamedCurve=e=>{const t={data:e,pos:0};return function(e){jo(e,48,"Invalid PKCS#8 structure"),Co(e),jo(e,2,"Expected version field");const t=Co(e);e.pos+=t,jo(e,48,"Expected algorithm identifier");Co(e);}(t),Ko(t)}),Lo("pkcs8",r,t,i)};async function No(e){var t,n;if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:o,keyUsages:r}=function(e){let t,n;switch(e.kty){case "AKP":switch(e.alg){case "ML-DSA-44":case "ML-DSA-65":case "ML-DSA-87":t={name:e.alg},n=e.priv?["sign"]:["verify"];break;default:throw new po('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case "RSA":switch(e.alg){case "PS256":case "PS384":case "PS512":t={name:"RSA-PSS",hash:"SHA-".concat(e.alg.slice(-3))},n=e.d?["sign"]:["verify"];break;case "RS256":case "RS384":case "RS512":t={name:"RSASSA-PKCS1-v1_5",hash:"SHA-".concat(e.alg.slice(-3))},n=e.d?["sign"]:["verify"];break;case "RSA-OAEP":case "RSA-OAEP-256":case "RSA-OAEP-384":case "RSA-OAEP-512":t={name:"RSA-OAEP",hash:"SHA-".concat(parseInt(e.alg.slice(-3),10)||1)},n=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new po('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case "EC":switch(e.alg){case "ES256":t={name:"ECDSA",namedCurve:"P-256"},n=e.d?["sign"]:["verify"];break;case "ES384":t={name:"ECDSA",namedCurve:"P-384"},n=e.d?["sign"]:["verify"];break;case "ES512":t={name:"ECDSA",namedCurve:"P-521"},n=e.d?["sign"]:["verify"];break;case "ECDH-ES":case "ECDH-ES+A128KW":case "ECDH-ES+A192KW":case "ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},n=e.d?["deriveBits"]:[];break;default:throw new po('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case "OKP":switch(e.alg){case "Ed25519":case "EdDSA":t={name:"Ed25519"},n=e.d?["sign"]:["verify"];break;case "ECDH-ES":case "ECDH-ES+A128KW":case "ECDH-ES+A192KW":case "ECDH-ES+A256KW":t={name:e.crv},n=e.d?["deriveBits"]:[];break;default:throw new po('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;default:throw new po('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return {algorithm:t,keyUsages:n}}(e),i=dt({},e);return "AKP"!==i.kty&&delete i.alg,delete i.use,crypto.subtle.importKey("jwk",i,o,null!==(t=e.ext)&&void 0!==t?t:!e.d&&!e.priv,null!==(n=e.key_ops)&&void 0!==n?n:r)}const Wo=e=>Oo(e)&&"string"==typeof e.kty;let zo;const Ho=async function(e,t,n){let o=arguments.length>3&&void 0!==arguments[3]&&arguments[3];zo||(zo=new WeakMap);let r=zo.get(e);if(null!=r&&r[n])return r[n];const i=await No(dt(dt({},t),{},{alg:n}));return o&&Object.freeze(e),r?r[n]=i:zo.set(e,{[n]:i}),i};async function Mo(e,t){if(e instanceof Uint8Array)return e;if(Po(e))return e;if(Ro(e)){if("secret"===e.type)return e.export();if("toCryptoKey"in e&&"function"==typeof e.toCryptoKey)try{return ((e,t)=>{zo||(zo=new WeakMap);let n=zo.get(e);if(null!=n&&n[t])return n[t];const o="public"===e.type,r=!!o;let i;if("x25519"===e.asymmetricKeyType){switch(t){case "ECDH-ES":case "ECDH-ES+A128KW":case "ECDH-ES+A192KW":case "ECDH-ES+A256KW":break;default:throw new TypeError("given KeyObject instance cannot be used for this algorithm")}i=e.toCryptoKey(e.asymmetricKeyType,r,o?[]:["deriveBits"]);}if("ed25519"===e.asymmetricKeyType){if("EdDSA"!==t&&"Ed25519"!==t)throw new TypeError("given KeyObject instance cannot be used for this algorithm");i=e.toCryptoKey(e.asymmetricKeyType,r,[o?"verify":"sign"]);}switch(e.asymmetricKeyType){case "ml-dsa-44":case "ml-dsa-65":case "ml-dsa-87":if(t!==e.asymmetricKeyType.toUpperCase())throw new TypeError("given KeyObject instance cannot be used for this algorithm");i=e.toCryptoKey(e.asymmetricKeyType,r,[o?"verify":"sign"]);}if("rsa"===e.asymmetricKeyType){let n;switch(t){case "RSA-OAEP":n="SHA-1";break;case "RS256":case "PS256":case "RSA-OAEP-256":n="SHA-256";break;case "RS384":case "PS384":case "RSA-OAEP-384":n="SHA-384";break;case "RS512":case "PS512":case "RSA-OAEP-512":n="SHA-512";break;default:throw new TypeError("given KeyObject instance cannot be used for this algorithm")}if(t.startsWith("RSA-OAEP"))return e.toCryptoKey({name:"RSA-OAEP",hash:n},r,o?["encrypt"]:["decrypt"]);i=e.toCryptoKey({name:t.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:n},r,[o?"verify":"sign"]);}if("ec"===e.asymmetricKeyType){var a;const n=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(null===(a=e.asymmetricKeyDetails)||void 0===a?void 0:a.namedCurve);if(!n)throw new TypeError("given KeyObject instance cannot be used for this algorithm");"ES256"===t&&"P-256"===n&&(i=e.toCryptoKey({name:"ECDSA",namedCurve:n},r,[o?"verify":"sign"])),"ES384"===t&&"P-384"===n&&(i=e.toCryptoKey({name:"ECDSA",namedCurve:n},r,[o?"verify":"sign"])),"ES512"===t&&"P-521"===n&&(i=e.toCryptoKey({name:"ECDSA",namedCurve:n},r,[o?"verify":"sign"])),t.startsWith("ECDH-ES")&&(i=e.toCryptoKey({name:"ECDH",namedCurve:n},r,o?[]:["deriveBits"]));}if(!i)throw new TypeError("given KeyObject instance cannot be used for this algorithm");return n?n[t]=i:zo.set(e,{[t]:i}),i})(e,t)}catch(e){if(e instanceof TypeError)throw e}let n=e.export({format:"jwk"});return Ho(e,n,t)}if(Wo(e))return e.k?so(e.k):Ho(e,e,t,true);throw new Error("unreachable")}const Jo=e=>null==e?void 0:e[Symbol.toStringTag],Vo=(e,t,n)=>{if(void 0!==t.use){let e;switch(n){case "sign":case "verify":e="sig";break;case "encrypt":case "decrypt":e="enc";}if(t.use!==e)throw new TypeError('Invalid key for this operation, its "use" must be "'.concat(e,'" when present'))}if(void 0!==t.alg&&t.alg!==e)throw new TypeError('Invalid key for this operation, its "alg" must be "'.concat(e,'" when present'));if(Array.isArray(t.key_ops)){var o,r;let i;switch(true){case "verify"===n:case "dir"===e:case e.includes("CBC-HS"):i=n;break;case e.startsWith("PBES2"):i="deriveBits";break;case /^A\d{3}(?:GCM)?(?:KW)?$/.test(e):i=!e.includes("GCM")&&e.endsWith("KW")?"unwrapKey":n;break;case "encrypt"===n:i="wrapKey";break;case "decrypt"===n:i=e.startsWith("RSA")?"unwrapKey":"deriveBits";}if(i&&false===(null===(o=t.key_ops)||void 0===o||null===(r=o.includes)||void 0===r?void 0:r.call(o,i)))throw new TypeError('Invalid key for this operation, its "key_ops" must include "'.concat(i,'" when present'))}return true};function Fo(e,t,n){switch(e.substring(0,2)){case "A1":case "A2":case "di":case "HS":case "PB":((e,t,n)=>{if(!(t instanceof Uint8Array)){if(Wo(t)){if((e=>"oct"===e.kty&&"string"==typeof e.k)(t)&&Vo(e,t,n))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!Io(t))throw new TypeError(To(e,t,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if("secret"!==t.type)throw new TypeError("".concat(Jo(t),' instances for symmetric algorithms must be of type "secret"'))}})(e,t,n);break;default:((e,t,n)=>{if(Wo(t))switch(n){case "decrypt":case "sign":if((e=>"oct"!==e.kty&&("AKP"===e.kty&&"string"==typeof e.priv||"string"==typeof e.d))(t)&&Vo(e,t,n))return;throw new TypeError("JSON Web Key for this operation must be a private JWK");case "encrypt":case "verify":if((e=>"oct"!==e.kty&&void 0===e.d&&void 0===e.priv)(t)&&Vo(e,t,n))return;throw new TypeError("JSON Web Key for this operation must be a public JWK")}if(!Io(t))throw new TypeError(To(e,t,"CryptoKey","KeyObject","JSON Web Key"));if("secret"===t.type)throw new TypeError("".concat(Jo(t),' instances for asymmetric algorithms must not be of type "secret"'));if("public"===t.type)switch(n){case "sign":throw new TypeError("".concat(Jo(t),' instances for asymmetric algorithm signing must be of type "private"'));case "decrypt":throw new TypeError("".concat(Jo(t),' instances for asymmetric algorithm decryption must be of type "private"'))}if("private"===t.type)switch(n){case "verify":throw new TypeError("".concat(Jo(t),' instances for asymmetric algorithm verifying must be of type "public"'));case "encrypt":throw new TypeError("".concat(Jo(t),' instances for asymmetric algorithm encryption must be of type "public"'))}})(e,t,n);}}var Go,Zo;let qo,Bo;if("undefined"==typeof navigator||null===(Go=navigator.userAgent)||void 0===Go||null===(Zo=Go.startsWith)||void 0===Zo||!Zo.call(Go,"Mozilla/5.0 ")){const e="v6.8.1";Bo="".concat("openid-client","/").concat(e),qo={"user-agent":Bo};}const Xo=e=>Yo.get(e);let Yo,Qo;function $o(e){return void 0!==e?Yt(e):(Qo||(Qo=new WeakMap),(e,t,n,o)=>{let r;return (r=Qo.get(t))||(!function(e,t){if("string"!=typeof e)throw or("".concat(t," must be a string"),nr);if(0===e.length)throw or("".concat(t," must not be empty"),tr)}(t.client_secret,'"metadata.client_secret"'),r=Yt(t.client_secret),Qo.set(t,r)),r(e,t,n,o)})}const er=St,tr="ERR_INVALID_ARG_VALUE",nr="ERR_INVALID_ARG_TYPE";function or(e,t,n){const o=new TypeError(e,{cause:n});return Object.assign(o,{code:t}),o}function rr(e){return async function(e){return Mt(e,"codeVerifier"),xt(await crypto.subtle.digest("SHA-256",Rt(e)))}(e)}function ir(){return Vt()}class ar extends Error{constructor(e,t){var n;super(e,t),ut(this,"code",void 0),this.name=this.constructor.name,this.code=null==t?void 0:t.code,null===(n=Error.captureStackTrace)||void 0===n||n.call(Error,this,this.constructor);}}function sr(e,t,n){return new ar(e,{cause:t,code:n})}function cr(e){if(e instanceof TypeError||e instanceof ar||e instanceof on||e instanceof rn||e instanceof an)throw e;if(e instanceof jt)switch(e.code){case Nn:throw sr("only requests to HTTPS are allowed",e,e.code);case Wn:throw sr("only requests to HTTP or HTTPS are allowed",e,e.code);case Un:throw sr("unexpected HTTP response status code",e.cause,e.code);case Ln:throw sr("unexpected response content-type",e.cause,e.code);case Dn:throw sr("parsing error occured",e,e.code);case Kn:throw sr("invalid response encountered",e,e.code);case Hn:throw sr("unexpected JWT claim value encountered",e,e.code);case Mn:throw sr("unexpected JSON attribute value encountered",e,e.code);case zn:throw sr("JWT timestamp claim value failed validation",e,e.code);default:throw sr(e.message,e,e.code)}if(e instanceof Ct)throw sr("unsupported operation",e,e.code);if(e instanceof DOMException)switch(e.name){case "OperationError":throw sr("runtime operation error",e,Cn);case "NotSupportedError":throw sr("runtime unsupported operation",e,Cn);case "TimeoutError":throw sr("operation timed out",e,"OAUTH_TIMEOUT");case "AbortError":throw sr("operation aborted",e,"OAUTH_ABORT")}throw new ar("something went wrong",{cause:e})}async function ur(e,t,n,o,r){const i=await async function(e,t){var n,o;if(!(e instanceof URL))throw or('"server" must be an instance of URL',nr);const r=!e.href.includes("/.well-known/"),i=null!==(n=null==t?void 0:t.timeout)&&void 0!==n?n:30,a=AbortSignal.timeout(1e3*i),s=await(r?zt(e,{algorithm:null==t?void 0:t.algorithm,[St]:null==t?void 0:t[er],[bt]:null==t||null===(o=t.execute)||void 0===o?void 0:o.includes(wr),signal:a,headers:new Headers(qo)}):((null==t?void 0:t[er])||fetch)((en(e,null==t||null===(c=t.execute)||void 0===c||!c.includes(wr)),e.href),{headers:Object.fromEntries(new Headers(dt({accept:"application/json"},qo)).entries()),body:void 0,method:"GET",redirect:"manual",signal:a})).then((e=>async function(e,t){const n=e;if(!(n instanceof URL)&&n!==to)throw vt('"expectedIssuerIdentifier" must be an instance of URL',"ERR_INVALID_ARG_TYPE");if(!gt(t,Response))throw vt('"response" must be an instance of Response',"ERR_INVALID_ARG_TYPE");if(200!==t.status)throw Dt('"response" is not a conform Authorization Server Metadata response (unexpected HTTP status code)',Un,t);Fn(t);const o=await eo(t);if(Mt(o.issuer,'"response" body "issuer" property',Kn,{body:o}),n!==to&&new URL(o.issuer).href!==n.href)throw Dt('"response" body "issuer" property does not match the expected value',Mn,{expected:n.href,body:o,attribute:"issuer"});return o}(to,e))).catch(cr);var c;r&&new URL(s.issuer).href!==e.href&&(function(e,t,n){return !("https://login.microsoftonline.com"!==e.origin||null!=n&&n.algorithm&&"oidc"!==n.algorithm||(t[lr]=true,0))}(e,s,t)||function(e,t){return !(!e.hostname.endsWith(".b2clogin.com")||null!=t&&t.algorithm&&"oidc"!==t.algorithm)}(e,t)||(()=>{throw new ar("discovered metadata issuer does not match the expected issuer",{code:Mn,cause:{expected:e.href,body:s,attribute:"issuer"}})})());return s}(e,r),a=new dr(i,t,n,o);let s=Xo(a);if(null!=r&&r[er]&&(s.fetch=r[er]),null!=r&&r.timeout&&(s.timeout=r.timeout),null!=r&&r.execute)for(const e of r.execute)e(a);return a}new TextDecoder;const lr=Symbol();class dr{constructor(e,t,n,o){var r,i,a,s,c;if("string"!=typeof t||!t.length)throw or('"clientId" must be a non-empty string',nr);if("string"==typeof n&&(n={client_secret:n}),void 0!==(null===(r=n)||void 0===r?void 0:r.client_id)&&t!==n.client_id)throw or('"clientId" and "metadata.client_id" must be the same',tr);const u=dt(dt({},structuredClone(n)),{},{client_id:t});let l;u[_t]=null!==(i=null===(a=n)||void 0===a?void 0:a[_t])&&void 0!==i?i:0,u[kt]=null!==(s=null===(c=n)||void 0===c?void 0:c[kt])&&void 0!==s?s:30,l=o||("string"==typeof u.client_secret&&u.client_secret.length?$o(u.client_secret):(e,t,n,o)=>{n.set("client_id",t.client_id);});let d=Object.freeze(u);const h=structuredClone(e);lr in e&&(h[no]=t=>{let{claims:{tid:n}}=t;return e.issuer.replace("{tenantid}",n)});let p=Object.freeze(h);Yo||(Yo=new WeakMap),Yo.set(this,{__proto__:null,as:p,c:d,auth:l,tlsOnly:true,jwksCache:{}});}serverMetadata(){const e=structuredClone(Xo(this).as);return function(e){Object.defineProperties(e,function(e){return {supportsPKCE:{__proto__:null,value(){var t;let n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"S256";return true===(null===(t=e.code_challenge_methods_supported)||void 0===t?void 0:t.includes(n))}}}}(e));}(e),e}clientMetadata(){return structuredClone(Xo(this).c)}get timeout(){return Xo(this).timeout}set timeout(e){Xo(this).timeout=e;}get[er](){return Xo(this).fetch}set[er](e){Xo(this).fetch=e;}}function hr(e){Object.defineProperties(e,function(e){let t;if(void 0!==e.expires_in){const n=new Date;n.setSeconds(n.getSeconds()+e.expires_in),t=n.getTime();}return {expiresIn:{__proto__:null,value(){if(t){const e=Date.now();return t>e?Math.floor((t-e)/1e3):0}}},claims:{__proto__:null,value(){try{return vn(this)}catch(e){return}}}}}(e));}async function pr(e,t,n){var o;let r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];const i=null===(o=e.headers.get("retry-after"))||void 0===o?void 0:o.trim();if(void 0===i)return;let a;if(/^\d+$/.test(i))a=parseInt(i,10);else {const e=new Date(i);if(Number.isFinite(e.getTime())){const t=new Date,n=e.getTime()-t.getTime();n>0&&(a=Math.ceil(n/1e3));}}if(r&&!Number.isFinite(a))throw new jt("invalid Retry-After header value",{cause:e});a>t&&await fr(a-t,n);}function fr(e,t){return new Promise(((n,o)=>{const r=e=>{try{t.throwIfAborted();}catch(e){return void o(e)}if(e<=0)return void n();const i=Math.min(e,5);setTimeout((()=>r(e-i)),1e3*i);};r(e);}))}async function mr(e,t){Sr(e);const{as:n,c:o,auth:r,fetch:i,tlsOnly:a,timeout:s}=Xo(e);return async function(e,t,n,o,r){Bt(e),Xt(t);const i=nn(e,"backchannel_authentication_endpoint",t.use_mtls_endpoint_aliases,true!==(null==r?void 0:r[bt])),a=new URLSearchParams(o);a.set("client_id",t.client_id);const s=Ut(null==r?void 0:r.headers);return s.set("accept","application/json"),mn(e,t,n,i,a,s,r)}(n,o,r,t,{[St]:i,[bt]:!a,headers:new Headers(qo),signal:Er(s)}).then((e=>async function(e,t,n){if(Bt(e),Xt(t),!gt(n,Response))throw vt('"response" must be an instance of Response',"ERR_INVALID_ARG_TYPE");await hn(n,200,"Backchannel Authentication Endpoint"),Fn(n);const o=await eo(n);Mt(o.auth_req_id,'"response" body "auth_req_id" property',Kn,{body:o});let r="number"!=typeof o.expires_in?parseFloat(o.expires_in):o.expires_in;return Ht(r,true,'"response" body "expires_in" property',Kn,{body:o}),o.expires_in=r,void 0!==o.interval&&Ht(o.interval,false,'"response" body "interval" property',Kn,{body:o}),o}(n,o,e))).catch(cr)}async function yr(e,t,n,o){var r,i;Sr(e),n=new URLSearchParams(n);let a=null!==(r=t.interval)&&void 0!==r?r:5;const s=null!==(i=null==o?void 0:o.signal)&&void 0!==i?i:AbortSignal.timeout(1e3*t.expires_in);try{await fr(a,s);}catch(e){cr(e);}const{as:c,c:u,auth:l,fetch:d,tlsOnly:h,nonRepudiation:p,timeout:f,decrypt:m}=Xo(e),y=(r,i)=>yr(e,dt(dt({},t),{},{interval:r}),n,dt(dt({},o),{},{signal:s,flag:i})),w=await async function(e,t,n,o,r){Bt(e),Xt(t),Mt(o,'"authReqId"');const i=new URLSearchParams(null==r?void 0:r.additionalParameters);return i.set("auth_req_id",o),yn(e,t,n,"urn:openid:params:grant-type:ciba",i,r)}(c,u,l,t.auth_req_id,{[St]:d,[bt]:!h,additionalParameters:n,DPoP:null==o?void 0:o.DPoP,headers:new Headers(qo),signal:s.aborted?s:Er(f)}).catch(cr);var g;if(503===w.status&&w.headers.has("retry-after"))return await pr(w,a,s,true),await(null===(g=w.body)||void 0===g?void 0:g.cancel()),y(a);const v=async function(e,t,n,o){return bn(e,t,n,void 0,null==o?void 0:o[At],null==o?void 0:o.recognizedTokenTypes)}(c,u,w,{[At]:m});let b;try{b=await v;}catch(e){if(Ar(e,o))return y(a,Tr);if(e instanceof on)switch(e.error){case "slow_down":a+=5;case "authorization_pending":return await pr(e.response,a,s),y(a)}cr(e);}return b.id_token&&await(null==p?void 0:p(w)),hr(b),b}function wr(e){Xo(e).tlsOnly=false;}async function gr(e,t,n,o,r){if(Sr(e),!((null==r?void 0:r.flag)===Tr||t instanceof URL||function(e,t){try{return Object.getPrototypeOf(e)[Symbol.toStringTag]===t}catch(e){return false}}(t,"Request")))throw or('"currentUrl" must be an instance of URL, or Request',nr);let i,a;const{as:s,c:c,auth:u,fetch:l,tlsOnly:d,jarm:h,hybrid:p,nonRepudiation:f,timeout:m,decrypt:y,implicit:w}=Xo(e);if((null==r?void 0:r.flag)===Tr)i=r.authResponse,a=r.redirectUri;else {if(!(t instanceof URL)){const e=t;switch(t=new URL(t.url),e.method){case "GET":break;case "POST":const n=new URLSearchParams(await qn(e));if(p)t.hash=n.toString();else for(const[e,o]of n.entries())t.searchParams.append(e,o);break;default:throw or("unexpected Request HTTP method",tr)}}switch(a=function(e){return (e=new URL(e)).search="",e.hash="",e.href}(t),true){case !!h:i=await h(t,null==n?void 0:n.expectedState);break;case !!p:i=await p(t,null==n?void 0:n.expectedNonce,null==n?void 0:n.expectedState,null==n?void 0:n.maxAge);break;case !!w:throw new TypeError("authorizationCodeGrant() cannot be used by response_type=id_token clients");default:try{i=$n(s,c,t.searchParams,null==n?void 0:n.expectedState);}catch(e){cr(e);}}}const g=await async function(e,t,n,o,r,i,a){if(Bt(e),Xt(t),!Sn.has(o))throw vt('"callbackParameters" must be an instance of URLSearchParams obtained from "validateAuthResponse()", or "validateJwtAuthResponse()',"ERR_INVALID_ARG_VALUE");Mt(r,'"redirectUri"');const s=Xn(o,"code");if(!s)throw Dt('no authorization code in "callbackParameters"',Kn);const c=new URLSearchParams(null==a?void 0:a.additionalParameters);return c.set("redirect_uri",r),c.set("code",s),i!==En&&(Mt(i,'"codeVerifier"'),c.set("code_verifier",i)),yn(e,t,n,"authorization_code",c,a)}(s,c,u,i,a,(null==n?void 0:n.pkceCodeVerifier)||En,{additionalParameters:o,[St]:l,[bt]:!d,DPoP:null==r?void 0:r.DPoP,headers:new Headers(qo),signal:Er(m)}).catch(cr);"string"!=typeof(null==n?void 0:n.expectedNonce)&&"number"!=typeof(null==n?void 0:n.maxAge)||(n.idTokenExpected=true);const v=In(s,c,g,{expectedNonce:null==n?void 0:n.expectedNonce,maxAge:null==n?void 0:n.maxAge,requireIdToken:null==n?void 0:n.idTokenExpected,[At]:y});let b;try{b=await v;}catch(t){if(Ar(t,r))return gr(e,void 0,n,o,dt(dt({},r),{},{flag:Tr,authResponse:i,redirectUri:a}));cr(t);}return b.id_token&&await(null==f?void 0:f(g)),hr(b),b}async function vr(e,t,n,o){Sr(e),n=new URLSearchParams(n);const{as:r,c:i,auth:a,fetch:s,tlsOnly:c,nonRepudiation:u,timeout:l,decrypt:d}=Xo(e),h=await async function(e,t,n,o,r){Bt(e),Xt(t),Mt(o,'"refreshToken"');const i=new URLSearchParams(null==r?void 0:r.additionalParameters);return i.set("refresh_token",o),yn(e,t,n,"refresh_token",i,r)}(r,i,a,t,{[St]:s,[bt]:!c,additionalParameters:n,DPoP:null==o?void 0:o.DPoP,headers:new Headers(qo),signal:Er(l)}).catch(cr),p=async function(e,t,n,o){return bn(e,t,n,void 0,null==o?void 0:o[At],null==o?void 0:o.recognizedTokenTypes)}(r,i,h,{[At]:d});let f;try{f=await p;}catch(r){if(Ar(r,o))return vr(e,t,n,dt(dt({},o),{},{flag:Tr}));cr(r);}return f.id_token&&await(null==u?void 0:u(h)),hr(f),f}async function br(e,t,n){Sr(e),t=new URLSearchParams(t);const{as:o,c:r,auth:i,fetch:a,tlsOnly:s,timeout:c}=Xo(e),u=await async function(e,t,n,o,r){return Bt(e),Xt(t),yn(e,t,n,"client_credentials",new URLSearchParams(o),r)}(o,r,i,t,{[St]:a,[bt]:!s,DPoP:null==n?void 0:n.DPoP,headers:new Headers(qo),signal:Er(c)}).catch(cr),l=async function(e,t,n,o){return bn(e,t,n,void 0,void 0,void 0)}(o,r,u);let d;try{d=await l;}catch(o){if(Ar(o,n))return br(e,t,dt(dt({},n),{},{flag:Tr}));cr(o);}return hr(d),d}function _r(e,t){Sr(e);const{as:n,c:o,tlsOnly:r,hybrid:i,jarm:a,implicit:s}=Xo(e),c=nn(n,"authorization_endpoint",false,r);if((t=new URLSearchParams(t)).has("client_id")||t.set("client_id",o.client_id),!t.has("request_uri")&&!t.has("request")){if(t.has("response_type")||t.set("response_type",i?"code id_token":s?"id_token":"code"),s&&!t.has("nonce"))throw or("response_type=id_token clients must provide a nonce parameter in their authorization request parameters",tr);a&&t.set("response_mode","jwt");}for(const[e,n]of t.entries())c.searchParams.append(e,n);return c}async function kr(e,t,n){Sr(e);const o=_r(e,t),{as:r,c:i,auth:a,fetch:s,tlsOnly:c,timeout:u}=Xo(e),l=await async function(e,t,n,o,r){var i;Bt(e),Xt(t);const a=nn(e,"pushed_authorization_request_endpoint",t.use_mtls_endpoint_aliases,true!==(null==r?void 0:r[bt])),s=new URLSearchParams(o);s.set("client_id",t.client_id);const c=Ut(null==r?void 0:r.headers);c.set("accept","application/json"),void 0!==(null==r?void 0:r.DPoP)&&(pn(r.DPoP),await r.DPoP.addProof(a,c,"POST"));const u=await mn(e,t,n,a,s,c,r);return null==r||null===(i=r.DPoP)||void 0===i||i.cacheNonce(u,a),u}(r,i,a,o.searchParams,{[St]:s,[bt]:!c,DPoP:null==n?void 0:n.DPoP,headers:new Headers(qo),signal:Er(u)}).catch(cr),d=async function(e,t,n){if(Bt(e),Xt(t),!gt(n,Response))throw vt('"response" must be an instance of Response',"ERR_INVALID_ARG_TYPE");await hn(n,201,"Pushed Authorization Request Endpoint"),Fn(n);const o=await eo(n);Mt(o.request_uri,'"response" body "request_uri" property',Kn,{body:o});let r="number"!=typeof o.expires_in?parseFloat(o.expires_in):o.expires_in;return Ht(r,true,'"response" body "expires_in" property',Kn,{body:o}),o.expires_in=r,o}(r,i,l);let h;try{h=await d;}catch(o){if(Ar(o,n))return kr(e,t,dt(dt({},n),{},{flag:Tr}));cr(o);}return _r(e,{request_uri:h.request_uri})}function Sr(e){if(!(e instanceof dr))throw or('"config" must be an instance of Configuration',nr);if(Object.getPrototypeOf(e)!==dr.prototype)throw or("subclassing Configuration is not allowed",tr)}function Er(e){return e?AbortSignal.timeout(1e3*e):void 0}function Ar(e,t){return !(null==t||!t.DPoP||t.flag===Tr)&&function(e){if(e instanceof an){const{0:t,length:n}=e.cause;return 1===n&&"dpop"===t.scheme&&"use_dpop_nonce"===t.parameters.error}return e instanceof on&&"use_dpop_nonce"===e.error}(e)}Object.freeze(dr.prototype);const Tr=Symbol();async function Pr(e,t,n,o){Sr(e);const{as:r,c:i,auth:a,fetch:s,tlsOnly:c,timeout:u,decrypt:l}=Xo(e),d=await async function(e,t,n,o,r,i){return Bt(e),Xt(t),Mt(o,'"grantType"'),yn(e,t,n,o,new URLSearchParams(r),i)}(r,i,a,t,new URLSearchParams(n),{[St]:s,[bt]:!c,DPoP:void 0,headers:new Headers(qo),signal:Er(u)}).then((e=>{let n;return "urn:ietf:params:oauth:grant-type:token-exchange"===t&&(n={n_a:()=>{}}),async function(e,t,n,o){return bn(e,t,n,void 0,null==o?void 0:o[At],null==o?void 0:o.recognizedTokenTypes)}(r,i,e,{[At]:l,recognizedTokenTypes:n})})).catch(cr);return hr(d),d}async function Rr(e,t,n){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),o=1;o<t;o++)n[o-1]=arguments[o];return Ao("Key must be ",e,...n)}(t,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",t,{hash:"SHA-".concat(e.slice(-3)),name:"HMAC"},false,[n])}return Eo(t,e,n),t}async function Ir(e,t,n,o){const r=await Rr(e,t,"verify");!function(e,t){if(e.startsWith("RS")||e.startsWith("PS")){const{modulusLength:n}=t.algorithm;if("number"!=typeof n||n<2048)throw new TypeError("".concat(e," requires key modulusLength to be 2048 bits or larger"))}}(e,r);const i=function(e,t){const n="SHA-".concat(e.slice(-3));switch(e){case "HS256":case "HS384":case "HS512":return {hash:n,name:"HMAC"};case "PS256":case "PS384":case "PS512":return {hash:n,name:"RSA-PSS",saltLength:parseInt(e.slice(-3),10)>>3};case "RS256":case "RS384":case "RS512":return {hash:n,name:"RSASSA-PKCS1-v1_5"};case "ES256":case "ES384":case "ES512":return {hash:n,name:"ECDSA",namedCurve:t.namedCurve};case "Ed25519":case "EdDSA":return {name:"Ed25519"};case "ML-DSA-44":case "ML-DSA-65":case "ML-DSA-87":return {name:e};default:throw new po("alg ".concat(e," is not supported either by JOSE or your javascript runtime"))}}(e,r.algorithm);try{return await crypto.subtle.verify(i,r,n,o)}catch(e){return false}}async function Or(e,t,n){if(!Oo(e))throw new fo("Flattened JWS must be an object");if(void 0===e.protected&&void 0===e.header)throw new fo('Flattened JWS must have either of the "protected" or "header" members');if(void 0!==e.protected&&"string"!=typeof e.protected)throw new fo("JWS Protected Header incorrect type");if(void 0===e.payload)throw new fo("JWS Payload missing");if("string"!=typeof e.signature)throw new fo("JWS Signature missing or incorrect type");if(void 0!==e.header&&!Oo(e.header))throw new fo("JWS Unprotected Header incorrect type");let o={};if(e.protected)try{const t=so(e.protected);o=JSON.parse(ro.decode(t));}catch(e){throw new fo("JWS Protected Header is invalid")}if(!function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];const o=t.filter(Boolean);if(0===o.length||1===o.length)return true;let r;for(const e of o){const t=Object.keys(e);if(r&&0!==r.size)for(const e of t){if(r.has(e))return false;r.add(e);}else r=new Set(t);}return true}(o,e.header))throw new fo("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const r=dt(dt({},o),e.header),i=function(e,t,n,o,r){if(void 0!==r.crit&&void 0===(null==o?void 0:o.crit))throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!o||void 0===o.crit)return new Set;if(!Array.isArray(o.crit)||0===o.crit.length||o.crit.some((e=>"string"!=typeof e||0===e.length)))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i;i=void 0!==n?new Map([...Object.entries(n),...t.entries()]):t;for(const t of o.crit){if(!i.has(t))throw new po('Extension Header Parameter "'.concat(t,'" is not recognized'));if(void 0===r[t])throw new e('Extension Header Parameter "'.concat(t,'" is missing'));if(i.get(t)&&void 0===o[t])throw new e('Extension Header Parameter "'.concat(t,'" MUST be integrity protected'))}return new Set(o.crit)}(fo,new Map([["b64",true]]),null==n?void 0:n.crit,o,r);let a=true;if(i.has("b64")&&(a=o.b64,"boolean"!=typeof a))throw new fo('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:s}=r;if("string"!=typeof s||!s)throw new fo('JWS "alg" (Algorithm) Header Parameter missing or invalid');const c=n&&function(e,t){if(void 0!==t&&(!Array.isArray(t)||t.some((e=>"string"!=typeof e))))throw new TypeError('"'.concat(e,'" option must be an array of strings'));if(t)return new Set(t)}("algorithms",n.algorithms);if(c&&!c.has(s))throw new ho('"alg" (Algorithm) Header Parameter value not allowed');if(a){if("string"!=typeof e.payload)throw new fo("JWS Payload must be a string")}else if("string"!=typeof e.payload&&!(e.payload instanceof Uint8Array))throw new fo("JWS Payload must be a string or an Uint8Array instance");let u=false;"function"==typeof t&&(t=await t(o,e),u=true),Fo(s,t,"verify");const l=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];const o=t.reduce(((e,t)=>{let{length:n}=t;return e+n}),0),r=new Uint8Array(o);let i=0;for(const e of t)r.set(e,i),i+=e.length;return r}(void 0!==e.protected?io(e.protected):new Uint8Array,io("."),"string"==typeof e.payload?a?io(e.payload):oo.encode(e.payload):e.payload);let d;try{d=so(e.signature);}catch(e){throw new fo("Failed to base64url decode the signature")}const h=await Mo(t,s);if(!await Ir(s,h,d,l))throw new bo;let p;if(a)try{p=so(e.payload);}catch(e){throw new fo("Failed to base64url decode the payload")}else p="string"==typeof e.payload?oo.encode(e.payload):e.payload;const f={payload:p};return void 0!==e.protected&&(f.protectedHeader=o),void 0!==e.header&&(f.unprotectedHeader=e.header),u?dt(dt({},f),{},{key:h}):f}const xr=e=>Math.floor(e.getTime()/1e3),Cr=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function jr(e){const t=Cr.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");const n=parseFloat(t[2]);let o;switch(t[3].toLowerCase()){case "sec":case "secs":case "second":case "seconds":case "s":o=Math.round(n);break;case "minute":case "minutes":case "min":case "mins":case "m":o=Math.round(60*n);break;case "hour":case "hours":case "hr":case "hrs":case "h":o=Math.round(3600*n);break;case "day":case "days":case "d":o=Math.round(86400*n);break;case "week":case "weeks":case "w":o=Math.round(604800*n);break;default:o=Math.round(31557600*n);}return "-"===t[1]||"ago"===t[4]?-o:o}const Dr=e=>e.includes("/")?e.toLowerCase():"application/".concat(e.toLowerCase()),Kr=(e,t)=>"string"==typeof e?t.includes(e):!!Array.isArray(e)&&t.some(Set.prototype.has.bind(new Set(e)));async function Lr(e,t,n){var o;const r=await async function(e,t,n){if(e instanceof Uint8Array&&(e=ro.decode(e)),"string"!=typeof e)throw new fo("Compact JWS must be a string or Uint8Array");const{0:o,1:r,2:i,length:a}=e.split(".");if(3!==a)throw new fo("Invalid Compact JWS");const s=await Or({payload:r,protected:o,signature:i},t,n),c={payload:s.payload,protectedHeader:s.protectedHeader};return "function"==typeof t?dt(dt({},c),{},{key:s.key}):c}(e,t,n);if(null!==(o=r.protectedHeader.crit)&&void 0!==o&&o.includes("b64")&&false===r.protectedHeader.b64)throw new mo("JWTs MUST NOT use unencoded payload");const i=function(e,t){let n,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};try{n=JSON.parse(ro.decode(t));}catch(e){}if(!Oo(n))throw new mo("JWT Claims Set must be a top-level JSON object");const{typ:r}=o;if(r&&("string"!=typeof e.typ||Dr(e.typ)!==Dr(r)))throw new uo('unexpected "typ" JWT header value',n,"typ","check_failed");const{requiredClaims:i=[],issuer:a,subject:s,audience:c,maxTokenAge:u}=o,l=[...i];void 0!==u&&l.push("iat"),void 0!==c&&l.push("aud"),void 0!==s&&l.push("sub"),void 0!==a&&l.push("iss");for(const e of new Set(l.reverse()))if(!(e in n))throw new uo('missing required "'.concat(e,'" claim'),n,e,"missing");if(a&&!(Array.isArray(a)?a:[a]).includes(n.iss))throw new uo('unexpected "iss" claim value',n,"iss","check_failed");if(s&&n.sub!==s)throw new uo('unexpected "sub" claim value',n,"sub","check_failed");if(c&&!Kr(n.aud,"string"==typeof c?[c]:c))throw new uo('unexpected "aud" claim value',n,"aud","check_failed");let d;switch(typeof o.clockTolerance){case "string":d=jr(o.clockTolerance);break;case "number":d=o.clockTolerance;break;case "undefined":d=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:h}=o,p=xr(h||new Date);if((void 0!==n.iat||u)&&"number"!=typeof n.iat)throw new uo('"iat" claim must be a number',n,"iat","invalid");if(void 0!==n.nbf){if("number"!=typeof n.nbf)throw new uo('"nbf" claim must be a number',n,"nbf","invalid");if(n.nbf>p+d)throw new uo('"nbf" claim timestamp check failed',n,"nbf","check_failed")}if(void 0!==n.exp){if("number"!=typeof n.exp)throw new uo('"exp" claim must be a number',n,"exp","invalid");if(n.exp<=p-d)throw new lo('"exp" claim timestamp check failed',n,"exp","check_failed")}if(u){const e=p-n.iat;if(e-d>("number"==typeof u?u:jr(u)))throw new lo('"iat" claim timestamp check failed (too far in the past)',n,"iat","check_failed");if(e<0-d)throw new uo('"iat" claim timestamp check failed (it should be in the past)',n,"iat","check_failed")}return n}(r.protectedHeader,r.payload,n),a={payload:i,protectedHeader:r.protectedHeader};return "function"==typeof t?dt(dt({},a),{},{key:r.key}):a}function Ur(e){return Oo(e)}var Nr,Wr,zr=new WeakMap,Hr=new WeakMap;class Mr{constructor(e){if(st(this,zr,void 0),st(this,Hr,new WeakMap),!function(e){return e&&"object"==typeof e&&Array.isArray(e.keys)&&e.keys.every(Ur)}(e))throw new yo("JSON Web Key Set malformed");ct(zr,this,structuredClone(e));}jwks(){return at(zr,this)}async getKey(e,t){const{alg:n,kid:o}=dt(dt({},e),null==t?void 0:t.header),r=function(e){switch("string"==typeof e&&e.slice(0,2)){case "RS":case "PS":return "RSA";case "ES":return "EC";case "Ed":return "OKP";case "ML":return "AKP";default:throw new po('Unsupported "alg" value for a JSON Web Key Set')}}(n),i=at(zr,this).keys.filter((e=>{let t=r===e.kty;if(t&&"string"==typeof o&&(t=o===e.kid),!t||"string"!=typeof e.alg&&"AKP"!==r||(t=n===e.alg),t&&"string"==typeof e.use&&(t="sig"===e.use),t&&Array.isArray(e.key_ops)&&(t=e.key_ops.includes("verify")),t)switch(n){case "ES256":t="P-256"===e.crv;break;case "ES384":t="P-384"===e.crv;break;case "ES512":t="P-521"===e.crv;break;case "Ed25519":case "EdDSA":t="Ed25519"===e.crv;}return t})),{0:a,length:s}=i;if(0===s)throw new wo;if(1!==s){const e=new go,t=at(Hr,this);throw e[Symbol.asyncIterator]=pt((function*(){for(const e of i)try{yield yield rt(Jr(t,e,n));}catch(e){}})),e}return Jr(at(Hr,this),a,n)}}async function Jr(e,t,n){const o=e.get(t)||e.set(t,{}).get(t);if(void 0===o[n]){const e=await async function(e,t,n){var o;if(!Oo(e))throw new TypeError("JWK must be an object");let r;switch(null!=t||(t=e.alg),null!=r||(r=null!==(o=void 0)&&void 0!==o?o:e.ext),e.kty){case "oct":if("string"!=typeof e.k||!e.k)throw new TypeError('missing "k" (Key Value) Parameter value');return so(e.k);case "RSA":if("oth"in e&&void 0!==e.oth)throw new po('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');return No(dt(dt({},e),{},{alg:t,ext:r}));case "AKP":if("string"!=typeof e.alg||!e.alg)throw new TypeError('missing "alg" (Algorithm) Parameter value');if(void 0!==t&&t!==e.alg)throw new TypeError("JWK alg and alg option value mismatch");return No(dt(dt({},e),{},{ext:r}));case "EC":case "OKP":return No(dt(dt({},e),{},{alg:t,ext:r}));default:throw new po('Unsupported "kty" (Key Type) Parameter value')}}(dt(dt({},t),{},{ext:true}),n);if(e instanceof Uint8Array||"public"!==e.type)throw new yo("JSON Web Key Set members must be public keys");o[n]=e;}return o[n]}function Vr(e){const t=new Mr(e),n=async(e,n)=>t.getKey(e,n);return Object.defineProperties(n,{jwks:{value:()=>structuredClone(t.jwks()),enumerable:false,configurable:false,writable:false}}),n}let Fr;if("undefined"==typeof navigator||null===(Nr=navigator.userAgent)||void 0===Nr||null===(Wr=Nr.startsWith)||void 0===Wr||!Wr.call(Nr,"Mozilla/5.0 ")){const e="v6.1.3";Fr="".concat("jose","/").concat(e);}const Gr=Symbol();const Zr=Symbol();var qr=new WeakMap,Br=new WeakMap,Xr=new WeakMap,Yr=new WeakMap,Qr=new WeakMap,$r=new WeakMap,ei=new WeakMap,ti=new WeakMap,ni=new WeakMap,oi=new WeakMap;class ri{constructor(e,t){if(st(this,qr,void 0),st(this,Br,void 0),st(this,Xr,void 0),st(this,Yr,void 0),st(this,Qr,void 0),st(this,$r,void 0),st(this,ei,void 0),st(this,ti,void 0),st(this,ni,void 0),st(this,oi,void 0),!(e instanceof URL))throw new TypeError("url must be an instance of URL");var n,o;ct(qr,this,new URL(e.href)),ct(Br,this,"number"==typeof(null==t?void 0:t.timeoutDuration)?null==t?void 0:t.timeoutDuration:5e3),ct(Xr,this,"number"==typeof(null==t?void 0:t.cooldownDuration)?null==t?void 0:t.cooldownDuration:3e4),ct(Yr,this,"number"==typeof(null==t?void 0:t.cacheMaxAge)?null==t?void 0:t.cacheMaxAge:6e5),ct(ei,this,new Headers(null==t?void 0:t.headers)),Fr&&!at(ei,this).has("User-Agent")&&at(ei,this).set("User-Agent",Fr),at(ei,this).has("accept")||(at(ei,this).set("accept","application/json"),at(ei,this).append("accept","application/jwk-set+json")),ct(ti,this,null==t?void 0:t[Gr]),void 0!==(null==t?void 0:t[Zr])&&(ct(oi,this,null==t?void 0:t[Zr]),n=null==t?void 0:t[Zr],o=at(Yr,this),"object"==typeof n&&null!==n&&"uat"in n&&"number"==typeof n.uat&&!(Date.now()-n.uat>=o)&&"jwks"in n&&Oo(n.jwks)&&Array.isArray(n.jwks.keys)&&Array.prototype.every.call(n.jwks.keys,Oo)&&(ct(Qr,this,at(oi,this).uat),ct(ni,this,Vr(at(oi,this).jwks))));}pendingFetch(){return !!at($r,this)}coolingDown(){return "number"==typeof at(Qr,this)&&Date.now()<at(Qr,this)+at(Xr,this)}fresh(){return "number"==typeof at(Qr,this)&&Date.now()<at(Qr,this)+at(Yr,this)}jwks(){var e;return null===(e=at(ni,this))||void 0===e?void 0:e.jwks()}async getKey(e,t){at(ni,this)&&this.fresh()||await this.reload();try{return await at(ni,this).call(this,e,t)}catch(n){if(n instanceof wo&&false===this.coolingDown())return await this.reload(),at(ni,this).call(this,e,t);throw n}}async reload(){at($r,this)&&("undefined"!=typeof WebSocketPair||"undefined"!=typeof navigator&&"Cloudflare-Workers"===navigator.userAgent||"undefined"!=typeof EdgeRuntime&&"vercel"===EdgeRuntime)&&ct($r,this,void 0),at($r,this)||ct($r,this,async function(e,t,n){let o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:fetch;const r=await o(e,{method:"GET",signal:n,redirect:"manual",headers:t}).catch((e=>{if("TimeoutError"===e.name)throw new vo;throw e}));if(200!==r.status)throw new co("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await r.json()}catch(e){throw new co("Failed to parse the JSON Web Key Set HTTP response as JSON")}}(at(qr,this).href,at(ei,this),AbortSignal.timeout(at(Br,this)),at(ti,this)).then((e=>{ct(ni,this,Vr(e)),at(oi,this)&&(at(oi,this).uat=Date.now(),at(oi,this).jwks=e),ct(Qr,this,Date.now()),ct($r,this,void 0);})).catch((e=>{throw ct($r,this,void 0),e}))),await at($r,this);}}const ii=["mfaToken"],ai=["mfaToken"];var si,ci,ui,li,di,hi,pi,fi,mi=class extends Error{constructor(e,t){super(t),ut(this,"code",void 0),this.name="NotSupportedError",this.code=e;}},yi=class extends Error{constructor(e,t,n){super(t),ut(this,"cause",void 0),ut(this,"code",void 0),this.code=e,this.cause=n&&{error:n.error,error_description:n.error_description,message:n.message};}},wi=class extends yi{constructor(e,t){super("token_by_code_error",e,t),this.name="TokenByCodeError";}},gi=class extends yi{constructor(e,t){super("token_by_client_credentials_error",e,t),this.name="TokenByClientCredentialsError";}},vi=class extends yi{constructor(e,t){super("token_by_refresh_token_error",e,t),this.name="TokenByRefreshTokenError";}},bi=class extends yi{constructor(e,t){super("token_for_connection_error",e,t),this.name="TokenForConnectionErrorCode";}},_i=class extends yi{constructor(e,t){super("token_exchange_error",e,t),this.name="TokenExchangeError";}},ki=class extends Error{constructor(e){super(e),ut(this,"code","verify_logout_token_error"),this.name="VerifyLogoutTokenError";}},Si=class extends yi{constructor(e){super("backchannel_authentication_error","There was an error when trying to use Client-Initiated Backchannel Authentication.",e),ut(this,"code","backchannel_authentication_error"),this.name="BackchannelAuthenticationError";}},Ei=class extends yi{constructor(e){super("build_authorization_url_error","There was an error when trying to build the authorization URL.",e),this.name="BuildAuthorizationUrlError";}},Ai=class extends yi{constructor(e){super("build_link_user_url_error","There was an error when trying to build the Link User URL.",e),this.name="BuildLinkUserUrlError";}},Ti=class extends yi{constructor(e){super("build_unlink_user_url_error","There was an error when trying to build the Unlink User URL.",e),this.name="BuildUnlinkUserUrlError";}},Pi=class extends Error{constructor(){super("The client secret or client assertion signing key must be provided."),ut(this,"code","missing_client_auth_error"),this.name="MissingClientAuthError";}};function Ri(e){return Object.entries(e).filter((e=>{let[,t]=e;return void 0!==t})).reduce(((e,t)=>dt(dt({},e),{},{[t[0]]:t[1]})),{})}var Ii=class extends Error{constructor(e,t,n){super(t),ut(this,"cause",void 0),ut(this,"code",void 0),this.code=e,this.cause=n&&{error:n.error,error_description:n.error_description,message:n.message};}},Oi=class extends Ii{constructor(e,t){super("mfa_list_authenticators_error",e,t),this.name="MfaListAuthenticatorsError";}},xi=class extends Ii{constructor(e,t){super("mfa_enrollment_error",e,t),this.name="MfaEnrollmentError";}},Ci=class extends Ii{constructor(e,t){super("mfa_delete_authenticator_error",e,t),this.name="MfaDeleteAuthenticatorError";}},ji=class extends Ii{constructor(e,t){super("mfa_challenge_error",e,t),this.name="MfaChallengeError";}};function Di(e){return {id:e.id,authenticatorType:e.authenticator_type,active:e.active,name:e.name,oobChannels:e.oob_channels,type:e.type}}var Ki=(si=new WeakMap,ci=new WeakMap,ui=new WeakMap,class{constructor(e){var t;st(this,si,void 0),st(this,ci,void 0),st(this,ui,void 0),ct(si,this,"https://".concat(e.domain)),ct(ci,this,e.clientId),ct(ui,this,null!==(t=e.customFetch)&&void 0!==t?t:function(){return fetch(...arguments)});}async listAuthenticators(e){const t="".concat(at(si,this),"/mfa/authenticators"),{mfaToken:n}=e,o=await at(ui,this).call(this,t,{method:"GET",headers:{Authorization:"Bearer ".concat(n),"Content-Type":"application/json"}});if(!o.ok){const e=await o.json();throw new Oi(e.error_description||"Failed to list authenticators",e)}return (await o.json()).map(Di)}async enrollAuthenticator(e){const t="".concat(at(si,this),"/mfa/associate"),{mfaToken:n}=e,o=ht(e,ii),r={authenticator_types:o.authenticatorTypes};"oobChannels"in o&&(r.oob_channels=o.oobChannels),"phoneNumber"in o&&o.phoneNumber&&(r.phone_number=o.phoneNumber),"email"in o&&o.email&&(r.email=o.email);const i=await at(ui,this).call(this,t,{method:"POST",headers:{Authorization:"Bearer ".concat(n),"Content-Type":"application/json"},body:JSON.stringify(r)});if(!i.ok){const e=await i.json();throw new xi(e.error_description||"Failed to enroll authenticator",e)}return function(e){if("otp"===e.authenticator_type)return {authenticatorType:"otp",secret:e.secret,barcodeUri:e.barcode_uri,recoveryCodes:e.recovery_codes,id:e.id};if("oob"===e.authenticator_type)return {authenticatorType:"oob",oobChannel:e.oob_channel,oobCode:e.oob_code,bindingMethod:e.binding_method,id:e.id};throw new Error("Unexpected authenticator type: ".concat(e.authenticator_type))}(await i.json())}async deleteAuthenticator(e){const{authenticatorId:t,mfaToken:n}=e,o="".concat(at(si,this),"/mfa/authenticators/").concat(encodeURIComponent(t)),r=await at(ui,this).call(this,o,{method:"DELETE",headers:{Authorization:"Bearer ".concat(n),"Content-Type":"application/json"}});if(!r.ok){const e=await r.json();throw new Ci(e.error_description||"Failed to delete authenticator",e)}}async challengeAuthenticator(e){const t="".concat(at(si,this),"/mfa/challenge"),{mfaToken:n}=e,o=ht(e,ai),r={mfa_token:n,client_id:at(ci,this),challenge_type:o.challengeType};o.authenticatorId&&(r.authenticator_id=o.authenticatorId);const i=await at(ui,this).call(this,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!i.ok){const e=await i.json();throw new ji(e.error_description||"Failed to challenge authenticator",e)}return function(e){const t={challengeType:e.challenge_type};return void 0!==e.oob_code&&(t.oobCode=e.oob_code),void 0!==e.binding_method&&(t.bindingMethod=e.binding_method),t}(await i.json())}}),Li=class e{constructor(e,t,n,o,r,i,a){ut(this,"accessToken",void 0),ut(this,"idToken",void 0),ut(this,"refreshToken",void 0),ut(this,"expiresAt",void 0),ut(this,"scope",void 0),ut(this,"claims",void 0),ut(this,"authorizationDetails",void 0),ut(this,"tokenType",void 0),ut(this,"issuedTokenType",void 0),this.accessToken=e,this.idToken=n,this.refreshToken=o,this.expiresAt=t,this.scope=r,this.claims=i,this.authorizationDetails=a;}static fromTokenEndpointResponse(t){const n=t.id_token?t.claims():void 0,o=new e(t.access_token,Math.floor(Date.now()/1e3)+Number(t.expires_in),t.id_token,t.refresh_token,t.scope,n,t.authorization_details);return o.tokenType=t.token_type,o.issuedTokenType=t.issued_token_type,o}},Ui="openid profile email offline_access",Ni=Object.freeze(new Set(["grant_type","client_id","client_secret","client_assertion","client_assertion_type","subject_token","subject_token_type","requested_token_type","actor_token","actor_token_type","audience","aud","resource","resources","resource_indicator","scope","connection","login_hint","organization","assertion"]));function Wi(e){if(null==e)throw new _i("subject_token is required");if("string"!=typeof e)throw new _i("subject_token must be a string");if(0===e.trim().length)throw new _i("subject_token cannot be blank or whitespace");if(e!==e.trim())throw new _i("subject_token must not include leading or trailing whitespace");if(/^bearer\s+/i.test(e))throw new _i("subject_token must not include the 'Bearer ' prefix")}function zi(e,t){if(t)for(const[n,o]of Object.entries(t))if(!Ni.has(n))if(Array.isArray(o)){if(o.length>20)throw new _i("Parameter '".concat(n,"' exceeds maximum array size of ").concat(20));o.forEach((t=>{e.append(n,t);}));}else e.append(n,o);}var Hi=(li=new WeakMap,di=new WeakMap,hi=new WeakMap,pi=new WeakMap,fi=new WeakSet,class{constructor(e){if(function(e,t){it(e,t),t.add(e);}(this,fi),st(this,li,void 0),st(this,di,void 0),st(this,hi,void 0),st(this,pi,void 0),ut(this,"mfa",void 0),ct(hi,this,e),e.useMtls&&!e.customFetch)throw new mi("mtls_without_custom_fetch_not_supported","Using mTLS without a custom fetch implementation is not supported");this.mfa=new Ki({domain:at(hi,this).domain,clientId:at(hi,this).clientId,customFetch:at(hi,this).customFetch});}async buildAuthorizationUrl(e){const{serverMetadata:t}=await ot(fi,this,Mi).call(this);if(null!=e&&e.pushedAuthorizationRequests&&!t.pushed_authorization_request_endpoint)throw new mi("par_not_supported_error","The Auth0 tenant does not have pushed authorization requests enabled. Learn how to enable it here: https://auth0.com/docs/get-started/applications/configure-par");try{return await ot(fi,this,Gi).call(this,e)}catch(e){throw new Ei(e)}}async buildLinkUserUrl(e){try{const t=await ot(fi,this,Gi).call(this,{authorizationParams:dt(dt({},e.authorizationParams),{},{requested_connection:e.connection,requested_connection_scope:e.connectionScope,scope:"openid link_account offline_access",id_token_hint:e.idToken})});return {linkUserUrl:t.authorizationUrl,codeVerifier:t.codeVerifier}}catch(e){throw new Ai(e)}}async buildUnlinkUserUrl(e){try{const t=await ot(fi,this,Gi).call(this,{authorizationParams:dt(dt({},e.authorizationParams),{},{requested_connection:e.connection,scope:"openid unlink_account",id_token_hint:e.idToken})});return {unlinkUserUrl:t.authorizationUrl,codeVerifier:t.codeVerifier}}catch(e){throw new Ti(e)}}async backchannelAuthentication(e){const{configuration:t,serverMetadata:n}=await ot(fi,this,Mi).call(this),o=Ri(dt(dt({},at(hi,this).authorizationParams),null==e?void 0:e.authorizationParams)),r=new URLSearchParams(dt(dt({scope:Ui},o),{},{client_id:at(hi,this).clientId,binding_message:e.bindingMessage,login_hint:JSON.stringify({format:"iss_sub",iss:n.issuer,sub:e.loginHint.sub})}));e.requestedExpiry&&r.append("requested_expiry",e.requestedExpiry.toString()),e.authorizationDetails&&r.append("authorization_details",JSON.stringify(e.authorizationDetails));try{const e=await mr(t,r),n=await yr(t,e);return Li.fromTokenEndpointResponse(n)}catch(e){throw new Si(e)}}async initiateBackchannelAuthentication(e){const{configuration:t,serverMetadata:n}=await ot(fi,this,Mi).call(this),o=Ri(dt(dt({},at(hi,this).authorizationParams),null==e?void 0:e.authorizationParams)),r=new URLSearchParams(dt(dt({scope:Ui},o),{},{client_id:at(hi,this).clientId,binding_message:e.bindingMessage,login_hint:JSON.stringify({format:"iss_sub",iss:n.issuer,sub:e.loginHint.sub})}));e.requestedExpiry&&r.append("requested_expiry",e.requestedExpiry.toString()),e.authorizationDetails&&r.append("authorization_details",JSON.stringify(e.authorizationDetails));try{const e=await mr(t,r);return {authReqId:e.auth_req_id,expiresIn:e.expires_in,interval:e.interval}}catch(e){throw new Si(e)}}async backchannelAuthenticationGrant(e){let{authReqId:t}=e;const{configuration:n}=await ot(fi,this,Mi).call(this),o=new URLSearchParams({auth_req_id:t});try{const e=await Pr(n,"urn:openid:params:grant-type:ciba",o);return Li.fromTokenEndpointResponse(e)}catch(e){throw new Si(e)}}async getTokenForConnection(e){var t;if(e.refreshToken&&e.accessToken)throw new bi("Either a refresh or access token should be specified, but not both.");const n=null!==(t=e.accessToken)&&void 0!==t?t:e.refreshToken;if(!n)throw new bi("Either a refresh or access token must be specified.");try{return await this.exchangeToken({connection:e.connection,subjectToken:n,subjectTokenType:e.accessToken?"urn:ietf:params:oauth:token-type:access_token":"urn:ietf:params:oauth:token-type:refresh_token",loginHint:e.loginHint})}catch(e){if(e instanceof _i)throw new bi(e.message,e.cause);throw e}}async exchangeToken(e){return "connection"in e?ot(fi,this,Ji).call(this,e):ot(fi,this,Vi).call(this,e)}async getTokenByCode(e,t){const{configuration:n}=await ot(fi,this,Mi).call(this);try{const o=await gr(n,e,{pkceCodeVerifier:t.codeVerifier});return Li.fromTokenEndpointResponse(o)}catch(e){throw new wi("There was an error while trying to request a token.",e)}}async getTokenByRefreshToken(e){const{configuration:t}=await ot(fi,this,Mi).call(this);try{const n=await vr(t,e.refreshToken);return Li.fromTokenEndpointResponse(n)}catch(e){throw new vi("The access token has expired and there was an error while trying to refresh it.",e)}}async getTokenByClientCredentials(e){const{configuration:t}=await ot(fi,this,Mi).call(this);try{const n=new URLSearchParams({audience:e.audience});e.organization&&n.append("organization",e.organization);const o=await br(t,n);return Li.fromTokenEndpointResponse(o)}catch(e){throw new gi("There was an error while trying to request a token.",e)}}async buildLogoutUrl(e){const{configuration:t,serverMetadata:n}=await ot(fi,this,Mi).call(this);if(!n.end_session_endpoint){const t=new URL("https://".concat(at(hi,this).domain,"/v2/logout"));return t.searchParams.set("returnTo",e.returnTo),t.searchParams.set("client_id",at(hi,this).clientId),t}return function(e,t){Sr(e);const{as:n,c:o,tlsOnly:r}=Xo(e),i=nn(n,"end_session_endpoint",false,r);(t=new URLSearchParams(t)).has("client_id")||t.set("client_id",o.client_id);for(const[e,n]of t.entries())i.searchParams.append(e,n);return i}(t,{post_logout_redirect_uri:e.returnTo})}async verifyLogoutToken(e){const{serverMetadata:t}=await ot(fi,this,Mi).call(this);at(pi,this)||ct(pi,this,function(e,t){const n=new ri(e,t),o=async(e,t)=>n.getKey(e,t);return Object.defineProperties(o,{coolingDown:{get:()=>n.coolingDown(),enumerable:true,configurable:false},fresh:{get:()=>n.fresh(),enumerable:true,configurable:false},reload:{value:()=>n.reload(),enumerable:true,configurable:false,writable:false},reloading:{get:()=>n.pendingFetch(),enumerable:true,configurable:false},jwks:{value:()=>n.jwks(),enumerable:true,configurable:false,writable:false}}),o}(new URL(t.jwks_uri),{[Gr]:at(hi,this).customFetch}));const{payload:n}=await Lr(e.logoutToken,at(pi,this),{issuer:t.issuer,audience:at(hi,this).clientId,algorithms:["RS256"],requiredClaims:["iat"]});if(!("sid"in n)&&!("sub"in n))throw new ki('either "sid" or "sub" (or both) claims must be present');if("sid"in n&&"string"!=typeof n.sid)throw new ki('"sid" claim must be a string');if("sub"in n&&"string"!=typeof n.sub)throw new ki('"sub" claim must be a string');if("nonce"in n)throw new ki('"nonce" claim is prohibited');if(!("events"in n))throw new ki('"events" claim is missing');if("object"!=typeof n.events||null===n.events)throw new ki('"events" claim must be an object');if(!("http://schemas.openid.net/event/backchannel-logout"in n.events))throw new ki('"http://schemas.openid.net/event/backchannel-logout" member is missing in the "events" claim');if("object"!=typeof n.events["http://schemas.openid.net/event/backchannel-logout"])throw new ki('"http://schemas.openid.net/event/backchannel-logout" member in the "events" claim must be an object');return {sid:n.sid,sub:n.sub}}});async function Mi(){if(at(li,this)&&at(di,this))return {configuration:at(li,this),serverMetadata:at(di,this)};const e=await ot(fi,this,Fi).call(this);return ct(li,this,await ur(new URL("https://".concat(at(hi,this).domain)),at(hi,this).clientId,{use_mtls_endpoint_aliases:at(hi,this).useMtls},e,{[er]:at(hi,this).customFetch})),ct(di,this,at(li,this).serverMetadata()),at(li,this)[er]=at(hi,this).customFetch||fetch,{configuration:at(li,this),serverMetadata:at(di,this)}}async function Ji(e){var t,n;const{configuration:o}=await ot(fi,this,Mi).call(this);if("audience"in e||"resource"in e)throw new _i("audience and resource parameters are not supported for Token Vault exchanges");Wi(e.subjectToken);const r=new URLSearchParams({connection:e.connection,subject_token:e.subjectToken,subject_token_type:null!==(t=e.subjectTokenType)&&void 0!==t?t:"urn:ietf:params:oauth:token-type:access_token",requested_token_type:null!==(n=e.requestedTokenType)&&void 0!==n?n:"http://auth0.com/oauth/token-type/federated-connection-access-token"});e.loginHint&&r.append("login_hint",e.loginHint),e.scope&&r.append("scope",e.scope),zi(r,e.extra);try{const e=await Pr(o,"urn:auth0:params:oauth:grant-type:token-exchange:federated-connection-access-token",r);return Li.fromTokenEndpointResponse(e)}catch(t){throw new _i("Failed to exchange token for connection '".concat(e.connection,"'."),t)}}async function Vi(e){const{configuration:t}=await ot(fi,this,Mi).call(this);Wi(e.subjectToken);const n=new URLSearchParams({subject_token_type:e.subjectTokenType,subject_token:e.subjectToken});e.audience&&n.append("audience",e.audience),e.scope&&n.append("scope",e.scope),e.requestedTokenType&&n.append("requested_token_type",e.requestedTokenType),e.organization&&n.append("organization",e.organization),zi(n,e.extra);try{const e=await Pr(t,"urn:ietf:params:oauth:grant-type:token-exchange",n);return Li.fromTokenEndpointResponse(e)}catch(t){throw new _i("Failed to exchange token of type '".concat(e.subjectTokenType,"'").concat(e.audience?" for audience '".concat(e.audience,"'"):"","."),t)}}async function Fi(){if(!at(hi,this).clientSecret&&!at(hi,this).clientAssertionSigningKey&&!at(hi,this).useMtls)throw new Pi;if(at(hi,this).useMtls)return (e,t,n,o)=>{n.set("client_id",t.client_id);};let e=at(hi,this).clientAssertionSigningKey;return !e||e instanceof CryptoKey||(e=await async function(e,t,n){if("string"!=typeof e||0!==e.indexOf("-----BEGIN PRIVATE KEY-----"))throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return Uo(e,t,n)}(e,at(hi,this).clientAssertionSigningAlg||"RS256")),e?function(e,t){return Qt(e)}(e):$o(at(hi,this).clientSecret)}async function Gi(e){const{configuration:t}=await ot(fi,this,Mi).call(this),n=ir(),o=await rr(n),r=Ri(dt(dt({},at(hi,this).authorizationParams),null==e?void 0:e.authorizationParams)),i=new URLSearchParams(dt(dt({scope:Ui},r),{},{client_id:at(hi,this).clientId,code_challenge:o,code_challenge_method:"S256"}));return {authorizationUrl:null!=e&&e.pushedAuthorizationRequests?await kr(t,i):await _r(t,i),codeVerifier:n}}class Zi extends w{constructor(e,t){super(e,t),Object.setPrototypeOf(this,Zi.prototype);}static fromPayload(e){let{error:t,error_description:n}=e;return new Zi(t,n)}}class qi extends Zi{constructor(e,t){super(e,t),Object.setPrototypeOf(this,qi.prototype);}}class Bi extends Zi{constructor(e,t){super(e,t),Object.setPrototypeOf(this,Bi.prototype);}}class Xi extends Zi{constructor(e,t){super(e,t),Object.setPrototypeOf(this,Xi.prototype);}}class Yi extends Zi{constructor(e,t){super(e,t),Object.setPrototypeOf(this,Yi.prototype);}}class Qi extends Zi{constructor(e,t){super(e,t),Object.setPrototypeOf(this,Qi.prototype);}}class $i{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:6e5;this.contexts=new Map,this.ttlMs=e;}set(e,t){this.cleanup(),this.contexts.set(e,Object.assign(Object.assign({},t),{createdAt:Date.now()}));}get(e){const t=this.contexts.get(e);if(t){if(!(Date.now()-t.createdAt>this.ttlMs))return t;this.contexts.delete(e);}}remove(e){this.contexts.delete(e);}cleanup(){const e=Date.now();for(const[t,n]of this.contexts)e-n.createdAt>this.ttlMs&&this.contexts.delete(t);}get size(){return this.contexts.size}}class ea{constructor(e,t){this.authJsMfaClient=e,this.auth0Client=t,this.contextManager=new $i;}setMFAAuthDetails(e,t,n,o){this.contextManager.set(e,{scope:t,audience:n,mfaRequirements:o});}async getAuthenticators(e){var t,n;const o=this.contextManager.get(e);if(!(null===(t=null==o?void 0:o.mfaRequirements)||void 0===t?void 0:t.challenge)||0===o.mfaRequirements.challenge.length)throw new qi("invalid_request","challengeType is required and must contain at least one challenge type, please check mfa_required error payload");const r=o.mfaRequirements.challenge.map((e=>e.type));try{return (await this.authJsMfaClient.listAuthenticators({mfaToken:e})).filter((e=>!!e.type&&r.includes(e.type)))}catch(e){if(e instanceof Oi)throw new qi(null===(n=e.cause)||void 0===n?void 0:n.error,e.message);throw e}}async enroll(e){var t;const n=function(e){const t=Qe[e.factorType];return Object.assign(Object.assign(Object.assign({mfaToken:e.mfaToken,authenticatorTypes:t.authenticatorTypes},t.oobChannels&&{oobChannels:t.oobChannels}),"phoneNumber"in e&&{phoneNumber:e.phoneNumber}),"email"in e&&{email:e.email})}(e);try{return await this.authJsMfaClient.enrollAuthenticator(n)}catch(e){if(e instanceof xi)throw new Bi(null===(t=e.cause)||void 0===t?void 0:t.error,e.message);throw e}}async challenge(e){var t;try{const t={challengeType:e.challengeType,mfaToken:e.mfaToken};return e.authenticatorId&&(t.authenticatorId=e.authenticatorId),await this.authJsMfaClient.challengeAuthenticator(t)}catch(e){if(e instanceof ji)throw new Xi(null===(t=e.cause)||void 0===t?void 0:t.error,e.message);throw e}}async getEnrollmentFactors(e){const t=this.contextManager.get(e);if(!t||!t.mfaRequirements)throw new Qi("mfa_context_not_found","MFA context not found for this MFA token. Please retry the original request to get a new MFA token.");return t.mfaRequirements.enroll&&0!==t.mfaRequirements.enroll.length?t.mfaRequirements.enroll:[]}async verify(e){const t=this.contextManager.get(e.mfaToken);if(!t)throw new Yi("mfa_context_not_found","MFA context not found for this MFA token. Please retry the original request to get a new MFA token.");const n=function(e){return "otp"in e&&e.otp?$e:"oobCode"in e&&e.oobCode?et:"recoveryCode"in e&&e.recoveryCode?tt:void 0}(e);if(!n)throw new Yi("invalid_request","Unable to determine grant type. Provide one of: otp, oobCode, or recoveryCode.");const o=t.scope,r=t.audience;try{const t=await this.auth0Client._requestTokenForMfa({grant_type:n,mfaToken:e.mfaToken,scope:o,audience:r,otp:e.otp,oob_code:e.oobCode,binding_code:e.bindingCode,recovery_code:e.recoveryCode});return this.contextManager.remove(e.mfaToken),t}catch(e){if(e instanceof E)this.setMFAAuthDetails(e.mfa_token,o,r,e.mfa_requirements);else if(e instanceof Yi)throw new Yi(e.error,e.error_description);throw e}}}const ta=new p;class na{constructor(e){let t,n;if(this.userCache=(new pe).enclosedCache,this.activeLockKeys=new Set,this.defaultOptions={authorizationParams:{scope:"openid profile email"},useRefreshTokensFallback:false,useFormData:true},this._releaseLockOnPageHide=async()=>{const e=Array.from(this.activeLockKeys);for(const t of e)await ta.releaseLock(t);this.activeLockKeys.clear(),window.removeEventListener("pagehide",this._releaseLockOnPageHide);},this.options=Object.assign(Object.assign(Object.assign({},this.defaultOptions),e),{authorizationParams:Object.assign(Object.assign({},this.defaultOptions.authorizationParams),e.authorizationParams)}),"undefined"!=typeof window&&(()=>{if(!I())throw new Error("For security reasons, `window.crypto` is required to run `auth0-spa-js`.");if(void 0===I().subtle)throw new Error("\n auth0-spa-js must run on a secure origin. See https://github.com/auth0/auth0-spa-js/blob/main/FAQ.md#why-do-i-get-auth0-spa-js-must-run-on-a-secure-origin for more information.\n ")})(),e.cache&&e.cacheLocation&&console.warn("Both `cache` and `cacheLocation` options have been specified in the Auth0Client configuration; ignoring `cacheLocation` and using `cache`."),e.cache)n=e.cache;else {if(t=e.cacheLocation||"memory",!Me(t))throw new Error('Invalid cache location "'.concat(t,'"'));n=Me(t)();}var o;this.httpTimeoutMs=e.httpTimeoutInSeconds?1e3*e.httpTimeoutInSeconds:1e4,this.cookieStorage=false===e.legacySameSiteCookie?Pe:Re,this.orgHintCookieName=(o=this.options.clientId,"auth0.".concat(o,".organization_hint")),this.isAuthenticatedCookieName=(e=>"auth0.".concat(e,".is.authenticated"))(this.options.clientId),this.sessionCheckExpiryDays=e.sessionCheckExpiryDays||1;const r=e.useCookiesForTransactions?this.cookieStorage:Ie;var i;this.scope=function(e,t){for(var n=arguments.length,o=new Array(n>2?n-2:0),r=2;r<n;r++)o[r-2]=arguments[r];if("object"!=typeof e)return {default:ue(t,e,...o)};let i={default:ue(t,...o)};return Object.keys(e).forEach((n=>{const r=e[n];i[n]=ue(t,r,...o);})),i}(this.options.authorizationParams.scope,"openid",this.options.useRefreshTokens?"offline_access":""),this.transactionManager=new me(r,this.options.clientId,this.options.cookieDomain),this.nowProvider=this.options.nowProvider||y,this.cacheManager=new fe(n,n.allKeys?void 0:new ze(n,this.options.clientId),this.nowProvider),this.dpop=this.options.useDpop?new Ze(this.options.clientId):void 0,this.domainUrl=(i=this.options.domain,/^https?:\/\//.test(i)?i:"https://".concat(i)),this.tokenIssuer=((e,t)=>e?e.startsWith("https://")?e:"https://".concat(e,"/"):"".concat(t,"/"))(this.options.issuer,this.domainUrl);const a="".concat(this.domainUrl,"/me/"),s=this.createFetcher(Object.assign(Object.assign({},this.options.useDpop&&{dpopNonceId:"__auth0_my_account_api__"}),{getAccessToken:()=>this.getTokenSilently({authorizationParams:{scope:"create:me:connected_accounts",audience:a},detailedResponse:true})}));this.myAccountApi=new Xe(s,a),this.authJsClient=new Hi({domain:this.options.domain,clientId:this.options.clientId}),this.mfa=new ea(this.authJsClient.mfa,this),"undefined"!=typeof window&&window.Worker&&this.options.useRefreshTokens&&"memory"===t&&(this.options.workerUrl?this.worker=new Worker(this.options.workerUrl):this.worker=new Ue);}getConfiguration(){return Object.freeze({domain:this.options.domain,clientId:this.options.clientId})}_url(e){const t=this.options.auth0Client||m,n=j(t,true),o=encodeURIComponent(btoa(JSON.stringify(n)));return "".concat(this.domainUrl).concat(e,"&auth0Client=").concat(o)}_authorizeUrl(e){return this._url("/authorize?".concat(D(e)))}async _verifyIdToken(e,t,n){const o=await this.nowProvider();return ge({iss:this.tokenIssuer,aud:this.options.clientId,id_token:e,nonce:t,organization:n,leeway:this.options.leeway,max_age:(r=this.options.authorizationParams.max_age,"string"!=typeof r?r:parseInt(r,10)||void 0),now:o});var r;}_processOrgHint(e){e?this.cookieStorage.save(this.orgHintCookieName,e,{daysUntilExpire:this.sessionCheckExpiryDays,cookieDomain:this.options.cookieDomain}):this.cookieStorage.remove(this.orgHintCookieName,{cookieDomain:this.options.cookieDomain});}async _prepareAuthorizeUrl(e,t,n){var o;const r=x(O()),i=x(O()),a=O(),s=await K(a),c=U(s),u=await(null===(o=this.dpop)||void 0===o?void 0:o.calculateThumbprint()),l=((e,t,n,o,r,i,a,s,c)=>Object.assign(Object.assign(Object.assign({client_id:e.clientId},e.authorizationParams),n),{scope:le(t,n.scope,n.audience),response_type:"code",response_mode:s||"query",state:o,nonce:r,redirect_uri:a||e.authorizationParams.redirect_uri,code_challenge:i,code_challenge_method:"S256",dpop_jkt:c}))(this.options,this.scope,e,r,i,c,e.redirect_uri||this.options.authorizationParams.redirect_uri||n,null==t?void 0:t.response_mode,u),d=this._authorizeUrl(l);return {nonce:i,code_verifier:a,scope:l.scope,audience:l.audience||"default",redirect_uri:l.redirect_uri,state:r,url:d}}async loginWithPopup(e,t){var n;if(e=e||{},!(t=t||{}).popup&&(t.popup=(e=>{const t=window.screenX+(window.innerWidth-400)/2,n=window.screenY+(window.innerHeight-600)/2;return window.open(e,"auth0:authorize:popup","left=".concat(t,",top=").concat(n,",width=").concat(400,",height=").concat(600,",resizable,scrollbars=yes,status=1"))})(""),!t.popup))throw new S;const o=await this._prepareAuthorizeUrl(e.authorizationParams||{},{response_mode:"web_message"},window.location.origin);t.popup.location.href=o.url;const r=await(e=>new Promise(((t,n)=>{let o;const r=setInterval((()=>{e.popup&&e.popup.closed&&(clearInterval(r),clearTimeout(i),window.removeEventListener("message",o,false),n(new k(e.popup)));}),1e3),i=setTimeout((()=>{clearInterval(r),n(new _(e.popup)),window.removeEventListener("message",o,false);}),1e3*(e.timeoutInSeconds||60));o=function(a){if(a.data&&"authorization_response"===a.data.type){if(clearTimeout(i),clearInterval(r),window.removeEventListener("message",o,false),false!==e.closePopup&&e.popup.close(),a.data.response.error)return n(w.fromPayload(a.data.response));t(a.data.response);}},window.addEventListener("message",o);})))(Object.assign(Object.assign({},t),{timeoutInSeconds:t.timeoutInSeconds||this.options.authorizeTimeoutInSeconds||60}));if(o.state!==r.state)throw new w("state_mismatch","Invalid state");const i=(null===(n=e.authorizationParams)||void 0===n?void 0:n.organization)||this.options.authorizationParams.organization;await this._requestToken({audience:o.audience,scope:o.scope,code_verifier:o.code_verifier,grant_type:"authorization_code",code:r.code,redirect_uri:o.redirect_uri},{nonceIn:o.nonce,organization:i});}async getUser(){var e;const t=await this._getIdTokenFromCache();return null===(e=null==t?void 0:t.decodedToken)||void 0===e?void 0:e.user}async getIdTokenClaims(){var e;const t=await this._getIdTokenFromCache();return null===(e=null==t?void 0:t.decodedToken)||void 0===e?void 0:e.claims}async loginWithRedirect(){var t;const n=Je(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),{openUrl:o,fragment:r,appState:i}=n,a=e(n,["openUrl","fragment","appState"]),s=(null===(t=a.authorizationParams)||void 0===t?void 0:t.organization)||this.options.authorizationParams.organization,c=await this._prepareAuthorizeUrl(a.authorizationParams||{}),{url:u}=c,l=e(c,["url"]);this.transactionManager.create(Object.assign(Object.assign(Object.assign({},l),{appState:i,response_type:Oe.Code}),s&&{organization:s}));const d=r?"".concat(u,"#").concat(r):u;o?await o(d):window.location.assign(d);}async handleRedirectCallback(){const e=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:window.location.href).split("?").slice(1);if(0===e.length)throw new Error("There are no query params available for parsing.");const t=this.transactionManager.get();if(!t)throw new w("missing_transaction","Invalid state");this.transactionManager.remove();const n=(e=>{e.indexOf("#")>-1&&(e=e.substring(0,e.indexOf("#")));const t=new URLSearchParams(e);return {state:t.get("state"),code:t.get("code")||void 0,connect_code:t.get("connect_code")||void 0,error:t.get("error")||void 0,error_description:t.get("error_description")||void 0}})(e.join(""));return t.response_type===Oe.ConnectCode?this._handleConnectAccountRedirectCallback(n,t):this._handleLoginRedirectCallback(n,t)}async _handleLoginRedirectCallback(e,t){const{code:n,state:o,error:r,error_description:i}=e;if(r)throw new g(r,i||r,o,t.appState);if(!t.code_verifier||t.state&&t.state!==o)throw new w("state_mismatch","Invalid state");const a=t.organization,s=t.nonce,c=t.redirect_uri;return await this._requestToken(Object.assign({audience:t.audience,scope:t.scope,code_verifier:t.code_verifier,grant_type:"authorization_code",code:n},c?{redirect_uri:c}:{}),{nonceIn:s,organization:a}),{appState:t.appState,response_type:Oe.Code}}async _handleConnectAccountRedirectCallback(e,t){const{connect_code:n,state:o,error:r,error_description:i}=e;if(r)throw new v(r,i||r,t.connection,o,t.appState);if(!n)throw new w("missing_connect_code","Missing connect code");if(!(t.code_verifier&&t.state&&t.auth_session&&t.redirect_uri&&t.state===o))throw new w("state_mismatch","Invalid state");const a=await this.myAccountApi.completeAccount({auth_session:t.auth_session,connect_code:n,redirect_uri:t.redirect_uri,code_verifier:t.code_verifier});return Object.assign(Object.assign({},a),{appState:t.appState,response_type:Oe.ConnectCode})}async checkSession(e){if(!this.cookieStorage.get(this.isAuthenticatedCookieName)){if(!this.cookieStorage.get("auth0.is.authenticated"))return;this.cookieStorage.save(this.isAuthenticatedCookieName,true,{daysUntilExpire:this.sessionCheckExpiryDays,cookieDomain:this.options.cookieDomain}),this.cookieStorage.remove("auth0.is.authenticated");}try{await this.getTokenSilently(e);}catch(e){}}async getTokenSilently(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};var t,n;const o=Object.assign(Object.assign({cacheMode:"on"},e),{authorizationParams:Object.assign(Object.assign(Object.assign({},this.options.authorizationParams),e.authorizationParams),{scope:le(this.scope,null===(t=e.authorizationParams)||void 0===t?void 0:t.scope,(null===(n=e.authorizationParams)||void 0===n?void 0:n.audience)||this.options.authorizationParams.audience)})}),r=await((e,t)=>{let n=Ne[t];return n||(n=e().finally((()=>{delete Ne[t],n=null;})),Ne[t]=n),n})((()=>this._getTokenSilently(o)),"".concat(this.options.clientId,"::").concat(o.authorizationParams.audience,"::").concat(o.authorizationParams.scope));return e.detailedResponse?r:null==r?void 0:r.access_token}async _getTokenSilently(t){const{cacheMode:n}=t,o=e(t,["cacheMode"]);if("off"!==n){const e=await this._getEntryFromCache({scope:o.authorizationParams.scope,audience:o.authorizationParams.audience||"default",clientId:this.options.clientId,cacheMode:n});if(e)return e}if("cache-only"===n)return;const r=(i=this.options.clientId,a=o.authorizationParams.audience||"default","".concat("auth0.lock.getTokenSilently",".").concat(i,".").concat(a));var i,a;if(!await We((()=>ta.acquireLock(r,5e3)),10))throw new b;this.activeLockKeys.add(r),1===this.activeLockKeys.size&&window.addEventListener("pagehide",this._releaseLockOnPageHide);try{if("off"!==n){const e=await this._getEntryFromCache({scope:o.authorizationParams.scope,audience:o.authorizationParams.audience||"default",clientId:this.options.clientId});if(e)return e}const e=this.options.useRefreshTokens?await this._getTokenUsingRefreshToken(o):await this._getTokenFromIFrame(o),{id_token:t,token_type:i,access_token:a,oauthTokenScope:s,expires_in:c}=e;return Object.assign(Object.assign({id_token:t,token_type:i,access_token:a},s?{scope:s}:null),{expires_in:c})}finally{await ta.releaseLock(r),this.activeLockKeys.delete(r),0===this.activeLockKeys.size&&window.removeEventListener("pagehide",this._releaseLockOnPageHide);}}async getTokenWithPopup(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var n,o;const r=Object.assign(Object.assign({},e),{authorizationParams:Object.assign(Object.assign(Object.assign({},this.options.authorizationParams),e.authorizationParams),{scope:le(this.scope,null===(n=e.authorizationParams)||void 0===n?void 0:n.scope,(null===(o=e.authorizationParams)||void 0===o?void 0:o.audience)||this.options.authorizationParams.audience)})});t=Object.assign(Object.assign({},f),t),await this.loginWithPopup(r,t);return (await this.cacheManager.get(new de({scope:r.authorizationParams.scope,audience:r.authorizationParams.audience||"default",clientId:this.options.clientId}),void 0,this.options.useMrrt)).access_token}async isAuthenticated(){return !!await this.getUser()}_buildLogoutUrl(t){null!==t.clientId?t.clientId=t.clientId||this.options.clientId:delete t.clientId;const n=t.logoutParams||{},{federated:o}=n,r=e(n,["federated"]),i=o?"&federated":"";return this._url("/v2/logout?".concat(D(Object.assign({clientId:t.clientId},r))))+i}async logout(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};var n;const o=Je(t),{openUrl:r}=o,i=e(o,["openUrl"]);null===t.clientId?await this.cacheManager.clear():await this.cacheManager.clear(t.clientId||this.options.clientId),this.cookieStorage.remove(this.orgHintCookieName,{cookieDomain:this.options.cookieDomain}),this.cookieStorage.remove(this.isAuthenticatedCookieName,{cookieDomain:this.options.cookieDomain}),this.userCache.remove("@@user@@"),await(null===(n=this.dpop)||void 0===n?void 0:n.clear());const a=this._buildLogoutUrl(i);r?await r(a):false!==r&&window.location.assign(a);}async _getTokenFromIFrame(e){const t=(n=this.options.clientId,"".concat("auth0.lock.getTokenFromIFrame",".").concat(n));var n;if(!await We((()=>ta.acquireLock(t,5e3)),10))throw new b;try{const n=Object.assign(Object.assign({},e.authorizationParams),{prompt:"none"}),o=this.cookieStorage.get(this.orgHintCookieName);o&&!n.organization&&(n.organization=o);const{url:r,state:i,nonce:a,code_verifier:s,redirect_uri:c,scope:u,audience:l}=await this._prepareAuthorizeUrl(n,{response_mode:"web_message"},window.location.origin);if(window.crossOriginIsolated)throw new w("login_required","The application is running in a Cross-Origin Isolated context, silently retrieving a token without refresh token is not possible.");const d=e.timeoutInSeconds||this.options.authorizeTimeoutInSeconds;let h;try{h=new URL(this.domainUrl).origin;}catch(e){h=this.domainUrl;}const p=await function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:60;return new Promise(((o,r)=>{const i=window.document.createElement("iframe");i.setAttribute("width","0"),i.setAttribute("height","0"),i.style.display="none";const a=()=>{window.document.body.contains(i)&&(window.document.body.removeChild(i),window.removeEventListener("message",s,!1));};let s;const c=setTimeout((()=>{r(new b),a();}),1e3*n);s=function(e){if(e.origin!=t)return;if(!e.data||"authorization_response"!==e.data.type)return;const n=e.source;n&&n.close(),e.data.response.error?r(w.fromPayload(e.data.response)):o(e.data.response),clearTimeout(c),window.removeEventListener("message",s,!1),setTimeout(a,2e3);},window.addEventListener("message",s,!1),window.document.body.appendChild(i),i.setAttribute("src",e);}))}(r,h,d);if(i!==p.state)throw new w("state_mismatch","Invalid state");const f=await this._requestToken(Object.assign(Object.assign({},e.authorizationParams),{code_verifier:s,code:p.code,grant_type:"authorization_code",redirect_uri:c,timeout:e.authorizationParams.timeout||this.httpTimeoutMs}),{nonceIn:a,organization:n.organization});return Object.assign(Object.assign({},f),{scope:u,oauthTokenScope:f.scope,audience:l})}catch(e){throw "login_required"===e.error&&this.logout({openUrl:false}),e}finally{await ta.releaseLock(t);}}async _getTokenUsingRefreshToken(e){var t,n;const o=await this.cacheManager.get(new de({scope:e.authorizationParams.scope,audience:e.authorizationParams.audience||"default",clientId:this.options.clientId}),void 0,this.options.useMrrt);if(!(o&&o.refresh_token||this.worker)){if(this.options.useRefreshTokensFallback)return await this._getTokenFromIFrame(e);throw new A(e.authorizationParams.audience||"default",e.authorizationParams.scope)}const r=e.authorizationParams.redirect_uri||this.options.authorizationParams.redirect_uri||window.location.origin,i="number"==typeof e.timeoutInSeconds?1e3*e.timeoutInSeconds:null,a=((e,t,n,o)=>{var r;if(e&&n&&o){if(t.audience!==n)return t.scope;const e=o.split(" "),i=(null===(r=t.scope)||void 0===r?void 0:r.split(" "))||[],a=i.every((t=>e.includes(t)));return e.length>=i.length&&a?o:t.scope}return t.scope})(this.options.useMrrt,e.authorizationParams,null==o?void 0:o.audience,null==o?void 0:o.scope);try{const t=await this._requestToken(Object.assign(Object.assign(Object.assign({},e.authorizationParams),{grant_type:"refresh_token",refresh_token:o&&o.refresh_token,redirect_uri:r}),i&&{timeout:i}),{scopesToRequest:a});if(t.refresh_token&&(null==o?void 0:o.refresh_token)&&await this.cacheManager.updateEntry(o.refresh_token,t.refresh_token),this.options.useMrrt){if(s=null==o?void 0:o.audience,c=null==o?void 0:o.scope,u=e.authorizationParams.audience,l=e.authorizationParams.scope,s!==u||!Ve(l,c)){if(!Ve(a,t.scope)){if(this.options.useRefreshTokensFallback)return await this._getTokenFromIFrame(e);await this.cacheManager.remove(this.options.clientId,e.authorizationParams.audience,e.authorizationParams.scope);const n=((e,t)=>{const n=(null==e?void 0:e.split(" "))||[],o=(null==t?void 0:t.split(" "))||[];return n.filter((e=>-1==o.indexOf(e))).join(",")})(a,t.scope);throw new T(e.authorizationParams.audience||"default",n)}}}return Object.assign(Object.assign({},t),{scope:e.authorizationParams.scope,oauthTokenScope:t.scope,audience:e.authorizationParams.audience||"default"})}catch(o){if((o.message.indexOf("Missing Refresh Token")>-1||o.message&&o.message.indexOf("invalid refresh token")>-1)&&this.options.useRefreshTokensFallback)return await this._getTokenFromIFrame(e);throw o instanceof E&&this.mfa.setMFAAuthDetails(o.mfa_token,null===(t=e.authorizationParams)||void 0===t?void 0:t.scope,null===(n=e.authorizationParams)||void 0===n?void 0:n.audience,o.mfa_requirements),o}var s,c,u,l;}async _saveEntryInCache(t){const{id_token:n,decodedToken:o}=t,r=e(t,["id_token","decodedToken"]);this.userCache.set("@@user@@",{id_token:n,decodedToken:o}),await this.cacheManager.setIdToken(this.options.clientId,t.id_token,t.decodedToken),await this.cacheManager.set(r);}async _getIdTokenFromCache(){const e=this.options.authorizationParams.audience||"default",t=this.scope[e],n=await this.cacheManager.getIdToken(new de({clientId:this.options.clientId,audience:e,scope:t})),o=this.userCache.get("@@user@@");return n&&n.id_token===(null==o?void 0:o.id_token)?o:(this.userCache.set("@@user@@",n),n)}async _getEntryFromCache(e){let{scope:t,audience:n,clientId:o,cacheMode:r}=e;const i=await this.cacheManager.get(new de({scope:t,audience:n,clientId:o}),60,this.options.useMrrt,r);if(i&&i.access_token){const{token_type:e,access_token:t,oauthTokenScope:n,expires_in:o}=i,r=await this._getIdTokenFromCache();return r&&Object.assign(Object.assign({id_token:r.id_token,token_type:e||"Bearer",access_token:t},n?{scope:n}:null),{expires_in:o})}}async _requestToken(e,t){var n,o;const{nonceIn:r,organization:i,scopesToRequest:a}=t||{},s=await se(Object.assign(Object.assign({baseUrl:this.domainUrl,client_id:this.options.clientId,auth0Client:this.options.auth0Client,useFormData:this.options.useFormData,timeout:this.httpTimeoutMs,useMrrt:this.options.useMrrt,dpop:this.dpop},e),{scope:a||e.scope}),this.worker),c=await this._verifyIdToken(s.id_token,r,i);if("authorization_code"===e.grant_type){const e=await this._getIdTokenFromCache();(null===(o=null===(n=null==e?void 0:e.decodedToken)||void 0===n?void 0:n.claims)||void 0===o?void 0:o.sub)&&e.decodedToken.claims.sub!==c.claims.sub&&(await this.cacheManager.clear(this.options.clientId),this.userCache.remove("@@user@@"));}return await this._saveEntryInCache(Object.assign(Object.assign(Object.assign(Object.assign({},s),{decodedToken:c,scope:e.scope,audience:e.audience||"default"}),s.scope?{oauthTokenScope:s.scope}:null),{client_id:this.options.clientId})),this.cookieStorage.save(this.isAuthenticatedCookieName,true,{daysUntilExpire:this.sessionCheckExpiryDays,cookieDomain:this.options.cookieDomain}),this._processOrgHint(i||c.claims.org_id),Object.assign(Object.assign({},s),{decodedToken:c})}async exchangeToken(e){return this._requestToken({grant_type:"urn:ietf:params:oauth:grant-type:token-exchange",subject_token:e.subject_token,subject_token_type:e.subject_token_type,scope:le(this.scope,e.scope,e.audience||this.options.authorizationParams.audience),audience:e.audience||this.options.authorizationParams.audience,organization:e.organization||this.options.authorizationParams.organization})}_assertDpop(e){if(!e)throw new Error("`useDpop` option must be enabled before using DPoP.")}getDpopNonce(e){return this._assertDpop(this.dpop),this.dpop.getNonce(e)}setDpopNonce(e,t){return this._assertDpop(this.dpop),this.dpop.setNonce(e,t)}generateDpopProof(e){return this._assertDpop(this.dpop),this.dpop.generateProof(e)}createFetcher(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return new Be(e,{isDpopEnabled:()=>!!this.options.useDpop,getAccessToken:e=>{var t;return this.getTokenSilently({authorizationParams:{scope:null===(t=null==e?void 0:e.scope)||void 0===t?void 0:t.join(" "),audience:null==e?void 0:e.audience},detailedResponse:true})},getDpopNonce:()=>this.getDpopNonce(e.dpopNonceId),setDpopNonce:t=>this.setDpopNonce(t,e.dpopNonceId),generateDpopProof:e=>this.generateDpopProof(e)})}async connectAccountWithRedirect(e){const{openUrl:t,appState:n,connection:o,scopes:r,authorization_params:i,redirectUri:a=this.options.authorizationParams.redirect_uri||window.location.origin}=e;if(!o)throw new Error("connection is required");const s=x(O()),c=O(),u=await K(c),l=U(u),{connect_uri:d,connect_params:h,auth_session:p}=await this.myAccountApi.connectAccount({connection:o,scopes:r,redirect_uri:a,state:s,code_challenge:l,code_challenge_method:"S256",authorization_params:i});this.transactionManager.create({state:s,code_verifier:c,auth_session:p,redirect_uri:a,appState:n,connection:o,response_type:Oe.ConnectCode});const f=new URL(d);f.searchParams.set("ticket",h.ticket),t?await t(f.toString()):window.location.assign(f);}async _requestTokenForMfa(t,n){const{mfaToken:o}=t,r=e(t,["mfaToken"]);return this._requestToken(Object.assign(Object.assign({},r),{mfa_token:o}),n)}}async function oa(e){const t=new na(e);return await t.checkSession(),t}
663
198
 
664
199
  /**
665
- * TokenService - Angular service wrapper for TokenManager
666
- * Provides Angular dependency injection support for the framework-agnostic TokenManager
667
- *
668
- * @example
669
- * ```typescript
670
- * import { Component, inject } from '@angular/core';
671
- * import { TokenService } from 'common-libs';
672
- *
673
- * export class AuthService {
674
- * private tokenService = inject(TokenService);
675
- *
676
- * login(token: string) {
677
- * this.tokenService.setToken(token);
678
- * }
200
+ * Auth0 Configuration
201
+ * Centralized configuration for Auth0 integration
679
202
  *
680
- * isAuthenticated(): boolean {
681
- * return this.tokenService.isAuthenticated();
682
- * }
683
- * }
684
- * ```
203
+ * Environment variables are typically set in consuming applications
204
+ * Default values are provided for development/testing
685
205
  */
686
- exports.TokenService = class TokenService extends TokenManager {
687
- constructor() {
688
- console.log("In TokenService of opensourcekd 2");
689
- super();
690
- }
206
+ /**
207
+ * Auth0 client configuration
208
+ * Override these values in your consuming application by setting them before importing AuthService
209
+ */
210
+ const AUTH0_CONFIG = {
211
+ domain: '', // Set in consuming app: process.env['NX_AUTH0_DOMAIN'] || 'your-domain.auth0.com'
212
+ clientId: '', // Set in consuming app: process.env['NX_AUTH0_CLIENT_ID'] || 'your-client-id'
213
+ redirectUri: typeof window !== 'undefined' ? window.location.origin + '/auth-callback' : '',
214
+ logoutUri: typeof window !== 'undefined' ? window.location.origin : '',
215
+ audience: '', // Optional: Set in consuming app if using API authorization
216
+ scope: 'openid profile email', // Default scopes
217
+ connection: undefined, // Optional: Force specific connection (e.g., 'Username-Password-Authentication')
691
218
  };
692
- exports.TokenService = __decorate([
693
- core.Injectable({
694
- providedIn: 'root'
695
- }),
696
- __metadata("design:paramtypes", [])
697
- ], exports.TokenService);
698
-
699
219
  /**
700
- * StorageService - Angular service wrapper for StorageManager
701
- * Provides Angular dependency injection support for the framework-agnostic StorageManager
702
- *
703
- * @example
704
- * ```typescript
705
- * import { Component, inject } from '@angular/core';
706
- * import { StorageService } from 'common-libs';
707
- *
708
- * export class UserPreferencesService {
709
- * private storage = inject(StorageService);
710
- *
711
- * savePreferences(prefs: any) {
712
- * this.storage.setLocal('user-prefs', prefs);
713
- * }
714
- *
715
- * getPreferences() {
716
- * return this.storage.getLocal('user-prefs');
717
- * }
718
- * }
719
- * ```
220
+ * Storage configuration
221
+ * Controls where sensitive data is stored
720
222
  */
721
- exports.StorageService = class StorageService extends StorageManager {
722
- constructor() {
723
- super();
724
- }
223
+ const STORAGE_CONFIG = {
224
+ TOKEN_STORAGE: 'sessionStorage',
225
+ USER_INFO_STORAGE: 'sessionStorage',
725
226
  };
726
- exports.StorageService = __decorate([
727
- core.Injectable({
728
- providedIn: 'root'
729
- }),
730
- __metadata("design:paramtypes", [])
731
- ], exports.StorageService);
732
-
733
227
  /**
734
- * LoggerService - Angular service wrapper for Logger
735
- * Provides Angular dependency injection support for the framework-agnostic Logger
228
+ * Storage keys for auth data
229
+ */
230
+ const STORAGE_KEYS = {
231
+ ACCESS_TOKEN: 'auth0_access_token',
232
+ USER_INFO: 'auth0_user_info',
233
+ };
234
+ /**
235
+ * Helper functions for storage operations
236
+ * These work with both localStorage and sessionStorage
237
+ */
238
+ /**
239
+ * Get item from storage
240
+ * @param key - Storage key
241
+ * @param storageType - Type of storage to use
242
+ * @returns Stored value or null
243
+ */
244
+ function getStorageItem(key, storageType = 'sessionStorage') {
245
+ if (typeof window === 'undefined')
246
+ return null;
247
+ const storage = storageType === 'localStorage' ? localStorage : sessionStorage;
248
+ return storage.getItem(key);
249
+ }
250
+ /**
251
+ * Set item in storage
252
+ * @param key - Storage key
253
+ * @param value - Value to store
254
+ * @param storageType - Type of storage to use
255
+ */
256
+ function setStorageItem(key, value, storageType = 'sessionStorage') {
257
+ if (typeof window === 'undefined')
258
+ return;
259
+ const storage = storageType === 'localStorage' ? localStorage : sessionStorage;
260
+ storage.setItem(key, value);
261
+ }
262
+ /**
263
+ * Remove item from storage
264
+ * @param key - Storage key
265
+ * @param storageType - Type of storage to use
266
+ */
267
+ function removeStorageItem(key, storageType = 'sessionStorage') {
268
+ if (typeof window === 'undefined')
269
+ return;
270
+ const storage = storageType === 'localStorage' ? localStorage : sessionStorage;
271
+ storage.removeItem(key);
272
+ }
273
+ /**
274
+ * Configure Auth0 settings
275
+ * Call this function in your consuming application before using AuthService
736
276
  *
737
277
  * @example
738
278
  * ```typescript
739
- * import { Component, inject } from '@angular/core';
740
- * import { LoggerService, LogLevel } from 'common-libs';
741
- *
742
- * export class MyService {
743
- * private logger = inject(LoggerService);
744
- *
745
- * constructor() {
746
- * this.logger.configure({
747
- * level: LogLevel.DEBUG,
748
- * prefix: 'MyApp'
749
- * });
750
- * }
279
+ * import { configureAuth0 } from '@opensourcekd/ng-common-libs';
751
280
  *
752
- * doSomething() {
753
- * this.logger.info('Doing something');
754
- * }
755
- * }
281
+ * configureAuth0({
282
+ * domain: 'your-domain.auth0.com',
283
+ * clientId: 'your-client-id',
284
+ * audience: 'https://your-api.com'
285
+ * });
756
286
  * ```
757
287
  */
758
- exports.LoggerService = class LoggerService extends Logger {
759
- constructor() {
760
- super();
761
- }
762
- };
763
- exports.LoggerService = __decorate([
764
- core.Injectable({
765
- providedIn: 'root'
766
- }),
767
- __metadata("design:paramtypes", [])
768
- ], exports.LoggerService);
288
+ function configureAuth0(config) {
289
+ Object.assign(AUTH0_CONFIG, config);
290
+ }
769
291
 
770
292
  /**
771
- * PermissionService - Manages user permissions and roles
293
+ * Authentication service for Auth0 integration
294
+ * Handles login, logout, token management, and user session
295
+ * Uses sessionStorage for sensitive data and emits authentication events for MicroApps
296
+ *
297
+ * Configuration is centralized in config/auth.config.ts for easy management
298
+ *
299
+ * NOTE: All navigation logic using setTimeout is commented out as per requirements.
300
+ * To enable navigation after auth operations, uncomment the marked sections in consuming components.
772
301
  */
773
- exports.PermissionService = class PermissionService {
774
- tokenService = core.inject(exports.TokenService);
302
+ exports.AuthService = class AuthService {
303
+ http;
304
+ eventBus;
305
+ id = 'auth of pokemon';
306
+ // Standard JWT claims that should be excluded from additional claims
307
+ STANDARD_JWT_CLAIMS = [
308
+ 'sub', 'name', 'email', 'email_verified', 'preferred_username',
309
+ 'given_name', 'family_name', 'nickname', 'locale', 'picture', 'phone',
310
+ 'phone_verified', 'updated_at', 'iss', 'aud', 'exp', 'iat',
311
+ 'auth_time', 'nonce', 'acr', 'amr', 'azp', 'at_hash', 'c_hash'
312
+ ];
313
+ auth0Client = null;
314
+ initializationPromise;
315
+ userSubject = new rxjs.BehaviorSubject(this.getUserInfoFromStorage());
316
+ user$ = this.userSubject.asObservable();
317
+ constructor(http, eventBus) {
318
+ this.http = http;
319
+ this.eventBus = eventBus;
320
+ console.log("[AuthService] Initializing Auth0 authentication service");
321
+ this.initializationPromise = this.initializeAuth0();
322
+ }
323
+ /**
324
+ * Initialize Auth0 client
325
+ */
326
+ async initializeAuth0() {
327
+ try {
328
+ console.log("[AuthService] Starting Auth0 client initialization...");
329
+ // Defensive check for AUTH0_CONFIG
330
+ if (!AUTH0_CONFIG || typeof AUTH0_CONFIG !== 'object') {
331
+ throw new Error('[AuthService] AUTH0_CONFIG is not defined or invalid');
332
+ }
333
+ if (!AUTH0_CONFIG.domain || !AUTH0_CONFIG.clientId) {
334
+ throw new Error('[AuthService] AUTH0_CONFIG is missing required fields (domain, clientId)');
335
+ }
336
+ this.auth0Client = await oa({
337
+ domain: AUTH0_CONFIG.domain,
338
+ clientId: AUTH0_CONFIG.clientId,
339
+ authorizationParams: {
340
+ redirect_uri: AUTH0_CONFIG.redirectUri,
341
+ scope: AUTH0_CONFIG.scope,
342
+ ...(AUTH0_CONFIG.audience && { audience: AUTH0_CONFIG.audience }),
343
+ },
344
+ cacheLocation: 'memory', // Use memory cache instead of localStorage
345
+ useRefreshTokens: true, // Enable refresh tokens for better security
346
+ });
347
+ console.log("[AuthService] Auth0 client initialized successfully");
348
+ }
349
+ catch (error) {
350
+ console.error("[AuthService] Failed to initialize Auth0 client:", error);
351
+ throw error;
352
+ }
353
+ }
775
354
  /**
776
- * Check if user has a specific permission
355
+ * Ensure Auth0 client is initialized before use
777
356
  */
778
- hasPermission(permission) {
779
- const user = this.tokenService.getUserFromToken();
780
- const permissions = user?.permissions || [];
781
- return permissions.includes(permission);
357
+ async ensureInitialized() {
358
+ await this.initializationPromise;
359
+ if (!this.auth0Client) {
360
+ throw new Error('[AuthService] Auth0 client failed to initialize');
361
+ }
782
362
  }
783
363
  /**
784
- * Check if user has any of the specified permissions
364
+ * Login with Auth0
365
+ * Redirects to Auth0 Universal Login
366
+ * Preserves current URL parameters (like invitation tokens) through the auth flow
367
+ *
368
+ * @param user - Optional user identifier for logging
369
+ * @param options - Optional login options including invitation and organization parameters
785
370
  */
786
- hasAnyPermission(permissions) {
787
- return permissions.some(permission => this.hasPermission(permission));
371
+ async login(user, options) {
372
+ if (user) {
373
+ console.log(`[AuthService] Logging in: ${user}`);
374
+ }
375
+ try {
376
+ // Ensure Auth0 client is initialized
377
+ await this.ensureInitialized();
378
+ // Capture current URL search parameters to preserve through auth flow
379
+ // Only capture if we're not already on the callback page
380
+ const currentPath = window.location.pathname;
381
+ const isCallbackPage = currentPath.includes('auth-callback');
382
+ let appState = undefined;
383
+ if (!isCallbackPage && window.location.search) {
384
+ const currentSearchParams = window.location.search;
385
+ appState = { returnTo: currentSearchParams };
386
+ console.log('[AuthService] Preserving URL parameters through auth flow:', currentSearchParams);
387
+ }
388
+ // Build authorization parameters
389
+ const authorizationParams = {
390
+ redirect_uri: AUTH0_CONFIG.redirectUri,
391
+ scope: AUTH0_CONFIG.scope,
392
+ ...(AUTH0_CONFIG.audience && { audience: AUTH0_CONFIG.audience }),
393
+ ...(AUTH0_CONFIG.connection && { connection: AUTH0_CONFIG.connection }),
394
+ };
395
+ // Add organization invitation parameters if provided
396
+ if (options?.invitation) {
397
+ authorizationParams.invitation = options.invitation;
398
+ console.log('[AuthService] Including invitation parameter:', options.invitation);
399
+ }
400
+ if (options?.organization) {
401
+ authorizationParams.organization = options.organization;
402
+ console.log('[AuthService] Including organization parameter:', options.organization);
403
+ }
404
+ console.log('[AuthService] Starting Auth0 login redirect...');
405
+ await this.auth0Client.loginWithRedirect({
406
+ authorizationParams,
407
+ ...(appState && { appState })
408
+ });
409
+ }
410
+ catch (error) {
411
+ console.error("[AuthService] Login failed:", error);
412
+ throw error; // Re-throw to allow caller to handle
413
+ }
788
414
  }
789
415
  /**
790
- * Check if user has all of the specified permissions
416
+ * Handle OAuth2 callback after successful authorization
417
+ * Processes the callback and retrieves user info
418
+ *
419
+ * NOTE: Navigation after successful/failed authentication should be handled in the calling component
420
+ * using setTimeout. See commented examples in app.component.ts
421
+ *
422
+ * @returns Promise<{ success: boolean, appState?: any }> - Success status and preserved appState
791
423
  */
792
- hasAllPermissions(permissions) {
793
- return permissions.every(permission => this.hasPermission(permission));
424
+ async handleCallback() {
425
+ try {
426
+ console.log("[AuthService] Processing Auth0 callback...");
427
+ // Ensure Auth0 client is initialized
428
+ await this.ensureInitialized();
429
+ // Process the callback
430
+ const result = await this.auth0Client.handleRedirectCallback();
431
+ console.log("[AuthService] Callback processed successfully");
432
+ // Log preserved appState if present
433
+ if (result.appState) {
434
+ console.log('[AuthService] Restored appState from auth flow:', JSON.stringify(result.appState));
435
+ }
436
+ else {
437
+ console.log('[AuthService] No appState restored (user may not have started from invitation link)');
438
+ }
439
+ // Get user info
440
+ const user = await this.auth0Client.getUser();
441
+ if (user) {
442
+ this.logUserClaims(user);
443
+ this.setUserInfo(user);
444
+ }
445
+ else {
446
+ console.warn('[AuthService] No user info returned from Auth0');
447
+ return { success: false };
448
+ }
449
+ // Get and store access token
450
+ const token = await this.auth0Client.getTokenSilently();
451
+ this.setToken(token);
452
+ console.log("[AuthService] Authentication successful");
453
+ return { success: true, appState: result.appState };
454
+ }
455
+ catch (error) {
456
+ console.error("[AuthService] Error processing callback:", error);
457
+ console.error("[AuthService] Error details:", JSON.stringify(error, null, 2));
458
+ return { success: false };
459
+ }
460
+ }
461
+ /**
462
+ * Log all user claims for debugging
463
+ * @param user - User info from Auth0
464
+ */
465
+ logUserClaims(user) {
466
+ console.log('='.repeat(80));
467
+ console.log('[AuthService] 🔍 AUTH0 ID TOKEN - ALL CLAIMS:');
468
+ console.log('='.repeat(80));
469
+ // Standard OIDC claims
470
+ this.logStandardClaims(user);
471
+ // Auth0 custom claims (namespaced)
472
+ const customClaims = this.getCustomClaims(user);
473
+ this.logClaims('\n🔑 Custom Claims (Auth0):', customClaims, user);
474
+ // Additional claims
475
+ const additionalClaims = this.getAdditionalClaims(user);
476
+ this.logClaims('\n🔧 Additional Claims:', additionalClaims, user);
477
+ // Complete claim dump
478
+ console.log('\n📦 Complete User Object (JSON):');
479
+ console.log(JSON.stringify(user, null, 2));
480
+ console.log('='.repeat(80));
481
+ }
482
+ /**
483
+ * Log standard OIDC claims
484
+ * @param user - User info from Auth0
485
+ */
486
+ logStandardClaims(user) {
487
+ console.log('\n📋 Standard OIDC Claims:');
488
+ const standardClaimKeys = ['sub', 'name', 'email', 'email_verified', 'preferred_username',
489
+ 'given_name', 'family_name', 'nickname', 'locale', 'picture',
490
+ 'phone', 'phone_verified', 'updated_at'];
491
+ standardClaimKeys.forEach(key => {
492
+ const displayKey = key === 'sub' ? `${key} (Subject/User ID)` : key;
493
+ console.log(` • ${displayKey}:`, user[key]);
494
+ });
794
495
  }
795
496
  /**
796
- * Check if user has a specific role
497
+ * Log claims with consistent formatting
498
+ * @param header - Section header to display
499
+ * @param claims - Array of claim keys to log
500
+ * @param user - User info object
797
501
  */
798
- hasRole(role) {
799
- const user = this.tokenService.getUserFromToken();
800
- const roles = user?.roles || [];
801
- return roles.includes(role);
502
+ logClaims(header, claims, user) {
503
+ console.log(header);
504
+ if (claims.length === 0) {
505
+ console.log(' No custom claims found');
506
+ return;
507
+ }
508
+ claims.forEach(claim => {
509
+ const value = user[claim];
510
+ const formattedValue = typeof value === 'object' ? JSON.stringify(value, null, 2) : value;
511
+ console.log(` • ${claim}:`, formattedValue);
512
+ });
802
513
  }
803
514
  /**
804
- * Check if user has any of the specified roles
515
+ * Get custom namespaced claims from user info
516
+ * @param user - User info object
517
+ * @returns Array of custom claim keys
805
518
  */
806
- hasAnyRole(roles) {
807
- return roles.some(role => this.hasRole(role));
519
+ getCustomClaims(user) {
520
+ return Object.keys(user).filter(key => !this.STANDARD_JWT_CLAIMS.includes(key) && this.isNamespacedClaim(key));
808
521
  }
809
522
  /**
810
- * Check if user has all of the specified roles
523
+ * Get additional non-namespaced claims from user info
524
+ * @param user - User info object
525
+ * @returns Array of additional claim keys
811
526
  */
812
- hasAllRoles(roles) {
813
- return roles.every(role => this.hasRole(role));
527
+ getAdditionalClaims(user) {
528
+ return Object.keys(user).filter(key => !this.STANDARD_JWT_CLAIMS.includes(key) && !this.isNamespacedClaim(key));
814
529
  }
815
530
  /**
816
- * Get all user permissions
531
+ * Check if a claim key is namespaced
532
+ * @param key - Claim key to check
533
+ * @returns True if the key starts with http:// or https://
817
534
  */
818
- getPermissions() {
819
- const user = this.tokenService.getUserFromToken();
820
- return user?.permissions || [];
535
+ isNamespacedClaim(key) {
536
+ return key.startsWith('http://') || key.startsWith('https://');
821
537
  }
822
538
  /**
823
- * Get all user roles
539
+ * Logout user and clear authentication state
540
+ * Redirects to Auth0 logout endpoint and clears local state
824
541
  */
825
- getRoles() {
826
- const user = this.tokenService.getUserFromToken();
827
- return user?.roles || [];
542
+ async logout() {
543
+ // Clear local storage
544
+ removeStorageItem(STORAGE_KEYS.ACCESS_TOKEN, STORAGE_CONFIG.TOKEN_STORAGE);
545
+ removeStorageItem(STORAGE_KEYS.USER_INFO, STORAGE_CONFIG.USER_INFO_STORAGE);
546
+ this.userSubject.next(null);
547
+ this.emitAuthEvent('logout', null);
548
+ console.log('[AuthService] User logged out, clearing Auth0 session');
549
+ // Logout from Auth0
550
+ try {
551
+ await this.ensureInitialized();
552
+ await this.auth0Client.logout({
553
+ logoutParams: {
554
+ returnTo: AUTH0_CONFIG.logoutUri
555
+ }
556
+ });
557
+ }
558
+ catch (error) {
559
+ console.error('[AuthService] Error during Auth0 logout:', error);
560
+ }
828
561
  }
829
562
  /**
830
- * Get user ID from token
563
+ * Get current access token from storage or Auth0 client
564
+ * @returns string | null - Access token or null if not authenticated
831
565
  */
832
- getUserId() {
833
- const user = this.tokenService.getUserFromToken();
834
- return user?.sub || user?.id || user?.userId || null;
566
+ async getToken() {
567
+ // Try to get from storage first
568
+ const storedToken = getStorageItem(STORAGE_KEYS.ACCESS_TOKEN, STORAGE_CONFIG.TOKEN_STORAGE);
569
+ if (storedToken) {
570
+ return storedToken;
571
+ }
572
+ // If not in storage, try to get from Auth0 client
573
+ try {
574
+ await this.ensureInitialized();
575
+ const token = await this.auth0Client.getTokenSilently();
576
+ this.setToken(token);
577
+ return token;
578
+ }
579
+ catch (error) {
580
+ console.error('[AuthService] Error getting token from Auth0:', error);
581
+ return null;
582
+ }
835
583
  }
836
584
  /**
837
- * Get username from token
585
+ * Get current access token synchronously from storage only
586
+ * Use this for synchronous operations like interceptors
587
+ * @returns string | null - Access token or null if not authenticated
838
588
  */
839
- getUsername() {
840
- const user = this.tokenService.getUserFromToken();
841
- return user?.username || user?.name || user?.email || null;
589
+ getTokenSync() {
590
+ return getStorageItem(STORAGE_KEYS.ACCESS_TOKEN, STORAGE_CONFIG.TOKEN_STORAGE);
842
591
  }
843
592
  /**
844
- * Get user email from token
593
+ * Set access token in storage and emit event for MicroApps
594
+ * @param token - Access token to store
845
595
  */
846
- getUserEmail() {
847
- const user = this.tokenService.getUserFromToken();
848
- return user?.email || null;
596
+ setToken(token) {
597
+ setStorageItem(STORAGE_KEYS.ACCESS_TOKEN, token, STORAGE_CONFIG.TOKEN_STORAGE);
598
+ this.emitAuthEvent('token_updated', { token });
849
599
  }
850
- };
851
- exports.PermissionService = __decorate([
852
- core.Injectable({
853
- providedIn: 'root'
854
- })
855
- ], exports.PermissionService);
856
-
857
- /**
858
- * Factory function to create an auth guard with configuration
859
- *
860
- * @example
861
- * ```typescript
862
- * // In routes
863
- * {
864
- * path: 'dashboard',
865
- * component: DashboardComponent,
866
- * canActivate: [createAuthGuard({ redirectUrl: '/login' })]
867
- * }
868
- * ```
869
- */
870
- function createAuthGuard(config = {}) {
871
- return (route, state) => {
872
- const tokenService = core.inject(exports.TokenService);
873
- const router$1 = core.inject(router.Router);
874
- const redirectUrl = config.redirectUrl || '/login';
875
- const checkExpiration = config.checkExpiration !== false;
876
- const hasToken = tokenService.hasToken();
877
- const isExpired = checkExpiration ? tokenService.isTokenExpired() : false;
878
- if (hasToken && !isExpired) {
879
- return true;
880
- }
881
- // Store the attempted URL for redirecting after login
882
- const returnUrl = state.url;
883
- router$1.navigate([redirectUrl], {
884
- queryParams: { returnUrl },
885
- queryParamsHandling: 'merge'
886
- });
887
- return false;
888
- };
889
- }
890
- /**
891
- * Default auth guard - redirects to '/login' if not authenticated
892
- */
893
- const authGuard = createAuthGuard();
894
- /**
895
- * Permission-based guard factory
896
- * Checks if user has required permissions from token
897
- *
898
- * @example
899
- * ```typescript
900
- * {
901
- * path: 'admin',
902
- * component: AdminComponent,
903
- * canActivate: [createPermissionGuard(['admin', 'editor'])]
904
- * }
905
- * ```
906
- */
907
- function createPermissionGuard(requiredPermissions, config = {}) {
908
- return (route, state) => {
909
- const tokenService = core.inject(exports.TokenService);
910
- const router$1 = core.inject(router.Router);
911
- const redirectUrl = config.redirectUrl || '/unauthorized';
912
- // First check authentication
913
- if (!tokenService.isAuthenticated()) {
914
- router$1.navigate(['/login'], {
915
- queryParams: { returnUrl: state.url }
916
- });
917
- return false;
600
+ /**
601
+ * Check if user is authenticated
602
+ * @returns boolean - True if user has valid token
603
+ */
604
+ async isAuthenticated() {
605
+ try {
606
+ await this.ensureInitialized();
607
+ return await this.auth0Client.isAuthenticated();
918
608
  }
919
- // Check permissions
920
- const user = tokenService.getUserFromToken();
921
- const userPermissions = user?.permissions || user?.roles || [];
922
- const hasPermission = requiredPermissions.some(permission => userPermissions.includes(permission));
923
- if (!hasPermission) {
924
- router$1.navigate([redirectUrl]);
925
- return false;
609
+ catch (error) {
610
+ console.error('[AuthService] Error checking authentication status:', error);
611
+ // Fallback to checking storage
612
+ return !!getStorageItem(STORAGE_KEYS.ACCESS_TOKEN, STORAGE_CONFIG.TOKEN_STORAGE);
926
613
  }
927
- return true;
928
- };
929
- }
930
- /**
931
- * Role-based guard factory
932
- * Checks if user has required role from token
933
- *
934
- * @example
935
- * ```typescript
936
- * {
937
- * path: 'admin',
938
- * component: AdminComponent,
939
- * canActivate: [createRoleGuard(['admin'])]
940
- * }
941
- * ```
942
- */
943
- function createRoleGuard(requiredRoles, config = {}) {
944
- return createPermissionGuard(requiredRoles, config);
945
- }
946
-
947
- const defaultConfig$1 = {
948
- headerName: 'Authorization',
949
- tokenPrefix: 'Bearer',
950
- excludedUrls: []
951
- };
952
- let interceptorConfig = { ...defaultConfig$1 };
953
- /**
954
- * Configure the auth interceptor
955
- */
956
- function configureAuthInterceptor(config) {
957
- interceptorConfig = { ...defaultConfig$1, ...config };
958
- }
959
- /**
960
- * Auth Interceptor - Automatically adds authentication token to HTTP requests
961
- *
962
- * @example
963
- * ```typescript
964
- * // In app.config.ts
965
- * export const appConfig: ApplicationConfig = {
966
- * providers: [
967
- * provideHttpClient(
968
- * withInterceptors([authInterceptor])
969
- * )
970
- * ]
971
- * };
972
- * ```
973
- */
974
- const authInterceptor = (req, next) => {
975
- const tokenService = core.inject(exports.TokenService);
976
- const config = interceptorConfig;
977
- // Check if URL should be excluded
978
- const isExcluded = config.excludedUrls?.some(url => req.url.includes(url));
979
- if (isExcluded) {
980
- return next(req);
981
614
  }
982
- // Get token and add to request if available
983
- const token = tokenService.getToken();
984
- if (token) {
985
- const authReq = req.clone({
986
- setHeaders: {
987
- [config.headerName]: `${config.tokenPrefix} ${token}`
988
- }
989
- });
990
- return next(authReq);
615
+ /**
616
+ * Check if user is authenticated synchronously
617
+ * Only checks storage, doesn't verify with Auth0
618
+ * @returns boolean - True if user has token in storage
619
+ */
620
+ isAuthenticatedSync() {
621
+ return !!getStorageItem(STORAGE_KEYS.ACCESS_TOKEN, STORAGE_CONFIG.TOKEN_STORAGE);
991
622
  }
992
- return next(req);
993
- };
994
-
995
- const defaultConfig = {
996
- enableLogging: true,
997
- retryAttempts: 0,
998
- retryDelay: 1000,
999
- retryStatusCodes: [408, 429, 500, 502, 503, 504],
1000
- excludedUrls: []
1001
- };
1002
- let errorConfig = { ...defaultConfig };
1003
- /**
1004
- * Configure the error handling interceptor
1005
- */
1006
- function configureErrorHandling(config) {
1007
- errorConfig = { ...defaultConfig, ...config };
1008
- }
1009
- /**
1010
- * Error handling interceptor - Handles HTTP errors and retries
1011
- *
1012
- * @example
1013
- * ```typescript
1014
- * // In app.config.ts
1015
- * export const appConfig: ApplicationConfig = {
1016
- * providers: [
1017
- * provideHttpClient(
1018
- * withInterceptors([errorHandlingInterceptor])
1019
- * )
1020
- * ]
1021
- * };
1022
- *
1023
- * // Configure retry behavior
1024
- * configureErrorHandling({
1025
- * retryAttempts: 3,
1026
- * retryDelay: 2000,
1027
- * retryStatusCodes: [500, 502, 503]
1028
- * });
1029
- * ```
1030
- */
1031
- const errorHandlingInterceptor = (req, next) => {
1032
- const logger = core.inject(exports.LoggerService);
1033
- const config = errorConfig;
1034
- // Check if URL should be excluded
1035
- const isExcluded = config.excludedUrls?.some(url => req.url.includes(url));
1036
- if (isExcluded) {
1037
- return next(req);
623
+ /**
624
+ * Get current user information
625
+ * @returns UserInfo | null - Current user or null if not authenticated
626
+ */
627
+ getUser() {
628
+ return this.userSubject.value;
1038
629
  }
1039
- return next(req).pipe(
1040
- // Retry logic with exponential backoff
1041
- operators.retry({
1042
- count: config.retryAttempts,
1043
- delay: (error, retryCount) => {
1044
- // Only retry for specific status codes
1045
- if (!config.retryStatusCodes?.includes(error.status)) {
1046
- return rxjs.throwError(() => error);
1047
- }
1048
- const delay = config.retryDelay * Math.pow(2, retryCount - 1);
1049
- if (config.enableLogging) {
1050
- logger.warn(`Retrying request (attempt ${retryCount}) after ${delay}ms`, { url: req.url, status: error.status });
1051
- }
1052
- return rxjs.timer(delay);
1053
- }
1054
- }),
1055
- // Error handling
1056
- operators.catchError((error) => {
1057
- if (config.enableLogging) {
1058
- logger.error('HTTP request failed', error, {
1059
- url: req.url,
1060
- status: error.status,
1061
- message: error.message
1062
- });
630
+ /**
631
+ * Get simplified user data from token
632
+ * Extracts user details, role, and organization from ID token claims
633
+ * Checks both top-level claims and namespaced custom claims
634
+ * @returns UserData | null - Simplified user data or null if not authenticated
635
+ */
636
+ getUserData() {
637
+ const userInfo = this.getUser();
638
+ if (!userInfo) {
639
+ return null;
1063
640
  }
1064
- return rxjs.throwError(() => error);
1065
- }));
1066
- };
1067
- /**
1068
- * HTTP Error class with additional context
1069
- */
1070
- class HttpError extends Error {
1071
- status;
1072
- statusText;
1073
- url;
1074
- originalError;
1075
- constructor(status, statusText, url, originalError) {
1076
- super(`HTTP ${status} ${statusText}: ${url}`);
1077
- this.status = status;
1078
- this.statusText = statusText;
1079
- this.url = url;
1080
- this.originalError = originalError;
1081
- this.name = 'HttpError';
1082
- }
1083
- }
1084
- /**
1085
- * Parse HTTP error and return user-friendly message
1086
- */
1087
- function parseHttpError(error) {
1088
- if (error.error instanceof ErrorEvent) {
1089
- // Client-side error
1090
- return `Network error: ${error.error.message}`;
1091
- }
1092
- else {
1093
- // Server-side error
1094
- const errorMessage = error.error?.message || error.message || 'Unknown error';
1095
- return `Server error (${error.status}): ${errorMessage}`;
641
+ const role = this.extractClaimValue(userInfo, 'role', 'user');
642
+ const org = this.extractClaimValue(userInfo, ['org', 'organization'], 'default');
643
+ return {
644
+ id: userInfo.sub,
645
+ name: userInfo.name || userInfo.email || 'User',
646
+ email: userInfo.email || '',
647
+ role,
648
+ org
649
+ };
1096
650
  }
1097
- }
1098
- /**
1099
- * Check if error is a network error
1100
- */
1101
- function isNetworkError(error) {
1102
- return error.error instanceof ErrorEvent || error.status === 0;
1103
- }
1104
- /**
1105
- * Check if error is a server error (5xx)
1106
- */
1107
- function isServerError(error) {
1108
- return error.status >= 500 && error.status < 600;
1109
- }
1110
- /**
1111
- * Check if error is a client error (4xx)
1112
- */
1113
- function isClientError(error) {
1114
- return error.status >= 400 && error.status < 500;
1115
- }
1116
-
1117
- const defaultCacheConfig = {
1118
- enabled: true,
1119
- maxAge: 60000, // 1 minute
1120
- excludedUrls: [],
1121
- cacheableUrls: [],
1122
- cacheMethods: ['GET']
1123
- };
1124
- let cacheConfig = { ...defaultCacheConfig };
1125
- const cache = new Map();
1126
- const MAX_CACHE_SIZE = 100; // Maximum number of cached entries
1127
- /**
1128
- * Configure the caching interceptor
1129
- */
1130
- function configureCaching(config) {
1131
- cacheConfig = { ...defaultCacheConfig, ...config };
1132
- }
1133
- /**
1134
- * Clean up expired cache entries
1135
- */
1136
- function cleanupCache() {
1137
- const now = Date.now();
1138
- const keysToDelete = [];
1139
- cache.forEach((entry, key) => {
1140
- const age = now - entry.timestamp;
1141
- if (age >= cacheConfig.maxAge) {
1142
- keysToDelete.push(key);
651
+ /**
652
+ * Extract claim value from user info, checking both direct properties and namespaced custom claims
653
+ * @param userInfo - User info object
654
+ * @param claimNames - Single claim name or array of claim names to search for
655
+ * @param defaultValue - Default value if claim is not found
656
+ * @returns Extracted claim value or default value
657
+ */
658
+ extractClaimValue(userInfo, claimNames, defaultValue) {
659
+ const names = Array.isArray(claimNames) ? claimNames : [claimNames];
660
+ // Check direct properties first
661
+ for (const name of names) {
662
+ const directValue = userInfo[name];
663
+ if (directValue) {
664
+ return directValue;
665
+ }
1143
666
  }
1144
- });
1145
- keysToDelete.forEach(key => cache.delete(key));
1146
- }
1147
- /**
1148
- * Evict oldest cache entry if cache is full
1149
- */
1150
- function evictOldestIfFull() {
1151
- if (cache.size >= MAX_CACHE_SIZE) {
1152
- let oldestKey = null;
1153
- let oldestTimestamp = Infinity;
1154
- cache.forEach((entry, key) => {
1155
- if (entry.timestamp < oldestTimestamp) {
1156
- oldestTimestamp = entry.timestamp;
1157
- oldestKey = key;
667
+ // Check namespaced custom claims
668
+ const customClaims = this.getCustomClaims(userInfo);
669
+ for (const name of names) {
670
+ const matchingClaim = customClaims.find(claim => claim.toLowerCase().includes(name.toLowerCase()));
671
+ if (matchingClaim && userInfo[matchingClaim]) {
672
+ const value = userInfo[matchingClaim];
673
+ return Array.isArray(value) ? value[0] : value;
1158
674
  }
1159
- });
1160
- if (oldestKey) {
1161
- cache.delete(oldestKey);
1162
675
  }
676
+ return defaultValue;
1163
677
  }
1164
- }
1165
- /**
1166
- * Clear all cached entries
1167
- */
1168
- function clearCache() {
1169
- cache.clear();
1170
- }
1171
- /**
1172
- * Clear cache entry for specific URL
1173
- */
1174
- function clearCacheEntry(url) {
1175
- cache.delete(url);
1176
- }
1177
- /**
1178
- * Caching interceptor - Caches HTTP GET requests
1179
- *
1180
- * @example
1181
- * ```typescript
1182
- * // In app.config.ts
1183
- * export const appConfig: ApplicationConfig = {
1184
- * providers: [
1185
- * provideHttpClient(
1186
- * withInterceptors([cachingInterceptor])
1187
- * )
1188
- * ]
1189
- * };
1190
- *
1191
- * // Configure caching
1192
- * configureCaching({
1193
- * enabled: true,
1194
- * maxAge: 300000, // 5 minutes
1195
- * cacheableUrls: ['/api/users', '/api/products']
1196
- * });
1197
- * ```
1198
- */
1199
- const cachingInterceptor = (req, next) => {
1200
- const logger = core.inject(exports.LoggerService);
1201
- const config = cacheConfig;
1202
- // Only cache if enabled
1203
- if (!config.enabled) {
1204
- return next(req);
1205
- }
1206
- // Only cache specific methods (default: GET)
1207
- if (!config.cacheMethods?.includes(req.method)) {
1208
- return next(req);
1209
- }
1210
- // Check if URL should be excluded
1211
- const isExcluded = config.excludedUrls?.some(url => req.url.includes(url));
1212
- if (isExcluded) {
1213
- return next(req);
1214
- }
1215
- // Check if URL is explicitly cacheable (if list is provided)
1216
- if (config.cacheableUrls && config.cacheableUrls.length > 0) {
1217
- const isCacheable = config.cacheableUrls.some(url => req.url.includes(url));
1218
- if (!isCacheable) {
1219
- return next(req);
1220
- }
678
+ /**
679
+ * Get user information from storage
680
+ * @returns UserInfo | null - Stored user info or null
681
+ */
682
+ getUserInfoFromStorage() {
683
+ const userJson = getStorageItem(STORAGE_KEYS.USER_INFO, STORAGE_CONFIG.USER_INFO_STORAGE);
684
+ return userJson ? JSON.parse(userJson) : null;
1221
685
  }
1222
- const cacheKey = req.urlWithParams;
1223
- // Check cache
1224
- const cached = cache.get(cacheKey);
1225
- if (cached) {
1226
- const age = Date.now() - cached.timestamp;
1227
- if (age < config.maxAge) {
1228
- logger.debug(`Cache hit for ${cacheKey}`, { age });
1229
- return new rxjs.Observable(observer => {
1230
- observer.next(cached.response.clone());
1231
- observer.complete();
686
+ /**
687
+ * Set user information in storage, update observable and emit event for MicroApps
688
+ * Logs all Auth0 claims for debugging
689
+ * @param userInfo - User information to store
690
+ */
691
+ setUserInfo(userInfo) {
692
+ setStorageItem(STORAGE_KEYS.USER_INFO, JSON.stringify(userInfo), STORAGE_CONFIG.USER_INFO_STORAGE);
693
+ this.userSubject.next(userInfo);
694
+ // Log stored user info with all claims
695
+ console.log('[AuthService] 💾 User info stored in sessionStorage:');
696
+ console.log(' Standard claims:', {
697
+ sub: userInfo.sub,
698
+ name: userInfo.name,
699
+ email: userInfo.email,
700
+ email_verified: userInfo.email_verified
701
+ });
702
+ // Log Auth0 custom claims if present (namespaced with http:// or https://)
703
+ const customClaims = this.getCustomClaims(userInfo);
704
+ if (customClaims.length > 0) {
705
+ console.log(' Custom claims stored:');
706
+ customClaims.forEach(claim => {
707
+ console.log(` • ${claim}:`, userInfo[claim]);
1232
708
  });
1233
709
  }
1234
- else {
1235
- // Cache expired
1236
- cache.delete(cacheKey);
1237
- }
710
+ this.emitAuthEvent('user_info_updated', userInfo);
1238
711
  }
1239
- // Clean up expired entries periodically
1240
- if (Math.random() < 0.1) { // 10% chance on each request
1241
- cleanupCache();
712
+ /**
713
+ * Emit authentication event for MicroApps to consume
714
+ * Events are emitted via EventBus for cross-MFE communication
715
+ * @param eventType - Type of authentication event
716
+ * @param payload - Event payload
717
+ */
718
+ emitAuthEvent(eventType, payload) {
719
+ const event = {
720
+ type: `auth:${eventType}`,
721
+ payload,
722
+ timestamp: new Date().toISOString()
723
+ };
724
+ this.eventBus.sendEvent(JSON.stringify(event));
725
+ console.log('[AuthService] Auth event emitted:', event.type);
1242
726
  }
1243
- // Make request and cache response
1244
- return next(req).pipe(operators.tap(event => {
1245
- if (event instanceof http.HttpResponse) {
1246
- evictOldestIfFull();
1247
- cache.set(cacheKey, {
1248
- response: event.clone(),
1249
- timestamp: Date.now()
1250
- });
1251
- logger.debug(`Cached response for ${cacheKey}`);
1252
- }
1253
- }));
1254
727
  };
728
+ exports.AuthService = __decorate([
729
+ core.Injectable({
730
+ providedIn: 'root'
731
+ }),
732
+ __metadata("design:paramtypes", [http.HttpClient,
733
+ exports.EventBusService])
734
+ ], exports.AuthService);
1255
735
 
736
+ exports.AUTH0_CONFIG = AUTH0_CONFIG;
1256
737
  exports.EventBus = EventBus;
1257
- exports.HttpError = HttpError;
1258
- exports.Logger = Logger;
1259
- exports.StorageManager = StorageManager;
1260
- exports.TokenManager = TokenManager;
1261
- exports.authGuard = authGuard;
1262
- exports.authInterceptor = authInterceptor;
1263
- exports.cachingInterceptor = cachingInterceptor;
1264
- exports.clearCache = clearCache;
1265
- exports.clearCacheEntry = clearCacheEntry;
1266
- exports.configureAuthInterceptor = configureAuthInterceptor;
1267
- exports.configureCaching = configureCaching;
1268
- exports.configureErrorHandling = configureErrorHandling;
1269
- exports.createAuthGuard = createAuthGuard;
1270
- exports.createPermissionGuard = createPermissionGuard;
1271
- exports.createRoleGuard = createRoleGuard;
1272
- exports.errorHandlingInterceptor = errorHandlingInterceptor;
1273
- exports.isClientError = isClientError;
1274
- exports.isNetworkError = isNetworkError;
1275
- exports.isServerError = isServerError;
1276
- exports.parseHttpError = parseHttpError;
738
+ exports.STORAGE_CONFIG = STORAGE_CONFIG;
739
+ exports.STORAGE_KEYS = STORAGE_KEYS;
740
+ exports.configureAuth0 = configureAuth0;
741
+ exports.getStorageItem = getStorageItem;
742
+ exports.removeStorageItem = removeStorageItem;
743
+ exports.setStorageItem = setStorageItem;
1277
744
  //# sourceMappingURL=index.cjs.map