wangzhibo
2026-05-09 53418655c061ac26f66058253f39200aced1ab1d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
/*! @azure/msal-browser v5.7.0 2026-04-16 */
'use strict';
import { CryptoOps } from '../crypto/CryptoOps.mjs';
import { DEFAULT_CRYPTO_IMPLEMENTATION, buildStaticAuthorityOptions, invokeAsync, enforceResourceParameter, InteractionRequiredAuthError, createClientAuthError, ClientAuthErrorCodes, AccountEntityUtils, AuthToken, Constants, AuthError, getRequestThumbprint, InteractionRequiredAuthErrorCodes } from '@azure/msal-common/browser';
import { InitializeCache, HandleNativeRedirectPromiseMeasurement, HandleRedirectPromiseMeasurement, NativeInteractionClientAcquireTokenRedirect, AcquireTokenByCodeAsync, SilentCacheClientAcquireToken, SilentRefreshClientAcquireToken, SilentIframeClientAcquireToken, NativeInteractionClientAcquireToken, AcquireTokenSilentAsync, InitializeSilentRequest, AcquireTokenBySilentIframe, AwaitConcurrentIframe, AcquireTokenFromCache, AcquireTokenByRefreshToken, GeneratePkceCodes } from '../telemetry/BrowserPerformanceEvents.mjs';
import { InitializeClientApplication, AcquireTokenRedirect, AcquireTokenPreRedirect, AcquireTokenPopup, SsoCapable, SsoSilent, AcquireTokenByCode, AcquireTokenSilent } from '../telemetry/BrowserRootPerformanceEvents.mjs';
import { BrowserCacheManager, DEFAULT_BROWSER_CACHE_MANAGER } from '../cache/BrowserCacheManager.mjs';
import { SSO_CAPABLE } from '../cache/CacheKeys.mjs';
import { getAllAccounts, getAccount, setActiveAccount, getActiveAccount } from '../cache/AccountManager.mjs';
import { BrowserCacheLocation, INTERACTION_TYPE, InteractionType, ApiId, CacheLookupPolicy, DEFAULT_REQUEST, iFrameRenewalPolicies, BrowserConstants } from '../utils/BrowserConstants.mjs';
import { blockAPICallsBeforeInitialize, redirectPreflightCheck, preflightCheck as preflightCheck$1, blockNonBrowserEnvironment } from '../utils/BrowserUtils.mjs';
import { EventType } from '../event/EventType.mjs';
import { EventHandler } from '../event/EventHandler.mjs';
import { PopupClient } from '../interaction_client/PopupClient.mjs';
import { RedirectClient } from '../interaction_client/RedirectClient.mjs';
import { SilentIframeClient } from '../interaction_client/SilentIframeClient.mjs';
import { SilentRefreshClient } from '../interaction_client/SilentRefreshClient.mjs';
import { PlatformAuthInteractionClient } from '../interaction_client/PlatformAuthInteractionClient.mjs';
import { NativeAuthError, isFatalNativeAuthError } from '../error/NativeAuthError.mjs';
import { SilentCacheClient } from '../interaction_client/SilentCacheClient.mjs';
import { SilentAuthCodeClient } from '../interaction_client/SilentAuthCodeClient.mjs';
import { createBrowserAuthError } from '../error/BrowserAuthError.mjs';
import { createNewGuid } from '../crypto/BrowserCrypto.mjs';
import { initializeSilentRequest } from '../request/RequestHelpers.mjs';
import { generatePkceCodes } from '../crypto/PkceGenerator.mjs';
import { getPlatformAuthProvider, isPlatformAuthAllowed } from '../broker/nativeBroker/PlatformAuthProvider.mjs';
import { collectInstanceStats } from '../utils/MsalFrameStatsUtils.mjs';
import { spaCodeAndNativeAccountIdPresent, unableToAcquireTokenFromNativePlatform, authCodeOrNativeAccountIdRequired, nativeConnectionNotEstablished, noAccountError } from '../error/BrowserAuthErrorCodes.mjs';
 
/*
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License.
 */
function preflightCheck(initialized, performanceEvent, config, request) {
    try {
        preflightCheck$1(initialized);
        enforceResourceParameter(config.auth.isMcp, request);
    }
    catch (e) {
        performanceEvent.end({ success: false }, e, request.account);
        throw e;
    }
}
class StandardController {
    /**
     * @constructor
     * Constructor for the PublicClientApplication used to instantiate the PublicClientApplication object
     *
     * Important attributes in the Configuration object for auth are:
     * - clientID: the application ID of your application. You can obtain one by registering your application with our Application registration portal : https://portal.azure.com/#blade/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/RegisteredAppsPreview
     * - authority: the authority URL for your application.
     * - redirect_uri: the uri of your application registered in the portal.
     *
     * In Azure AD, authority is a URL indicating the Azure active directory that MSAL uses to obtain tokens.
     * It is of the form https://login.microsoftonline.com/{Enter_the_Tenant_Info_Here}
     * If your application supports Accounts in one organizational directory, replace "Enter_the_Tenant_Info_Here" value with the Tenant Id or Tenant name (for example, contoso.microsoft.com).
     * If your application supports Accounts in any organizational directory, replace "Enter_the_Tenant_Info_Here" value with organizations.
     * If your application supports Accounts in any organizational directory and personal Microsoft accounts, replace "Enter_the_Tenant_Info_Here" value with common.
     * To restrict support to Personal Microsoft accounts only, replace "Enter_the_Tenant_Info_Here" value with consumers.
     *
     * In Azure B2C, authority is of the form https://{instance}/tfp/{tenant}/{policyName}/
     * Full B2C functionality will be available in this library in future versions.
     *
     * @param configuration Object for the MSAL PublicClientApplication instance
     */
    constructor(operatingContext) {
        this.operatingContext = operatingContext;
        this.isBrowserEnvironment =
            this.operatingContext.isBrowserEnvironment();
        // Set the configuration.
        this.config = operatingContext.getConfig();
        this.initialized = false;
        // Initialize logger
        this.logger = this.operatingContext.getLogger();
        // Initialize the network module class.
        this.networkClient = this.config.system.networkClient;
        // Initialize the navigation client class.
        this.navigationClient = this.config.system.navigationClient;
        // Initialize redirectResponse Map
        this.redirectResponse = new Map();
        // Initial hybrid spa map
        this.hybridAuthCodeResponses = new Map();
        // Initialize performance client
        this.performanceClient = this.config.telemetry.client;
        // Initialize the crypto class.
        this.browserCrypto = this.isBrowserEnvironment
            ? new CryptoOps(this.logger, this.performanceClient)
            : DEFAULT_CRYPTO_IMPLEMENTATION;
        this.eventHandler = new EventHandler(this.logger);
        // Initialize the browser storage class.
        this.browserStorage = this.isBrowserEnvironment
            ? new BrowserCacheManager(this.config.auth.clientId, this.config.cache, this.browserCrypto, this.logger, this.performanceClient, this.eventHandler, buildStaticAuthorityOptions(this.config.auth))
            : DEFAULT_BROWSER_CACHE_MANAGER(this.config.auth.clientId, this.logger, this.performanceClient, this.eventHandler);
        // initialize in memory storage for native flows
        const nativeCacheOptions = {
            cacheLocation: BrowserCacheLocation.MemoryStorage,
            cacheRetentionDays: 5,
        };
        this.nativeInternalStorage = new BrowserCacheManager(this.config.auth.clientId, nativeCacheOptions, this.browserCrypto, this.logger, this.performanceClient, this.eventHandler);
        this.activeSilentTokenRequests = new Map();
        // Register listener functions
        this.trackStateChange = this.trackStateChange.bind(this);
        // Register listener functions
        this.trackStateChangeWithMeasurement =
            this.trackStateChangeWithMeasurement.bind(this);
    }
    static async createController(operatingContext, request) {
        const controller = new StandardController(operatingContext);
        await controller.initialize(request);
        return controller;
    }
    trackStateChange(correlationId, event) {
        if (!correlationId) {
            return;
        }
        if (event.type === "visibilitychange") {
            this.logger.info("16v6hv", correlationId);
            this.performanceClient.incrementFields({ visibilityChangeCount: 1 }, correlationId);
        }
        else if (event.type === "online") {
            this.logger.info("0zirfd", correlationId);
            this.performanceClient.incrementFields({ onlineStatusChangeCount: 1 }, correlationId);
        }
        else if (event.type === "offline") {
            this.logger.info("1xk9ef", correlationId);
            this.performanceClient.incrementFields({ onlineStatusChangeCount: 1 }, correlationId);
        }
    }
    /**
     * Initializer function to perform async startup tasks such as connecting to WAM extension
     * @param request {?InitializeApplicationRequest} correlation id
     */
    async initialize(request) {
        const correlationId = this.getRequestCorrelationId(request);
        this.logger.trace("1f7joy", correlationId);
        if (this.initialized) {
            this.logger.info("061m5x", correlationId);
            return;
        }
        if (!this.isBrowserEnvironment) {
            this.logger.info("19fvpi", correlationId);
            this.initialized = true;
            this.eventHandler.emitEvent(EventType.INITIALIZE_END, correlationId);
            return;
        }
        const allowPlatformBroker = this.config.system.allowPlatformBroker;
        const initMeasurement = this.performanceClient.startMeasurement(InitializeClientApplication, correlationId);
        this.eventHandler.emitEvent(EventType.INITIALIZE_START, correlationId);
        // Broker applications are initialized twice, so we avoid double-counting it
        this.logMultipleInstances(initMeasurement, correlationId);
        initMeasurement.add({ isMcp: this.config.auth.isMcp });
        await invokeAsync(this.browserStorage.initialize.bind(this.browserStorage), InitializeCache, this.logger, this.performanceClient, correlationId)(correlationId);
        if (allowPlatformBroker) {
            try {
                // check if platform authentication is available via DOM or browser extension and create relevant handlers
                this.platformAuthProvider = await getPlatformAuthProvider(this.logger, this.performanceClient, correlationId, this.config.system.nativeBrokerHandshakeTimeout);
            }
            catch (e) {
                this.logger.verbose(e, correlationId);
            }
        }
        if (this.config.cache.cacheLocation ===
            BrowserCacheLocation.LocalStorage) {
            this.eventHandler.subscribeCrossTab();
        }
        !this.config.system.navigatePopups &&
            (await this.preGeneratePkceCodes(correlationId));
        this.initialized = true;
        this.eventHandler.emitEvent(EventType.INITIALIZE_END, correlationId);
        initMeasurement.end({
            allowPlatformBroker: allowPlatformBroker,
            success: true,
        });
    }
    // #region Redirect Flow
    /**
     * Event handler function which allows users to fire events after the PublicClientApplication object
     * has loaded during redirect flows. This should be invoked on all page loads involved in redirect
     * auth flows.
     * @param hash Hash to process. Defaults to the current value of window.location.hash. Only needs to be provided explicitly if the response to be handled is not contained in the current value.
     * @param options Object containing optional configuration for redirect promise handling.
     * @returns Token response or null. If the return value is null, then no auth redirect was detected.
     */
    async handleRedirectPromise(options) {
        this.logger.verbose("02l8bm", "");
        // Block token acquisition before initialize has been called
        blockAPICallsBeforeInitialize(this.initialized);
        if (this.isBrowserEnvironment) {
            /**
             * Store the promise on the PublicClientApplication instance if this is the first invocation of handleRedirectPromise,
             * otherwise return the promise from the first invocation. Prevents race conditions when handleRedirectPromise is called
             * several times concurrently.
             */
            const redirectResponseKey = options?.hash || "";
            let response = this.redirectResponse.get(redirectResponseKey);
            if (typeof response === "undefined") {
                response = this.handleRedirectPromiseInternal(options);
                this.redirectResponse.set(redirectResponseKey, response);
                this.logger.verbose("1wn9kp", "");
            }
            else {
                this.logger.verbose("0w0gm3", "");
            }
            return response;
        }
        this.logger.verbose("12xi63", "");
        return null;
    }
    /**
     * The internal details of handleRedirectPromise. This is separated out to a helper to allow handleRedirectPromise to memoize requests
     * @param hash
     * @returns
     */
    async handleRedirectPromiseInternal(options) {
        if (!this.browserStorage.isInteractionInProgress(true)) {
            this.logger.info("0le6uv", "");
            return null;
        }
        const interactionType = this.browserStorage.getInteractionInProgress()?.type;
        if (interactionType === INTERACTION_TYPE.SIGNOUT) {
            this.logger.verbose("1ywcv2", "");
            this.browserStorage.setInteractionInProgress(false);
            return Promise.resolve(null);
        }
        const loggedInAccounts = this.getAllAccounts();
        const platformBrokerRequest = this.browserStorage.getCachedNativeRequest();
        const useNative = platformBrokerRequest && !options?.hash;
        let rootMeasurement;
        let redirectResponse;
        let cachedRedirectRequest;
        try {
            if (useNative && this.platformAuthProvider) {
                const correlationId = platformBrokerRequest?.correlationId || "";
                this.eventHandler.emitEvent(EventType.HANDLE_REDIRECT_START, correlationId, InteractionType.Redirect);
                rootMeasurement = this.performanceClient.startMeasurement(AcquireTokenRedirect, correlationId);
                this.logger.trace("12v7is", correlationId);
                rootMeasurement.add({
                    isPlatformBrokerRequest: true,
                });
                const nativeClient = new PlatformAuthInteractionClient(this.config, this.browserStorage, this.browserCrypto, this.logger, this.eventHandler, this.navigationClient, ApiId.handleRedirectPromise, this.performanceClient, this.platformAuthProvider, platformBrokerRequest.accountId, this.nativeInternalStorage, platformBrokerRequest.correlationId);
                redirectResponse = invokeAsync(nativeClient.handleRedirectPromise.bind(nativeClient), HandleNativeRedirectPromiseMeasurement, this.logger, this.performanceClient, rootMeasurement.event.correlationId)();
            }
            else {
                const [standardRequest, codeVerifier] = this.browserStorage.getCachedRequest("");
                cachedRedirectRequest = standardRequest;
                const correlationId = standardRequest.correlationId;
                this.eventHandler.emitEvent(EventType.HANDLE_REDIRECT_START, correlationId, InteractionType.Redirect);
                // Reset rootMeasurement now that we have correlationId
                rootMeasurement = this.performanceClient.startMeasurement(AcquireTokenRedirect, correlationId);
                this.logger.trace("0znzs5", correlationId);
                const redirectClient = this.createRedirectClient(correlationId);
                redirectResponse = invokeAsync(redirectClient.handleRedirectPromise.bind(redirectClient), HandleRedirectPromiseMeasurement, this.logger, this.performanceClient, rootMeasurement.event.correlationId)(standardRequest, codeVerifier, rootMeasurement, options);
            }
        }
        catch (e) {
            this.browserStorage.resetRequestCache("");
            throw e;
        }
        return redirectResponse
            .then((result) => {
            if (result) {
                this.browserStorage.resetRequestCache(result.correlationId);
                this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_SUCCESS, result.correlationId, InteractionType.Redirect, result);
                this.logger.verbose("0ui8f5", result.correlationId);
                // Emit login event if number of accounts change
                const isLoggingIn = loggedInAccounts.length < this.getAllAccounts().length;
                if (isLoggingIn) {
                    this.eventHandler.emitEvent(EventType.LOGIN_SUCCESS, result.correlationId, InteractionType.Redirect, result.account);
                    this.logger.verbose("16im3l", result.correlationId);
                }
                rootMeasurement.end({
                    success: true,
                }, undefined, result.account);
                // Fire-and-forget SSO capability verification in background
                this.verifySsoCapability(cachedRedirectRequest, InteractionType.Redirect);
            }
            else {
                /*
                 * Instrument an event only if an error code is set. Otherwise, discard it when the redirect response
                 * is empty and the error code is missing.
                 */
                if (rootMeasurement.event.errorCode) {
                    rootMeasurement.end({ success: false }, undefined);
                }
                else {
                    rootMeasurement.discard();
                }
            }
            this.eventHandler.emitEvent(EventType.HANDLE_REDIRECT_END, rootMeasurement.event.correlationId, InteractionType.Redirect);
            return result;
        })
            .catch((e) => {
            this.browserStorage.resetRequestCache(rootMeasurement.event.correlationId);
            const eventError = e;
            this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_FAILURE, rootMeasurement.event.correlationId, InteractionType.Redirect, null, eventError);
            this.eventHandler.emitEvent(EventType.HANDLE_REDIRECT_END, rootMeasurement.event.correlationId, InteractionType.Redirect);
            rootMeasurement.end({
                success: false,
            }, eventError);
            throw e;
        });
    }
    /**
     * Use when you want to obtain an access_token for your API by redirecting the user's browser window to the authorization endpoint. This function redirects
     * the page, so any code that follows this function will not execute.
     *
     * IMPORTANT: It is NOT recommended to have code that is dependent on the resolution of the Promise. This function will navigate away from the current
     * browser window. It currently returns a Promise in order to reflect the asynchronous nature of the code running in this function.
     *
     * @param request
     */
    async acquireTokenRedirect(request) {
        // Preflight request
        const correlationId = this.getRequestCorrelationId(request);
        this.logger.verbose("0os66p", correlationId);
        const atrMeasurement = this.performanceClient.startMeasurement(AcquireTokenPreRedirect, correlationId);
        atrMeasurement.add({
            scenarioId: request.scenarioId,
        });
        const configOnRedirectNavigateCb = this.config.auth.onRedirectNavigate;
        this.config.auth.onRedirectNavigate = (url) => {
            const navigate = typeof configOnRedirectNavigateCb === "function"
                ? configOnRedirectNavigateCb(url)
                : undefined;
            atrMeasurement.add({
                navigateCallbackResult: navigate !== false,
            });
            atrMeasurement.event =
                atrMeasurement.end({ success: true }, undefined, request.account) || atrMeasurement.event;
            return navigate;
        };
        try {
            redirectPreflightCheck(this.initialized, this.config);
            enforceResourceParameter(this.config.auth.isMcp, request);
            this.browserStorage.setInteractionInProgress(true, INTERACTION_TYPE.SIGNIN);
            this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_START, correlationId, InteractionType.Redirect, request);
            let result;
            if (this.platformAuthProvider &&
                this.canUsePlatformBroker(request)) {
                const nativeClient = new PlatformAuthInteractionClient(this.config, this.browserStorage, this.browserCrypto, this.logger, this.eventHandler, this.navigationClient, ApiId.acquireTokenRedirect, this.performanceClient, this.platformAuthProvider, this.getNativeAccountId(request), this.nativeInternalStorage, correlationId);
                result = invokeAsync(nativeClient.acquireTokenRedirect.bind(nativeClient), NativeInteractionClientAcquireTokenRedirect, this.logger, this.performanceClient, correlationId)(request, atrMeasurement).catch((e) => {
                    atrMeasurement.add({
                        brokerErrorName: e.name,
                        brokerErrorCode: e.errorCode,
                    });
                    if (e instanceof NativeAuthError &&
                        isFatalNativeAuthError(e)) {
                        this.platformAuthProvider = undefined; // If extension gets uninstalled during session prevent future requests from continuing to attempt platform broker calls
                        const redirectClient = this.createRedirectClient(correlationId);
                        return redirectClient.acquireToken(request);
                    }
                    else if (e instanceof InteractionRequiredAuthError) {
                        this.logger.verbose("1ipyz4", correlationId);
                        const redirectClient = this.createRedirectClient(correlationId);
                        return redirectClient.acquireToken(request);
                    }
                    throw e;
                });
            }
            else {
                const redirectClient = this.createRedirectClient(correlationId);
                result = redirectClient.acquireToken(request);
            }
            return await result;
        }
        catch (e) {
            this.browserStorage.resetRequestCache(correlationId);
            /*
             * Pre-redirect event completes before navigation occurs.
             * Timed out navigation needs to be instrumented separately as a post-redirect event.
             */
            if (atrMeasurement.event.status === 2) {
                this.performanceClient
                    .startMeasurement(AcquireTokenRedirect, correlationId)
                    .end({ success: false }, e, request.account);
            }
            else {
                atrMeasurement.end({ success: false }, e, request.account);
            }
            this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_FAILURE, correlationId, InteractionType.Redirect, null, e);
            throw e;
        }
    }
    // #endregion
    // #region Popup Flow
    /**
     * Use when you want to obtain an access_token for your API via opening a popup window in the user's browser
     *
     * @param request
     *
     * @returns A promise that is fulfilled when this function has completed, or rejected if an error was raised.
     */
    acquireTokenPopup(request) {
        const correlationId = this.getRequestCorrelationId(request);
        const atPopupMeasurement = this.performanceClient.startMeasurement(AcquireTokenPopup, correlationId);
        atPopupMeasurement.add({
            scenarioId: request.scenarioId,
        });
        try {
            this.logger.verbose("0ch87b", correlationId);
            preflightCheck(this.initialized, atPopupMeasurement, this.config, request);
            this.browserStorage.setInteractionInProgress(true, INTERACTION_TYPE.SIGNIN, request.overrideInteractionInProgress, correlationId);
        }
        catch (e) {
            // Since this function is syncronous we need to reject
            return Promise.reject(e);
        }
        // If logged in, emit acquire token events
        const loggedInAccounts = this.getAllAccounts();
        this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_START, correlationId, InteractionType.Popup, request);
        let result;
        const pkce = this.getPreGeneratedPkceCodes(correlationId);
        if (this.canUsePlatformBroker(request)) {
            atPopupMeasurement.add({
                isPlatformBrokerRequest: true,
            });
            result = this.acquireTokenNative({
                ...request,
                correlationId,
            }, ApiId.acquireTokenPopup)
                .then((response) => {
                atPopupMeasurement.end({
                    success: true,
                    isNativeBroker: true,
                }, undefined, response.account);
                return response;
            })
                .catch((e) => {
                atPopupMeasurement.add({
                    brokerErrorName: e.name,
                    brokerErrorCode: e.errorCode,
                });
                if (e instanceof NativeAuthError &&
                    isFatalNativeAuthError(e)) {
                    this.platformAuthProvider = undefined; // If extension gets uninstalled during session prevent future requests from continuing to attempt platform broker calls
                    const popupClient = this.createPopupClient(correlationId);
                    return popupClient.acquireToken(request, pkce);
                }
                else if (e instanceof InteractionRequiredAuthError) {
                    this.logger.verbose("0yy5fw", correlationId);
                    const popupClient = this.createPopupClient(correlationId);
                    return popupClient.acquireToken(request, pkce);
                }
                throw e;
            });
        }
        else {
            const popupClient = this.createPopupClient(correlationId);
            result = popupClient.acquireToken(request, pkce);
        }
        return result
            .then((result) => {
            /*
             *  If logged in, emit acquire token events
             */
            const isLoggingIn = loggedInAccounts.length < this.getAllAccounts().length;
            this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_SUCCESS, correlationId, InteractionType.Popup, result);
            if (isLoggingIn) {
                this.eventHandler.emitEvent(EventType.LOGIN_SUCCESS, correlationId, InteractionType.Popup, result.account);
            }
            atPopupMeasurement.end({
                success: true,
                accessTokenSize: result.accessToken.length,
                idTokenSize: result.idToken.length,
            }, undefined, result.account);
            // SSO capability verification in background
            this.verifySsoCapability(request, InteractionType.Popup);
            return result;
        })
            .catch((e) => {
            this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_FAILURE, correlationId, InteractionType.Popup, null, e);
            atPopupMeasurement.end({
                success: false,
            }, e, request.account);
            // Since this function is syncronous we need to reject
            return Promise.reject(e);
        })
            .finally(async () => {
            this.browserStorage.setInteractionInProgress(false);
            if (!this.config.system.navigatePopups) {
                await this.preGeneratePkceCodes(correlationId);
            }
        });
    }
    trackStateChangeWithMeasurement(event) {
        const measurement = this.ssoSilentMeasurement ||
            this.acquireTokenByCodeAsyncMeasurement;
        if (!measurement) {
            return;
        }
        if (event.type === "visibilitychange") {
            this.logger.info("0yzimq", measurement.event.correlationId);
            measurement.increment({
                visibilityChangeCount: 1,
            });
        }
        else if (event.type === "online") {
            this.logger.info("1caf53", measurement.event.correlationId);
            measurement.increment({
                onlineStatusChangeCount: 1,
            });
        }
        else if (event.type === "offline") {
            this.logger.info("0fdyk7", measurement.event.correlationId);
            measurement.increment({
                onlineStatusChangeCount: 1,
            });
        }
    }
    addStateChangeListeners(listener) {
        document.addEventListener("visibilitychange", listener);
        window.addEventListener("online", listener);
        window.addEventListener("offline", listener);
    }
    removeStateChangeListeners(listener) {
        document.removeEventListener("visibilitychange", listener);
        window.removeEventListener("online", listener);
        window.removeEventListener("offline", listener);
    }
    /**
     * Reads the cached ssoCapable value from localStorage.
     * @returns The cached ssoCapable boolean value, or undefined if not cached or expired.
     */
    getCachedSsoCapable() {
        try {
            const cachedValue = window.localStorage.getItem(SSO_CAPABLE);
            if (cachedValue) {
                const parsed = JSON.parse(cachedValue);
                if (parsed &&
                    typeof parsed.ssoCapable === "boolean" &&
                    parsed.expiresOn &&
                    Date.now() < parsed.expiresOn) {
                    return parsed.ssoCapable;
                }
            }
        }
        catch {
            // If parsing fails, return undefined
        }
        return undefined;
    }
    /**
     * SSO capability verification in the background.
     * This method makes an iframe request to /authorize to verify SSO capability without calling /token.
     * This method does not block the caller and tracks telemetry for success/failure.
     * This method only executes if verifySSO is set to true in the auth configuration.
     * The result is cached in localStorage with a 24-hour TTL; the SSO verification call
     * is only attempted when the cached value is absent or expired.
     * @param request - The original request used for the authentication flow
     * @param interactionType - The interactionType of the AT operation for logging purposes
     */
    verifySsoCapability(request, interactionType) {
        // Check if SSO capability verification is enabled
        if (!this.config.auth.verifySSO) {
            return;
        }
        // Check TTL: derive ssoCapable state from localStorage and skip if not expired
        const ssoCacheKey = SSO_CAPABLE;
        const SSO_CAPABLE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
        const cachedSsoCapable = this.getCachedSsoCapable();
        if (cachedSsoCapable !== undefined) {
            this.logger.verbose("13poou", "");
            return;
        }
        const correlationId = createNewGuid();
        const ssoCapableMeasurement = this.performanceClient.startMeasurement(SsoCapable, correlationId);
        ssoCapableMeasurement.add({
            "ext.interactionType": interactionType,
        });
        this.logger.verbose("0pbr0i", correlationId);
        /*
         * Use setTimeout to ensure this runs in a separate macrotask after the current call stack completes
         * This ensures the result is returned to the caller before the SSO verification starts and doesn't affect performance
         */
        setTimeout(() => {
            const ssoVerificationRequest = {
                ...request,
                correlationId: correlationId,
            };
            const silentIframeClient = this.createSilentIframeClient(correlationId);
            silentIframeClient
                .verifySso(ssoVerificationRequest)
                .then((result) => {
                this.logger.verbose("1gd1iv", correlationId);
                // TBD to add profileTelemetry later in localStorage with 24h TTL
                try {
                    const cacheEntry = JSON.stringify({
                        ssoCapable: result,
                        expiresOn: Date.now() + SSO_CAPABLE_TTL_MS,
                    });
                    window.localStorage.setItem(ssoCacheKey, cacheEntry);
                }
                catch {
                    this.logger.warning("18lmoj", correlationId);
                }
                ssoCapableMeasurement.end({
                    fromCache: false,
                    success: result,
                }, undefined);
            })
                .catch((error) => {
                this.logger.warning("05g83w", correlationId);
                // reset the cache
                try {
                    window.localStorage.removeItem(ssoCacheKey);
                }
                catch {
                    this.logger.warning("0nlf9q", correlationId);
                }
                ssoCapableMeasurement.end({
                    fromCache: false,
                    success: false,
                }, error);
            });
        }, 0);
    }
    // #endregion
    // #region Silent Flow
    /**
     * This function uses a hidden iframe to fetch an authorization code from the eSTS. There are cases where this may not work:
     * - Any browser using a form of Intelligent Tracking Prevention
     * - If there is not an established session with the service
     *
     * In these cases, the request must be done inside a popup or full frame redirect.
     *
     * For the cases where interaction is required, you cannot send a request with prompt=none.
     *
     * If your refresh token has expired, you can use this function to fetch a new set of tokens silently as long as
     * you session on the server still exists.
     * @param request {@link SsoSilentRequest}
     *
     * @returns A promise that is fulfilled when this function has completed, or rejected if an error was raised.
     */
    async ssoSilent(request) {
        const correlationId = this.getRequestCorrelationId(request);
        const validRequest = {
            ...request,
            correlationId: correlationId,
        };
        this.ssoSilentMeasurement = this.performanceClient.startMeasurement(SsoSilent, correlationId);
        this.ssoSilentMeasurement?.add({
            scenarioId: request.scenarioId,
            ssoCapable: this.getCachedSsoCapable(),
        });
        preflightCheck(this.initialized, this.ssoSilentMeasurement, this.config, validRequest);
        this.ssoSilentMeasurement?.increment({
            visibilityChangeCount: 0,
            onlineStatusChangeCount: 0,
        });
        this.addStateChangeListeners(this.trackStateChangeWithMeasurement);
        const loggedInAccounts = this.getAllAccounts();
        this.logger.verbose("0w1b45", correlationId);
        this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_START, correlationId, InteractionType.Silent, validRequest);
        let result;
        if (this.canUsePlatformBroker(validRequest)) {
            this.ssoSilentMeasurement?.add({
                isPlatformBrokerRequest: true,
            });
            result = this.acquireTokenNative(validRequest, ApiId.ssoSilent).catch((e) => {
                this.ssoSilentMeasurement?.add({
                    brokerErrorName: e.name,
                    brokerErrorCode: e.errorCode,
                });
                // If native token acquisition fails for availability reasons fallback to standard flow
                if (e instanceof NativeAuthError && isFatalNativeAuthError(e)) {
                    this.platformAuthProvider = undefined; // If extension gets uninstalled during session prevent future requests from continuing to attempt platform broker calls
                    const silentIframeClient = this.createSilentIframeClient(validRequest.correlationId);
                    return silentIframeClient.acquireToken(validRequest);
                }
                throw e;
            });
        }
        else {
            const silentIframeClient = this.createSilentIframeClient(validRequest.correlationId);
            result = silentIframeClient.acquireToken(validRequest);
        }
        return result
            .then((response) => {
            const isLoggingIn = loggedInAccounts.length < this.getAllAccounts().length;
            this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_SUCCESS, correlationId, InteractionType.Silent, response);
            if (isLoggingIn) {
                this.eventHandler.emitEvent(EventType.LOGIN_SUCCESS, correlationId, InteractionType.Silent, response.account);
            }
            this.ssoSilentMeasurement?.end({
                success: true,
                isNativeBroker: response.fromPlatformBroker,
                accessTokenSize: response.accessToken.length,
                idTokenSize: response.idToken.length,
            }, undefined, response.account);
            return response;
        })
            .catch((e) => {
            this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_FAILURE, correlationId, InteractionType.Silent, null, e);
            this.ssoSilentMeasurement?.end({
                success: false,
            }, e, request.account);
            throw e;
        })
            .finally(() => {
            this.removeStateChangeListeners(this.trackStateChangeWithMeasurement);
        });
    }
    /**
     * This function redeems an authorization code (passed as code) from the eSTS token endpoint.
     * This authorization code should be acquired server-side using a confidential client to acquire a spa_code.
     * This API is not indended for normal authorization code acquisition and redemption.
     *
     * Redemption of this authorization code will not require PKCE, as it was acquired by a confidential client.
     *
     * @param request {@link AuthorizationCodeRequest}
     * @returns A promise that is fulfilled when this function has completed, or rejected if an error was raised.
     */
    async acquireTokenByCode(request) {
        const correlationId = this.getRequestCorrelationId(request);
        this.logger.trace("0ch6ga", correlationId);
        const atbcMeasurement = this.performanceClient.startMeasurement(AcquireTokenByCode, correlationId);
        preflightCheck(this.initialized, atbcMeasurement, this.config, request);
        this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_START, correlationId, InteractionType.Silent, request);
        atbcMeasurement.add({ scenarioId: request.scenarioId });
        try {
            if (request.code && request.nativeAccountId) {
                // Throw error in case server returns both spa_code and spa_accountid in exchange for auth code.
                throw createBrowserAuthError(spaCodeAndNativeAccountIdPresent);
            }
            else if (request.code) {
                const hybridAuthCode = request.code;
                let response = this.hybridAuthCodeResponses.get(hybridAuthCode);
                if (!response) {
                    this.logger.verbose("06eh73", correlationId);
                    response = this.acquireTokenByCodeAsync({
                        ...request,
                        correlationId,
                    })
                        .then((result) => {
                        this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_SUCCESS, correlationId, InteractionType.Silent, result);
                        this.hybridAuthCodeResponses.delete(hybridAuthCode);
                        atbcMeasurement.end({
                            success: true,
                            accessTokenSize: result.accessToken.length,
                            idTokenSize: result.idToken.length,
                        }, undefined, result.account);
                        return result;
                    })
                        .catch((error) => {
                        this.hybridAuthCodeResponses.delete(hybridAuthCode);
                        this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_FAILURE, correlationId, InteractionType.Silent, null, error);
                        atbcMeasurement.end({
                            success: false,
                        }, error);
                        throw error;
                    });
                    this.hybridAuthCodeResponses.set(hybridAuthCode, response);
                }
                else {
                    this.logger.verbose("0qgp28", correlationId);
                    atbcMeasurement.discard();
                }
                return await response;
            }
            else if (request.nativeAccountId) {
                if (this.canUsePlatformBroker(request, request.nativeAccountId)) {
                    atbcMeasurement.add({
                        isPlatformBrokerRequest: true,
                    });
                    const result = await this.acquireTokenNative({
                        ...request,
                        correlationId,
                    }, ApiId.acquireTokenByCode, request.nativeAccountId).catch((e) => {
                        atbcMeasurement.add({
                            brokerErrorName: e.name,
                            brokerErrorCode: e.errorCode,
                        });
                        // If native token acquisition fails for availability reasons fallback to standard flow
                        if (e instanceof NativeAuthError &&
                            isFatalNativeAuthError(e)) {
                            this.platformAuthProvider = undefined; // If extension gets uninstalled during session prevent future requests from continuing to attempt
                        }
                        throw e;
                    });
                    atbcMeasurement.end({
                        success: true,
                    }, undefined, result.account);
                    return result;
                }
                else {
                    throw createBrowserAuthError(unableToAcquireTokenFromNativePlatform);
                }
            }
            else {
                throw createBrowserAuthError(authCodeOrNativeAccountIdRequired);
            }
        }
        catch (e) {
            this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_FAILURE, correlationId, InteractionType.Silent, null, e);
            atbcMeasurement.end({
                success: false,
            }, e);
            throw e;
        }
    }
    /**
     * Creates a SilentAuthCodeClient to redeem an authorization code.
     * @param request
     * @returns Result of the operation to redeem the authorization code
     */
    async acquireTokenByCodeAsync(request) {
        const correlationId = this.getRequestCorrelationId(request);
        this.logger.trace("10d9hy", correlationId);
        this.acquireTokenByCodeAsyncMeasurement =
            this.performanceClient.startMeasurement(AcquireTokenByCodeAsync, correlationId);
        this.acquireTokenByCodeAsyncMeasurement?.increment({
            visibilityChangeCount: 0,
            onlineStatusChangeCount: 0,
        });
        this.addStateChangeListeners(this.trackStateChangeWithMeasurement);
        const silentAuthCodeClient = this.createSilentAuthCodeClient(correlationId);
        const silentTokenResult = await silentAuthCodeClient
            .acquireToken(request)
            .then((response) => {
            this.acquireTokenByCodeAsyncMeasurement?.end({
                success: true,
                fromCache: response.fromCache,
            });
            return response;
        })
            .catch((tokenRenewalError) => {
            this.acquireTokenByCodeAsyncMeasurement?.end({
                success: false,
            }, tokenRenewalError);
            throw tokenRenewalError;
        })
            .finally(() => {
            this.removeStateChangeListeners(this.trackStateChangeWithMeasurement);
        });
        return silentTokenResult;
    }
    /**
     * Attempt to acquire an access token from the cache
     * @param silentCacheClient SilentCacheClient
     * @param commonRequest CommonSilentFlowRequest
     * @param silentRequest SilentRequest
     * @returns A promise that, when resolved, returns the access token
     */
    async acquireTokenFromCache(commonRequest, cacheLookupPolicy) {
        switch (cacheLookupPolicy) {
            case CacheLookupPolicy.Default:
            case CacheLookupPolicy.AccessToken:
            case CacheLookupPolicy.AccessTokenAndRefreshToken:
                const silentCacheClient = this.createSilentCacheClient(commonRequest.correlationId);
                return invokeAsync(silentCacheClient.acquireToken.bind(silentCacheClient), SilentCacheClientAcquireToken, this.logger, this.performanceClient, commonRequest.correlationId)(commonRequest);
            default:
                throw createClientAuthError(ClientAuthErrorCodes.tokenRefreshRequired);
        }
    }
    /**
     * Attempt to acquire an access token via a refresh token
     * @param commonRequest CommonSilentFlowRequest
     * @param cacheLookupPolicy CacheLookupPolicy
     * @returns A promise that, when resolved, returns the access token
     */
    async acquireTokenByRefreshToken(commonRequest, cacheLookupPolicy) {
        switch (cacheLookupPolicy) {
            case CacheLookupPolicy.Default:
            case CacheLookupPolicy.AccessTokenAndRefreshToken:
            case CacheLookupPolicy.RefreshToken:
            case CacheLookupPolicy.RefreshTokenAndNetwork:
                const silentRefreshClient = this.createSilentRefreshClient(commonRequest.correlationId);
                return invokeAsync(silentRefreshClient.acquireToken.bind(silentRefreshClient), SilentRefreshClientAcquireToken, this.logger, this.performanceClient, commonRequest.correlationId)(commonRequest);
            default:
                throw createClientAuthError(ClientAuthErrorCodes.tokenRefreshRequired);
        }
    }
    /**
     * Attempt to acquire an access token via an iframe
     * @param request CommonSilentFlowRequest
     * @returns A promise that, when resolved, returns the access token
     */
    async acquireTokenBySilentIframe(request) {
        const silentIframeClient = this.createSilentIframeClient(request.correlationId);
        return invokeAsync(silentIframeClient.acquireToken.bind(silentIframeClient), SilentIframeClientAcquireToken, this.logger, this.performanceClient, request.correlationId)(request);
    }
    // #endregion
    // #region Logout
    /**
     * Use to log out the current user, and redirect the user to the postLogoutRedirectUri.
     * Default behaviour is to redirect the user to `window.location.href`.
     * @param logoutRequest
     */
    async logoutRedirect(logoutRequest) {
        const correlationId = this.getRequestCorrelationId(logoutRequest);
        redirectPreflightCheck(this.initialized, this.config);
        this.browserStorage.setInteractionInProgress(true, INTERACTION_TYPE.SIGNOUT);
        const redirectClient = this.createRedirectClient(correlationId);
        return redirectClient.logout(logoutRequest);
    }
    /**
     * Clears local cache for the current user then opens a popup window prompting the user to sign-out of the server
     * @param logoutRequest
     */
    logoutPopup(logoutRequest) {
        try {
            const correlationId = this.getRequestCorrelationId(logoutRequest);
            preflightCheck$1(this.initialized);
            this.browserStorage.setInteractionInProgress(true, INTERACTION_TYPE.SIGNOUT);
            const popupClient = this.createPopupClient(correlationId);
            return popupClient.logout(logoutRequest).finally(() => {
                this.browserStorage.setInteractionInProgress(false);
            });
        }
        catch (e) {
            // Since this function is syncronous we need to reject
            return Promise.reject(e);
        }
    }
    /**
     * Creates a cache interaction client to clear broswer cache.
     * @param logoutRequest
     */
    async clearCache(logoutRequest) {
        if (!this.isBrowserEnvironment) {
            return;
        }
        const correlationId = this.getRequestCorrelationId(logoutRequest);
        const cacheClient = this.createSilentCacheClient(correlationId);
        return cacheClient.logout(logoutRequest);
    }
    // #endregion
    // #region Account APIs
    /**
     * Returns all the accounts in the cache that match the optional filter. If no filter is provided, all accounts are returned.
     * @param accountFilter - (Optional) filter to narrow down the accounts returned
     * @returns Array of AccountInfo objects in cache
     */
    getAllAccounts(accountFilter) {
        return getAllAccounts(this.logger, this.browserStorage, this.isBrowserEnvironment, this.getRequestCorrelationId(), accountFilter);
    }
    /**
     * Returns the first account found in the cache that matches the account filter passed in.
     * @param accountFilter
     * @returns The first account found in the cache matching the provided filter or null if no account could be found.
     */
    getAccount(accountFilter) {
        return getAccount(accountFilter, this.logger, this.browserStorage, this.getRequestCorrelationId());
    }
    /**
     * Sets the account to use as the active account. If no account is passed to the acquireToken APIs, then MSAL will use this active account.
     * @param account
     */
    setActiveAccount(account) {
        setActiveAccount(account, this.browserStorage, this.getRequestCorrelationId());
    }
    /**
     * Gets the currently active account
     */
    getActiveAccount() {
        return getActiveAccount(this.browserStorage, this.getRequestCorrelationId());
    }
    // #endregion
    /**
     * Hydrates the cache with the tokens from an AuthenticationResult
     * @param result
     * @param request
     * @returns
     */
    async hydrateCache(result, request) {
        this.logger.verbose("16jycr", result.correlationId);
        // Account gets saved to browser storage regardless of native or not
        const accountEntity = AccountEntityUtils.createAccountEntityFromAccountInfo(result.account, result.cloudGraphHostName, result.msGraphHost);
        await this.browserStorage.setAccount(accountEntity, result.correlationId, AuthToken.isKmsi(result.idTokenClaims), ApiId.hydrateCache);
        if (result.fromPlatformBroker) {
            this.logger.verbose("1fxyu8", result.correlationId);
            // Tokens from native broker are stored in-memory
            return this.nativeInternalStorage.hydrateCache(result, request);
        }
        else {
            return this.browserStorage.hydrateCache(result, request);
        }
    }
    // #region Helpers
    /**
     * Acquire a token from native device (e.g. WAM)
     * @param request
     */
    async acquireTokenNative(request, apiId, accountId, cacheLookupPolicy) {
        const correlationId = this.getRequestCorrelationId(request);
        this.logger.trace("0b9y3p", correlationId);
        if (!this.platformAuthProvider) {
            throw createBrowserAuthError(nativeConnectionNotEstablished);
        }
        const nativeClient = new PlatformAuthInteractionClient(this.config, this.browserStorage, this.browserCrypto, this.logger, this.eventHandler, this.navigationClient, apiId, this.performanceClient, this.platformAuthProvider, accountId || this.getNativeAccountId(request), this.nativeInternalStorage, correlationId);
        return invokeAsync(nativeClient.acquireToken.bind(nativeClient), NativeInteractionClientAcquireToken, this.logger, this.performanceClient, correlationId)(request, cacheLookupPolicy);
    }
    /**
     * Returns boolean indicating if this request can use the platform broker
     * @param request
     */
    canUsePlatformBroker(request, accountId) {
        const correlationId = this.getRequestCorrelationId(request);
        this.logger.trace("1n9lbl", correlationId);
        if (!this.platformAuthProvider) {
            this.logger.trace("0vnu11", correlationId);
            return false;
        }
        if (!isPlatformAuthAllowed(this.config, this.logger, correlationId, this.platformAuthProvider, request.authenticationScheme)) {
            this.logger.trace("0yoy1g", correlationId);
            return false;
        }
        if (request.prompt) {
            switch (request.prompt) {
                case Constants.PromptValue.NONE:
                case Constants.PromptValue.CONSENT:
                case Constants.PromptValue.LOGIN:
                    this.logger.trace("0vdv8e", correlationId);
                    break;
                default:
                    this.logger.trace("0pdzw6", correlationId);
                    return false;
            }
        }
        if (!accountId && !this.getNativeAccountId(request)) {
            this.logger.trace("16lbtk", correlationId);
            return false;
        }
        return true;
    }
    /**
     * Get the native accountId from the account
     * @param request
     * @returns
     */
    getNativeAccountId(request) {
        const account = request.account ||
            this.getAccount({
                loginHint: request.loginHint,
                sid: request.sid,
            }) ||
            this.getActiveAccount();
        return (account && account.nativeAccountId) || "";
    }
    /**
     * Returns new instance of the Popup Interaction Client
     * @param correlationId
     */
    createPopupClient(correlationId) {
        return new PopupClient(this.config, this.browserStorage, this.browserCrypto, this.logger, this.eventHandler, this.navigationClient, this.performanceClient, this.nativeInternalStorage, correlationId, this.platformAuthProvider);
    }
    /**
     * Returns new instance of the Redirect Interaction Client
     * @param correlationId
     */
    createRedirectClient(correlationId) {
        return new RedirectClient(this.config, this.browserStorage, this.browserCrypto, this.logger, this.eventHandler, this.navigationClient, this.performanceClient, this.nativeInternalStorage, correlationId, this.platformAuthProvider);
    }
    /**
     * Returns new instance of the Silent Iframe Interaction Client
     * @param correlationId
     */
    createSilentIframeClient(correlationId) {
        return new SilentIframeClient(this.config, this.browserStorage, this.browserCrypto, this.logger, this.eventHandler, this.navigationClient, ApiId.ssoSilent, this.performanceClient, this.nativeInternalStorage, correlationId, this.platformAuthProvider);
    }
    /**
     * Returns new instance of the Silent Cache Interaction Client
     */
    createSilentCacheClient(correlationId) {
        return new SilentCacheClient(this.config, this.browserStorage, this.browserCrypto, this.logger, this.eventHandler, this.navigationClient, this.performanceClient, correlationId, this.platformAuthProvider);
    }
    /**
     * Returns new instance of the Silent Refresh Interaction Client
     */
    createSilentRefreshClient(correlationId) {
        return new SilentRefreshClient(this.config, this.browserStorage, this.browserCrypto, this.logger, this.eventHandler, this.navigationClient, this.performanceClient, correlationId, this.platformAuthProvider);
    }
    /**
     * Returns new instance of the Silent AuthCode Interaction Client
     */
    createSilentAuthCodeClient(correlationId) {
        return new SilentAuthCodeClient(this.config, this.browserStorage, this.browserCrypto, this.logger, this.eventHandler, this.navigationClient, ApiId.acquireTokenByCode, this.performanceClient, correlationId, this.platformAuthProvider);
    }
    /**
     * Adds event callbacks to array
     * @param callback
     */
    addEventCallback(callback, eventTypes) {
        return this.eventHandler.addEventCallback(callback, eventTypes);
    }
    /**
     * Removes callback with provided id from callback array
     * @param callbackId
     */
    removeEventCallback(callbackId) {
        this.eventHandler.removeEventCallback(callbackId);
    }
    /**
     * Registers a callback to receive performance events.
     *
     * @param {PerformanceCallbackFunction} callback
     * @returns {string}
     */
    addPerformanceCallback(callback) {
        blockNonBrowserEnvironment();
        return this.performanceClient.addPerformanceCallback(callback);
    }
    /**
     * Removes a callback registered with addPerformanceCallback.
     *
     * @param {string} callbackId
     * @returns {boolean}
     */
    removePerformanceCallback(callbackId) {
        return this.performanceClient.removePerformanceCallback(callbackId);
    }
    /**
     * Returns the logger instance
     */
    getLogger() {
        return this.logger;
    }
    /**
     * Replaces the default logger set in configurations with new Logger with new configurations
     * @param logger Logger instance
     */
    setLogger(logger) {
        this.logger = logger;
    }
    /**
     * Called by wrapper libraries (Angular & React) to set SKU and Version passed down to telemetry, logger, etc.
     * @param sku
     * @param version
     */
    initializeWrapperLibrary(sku, version) {
        // Validate the SKU passed in is one we expect
        this.browserStorage.setWrapperMetadata(sku, version);
    }
    /**
     * Sets navigation client
     * @param navigationClient
     */
    setNavigationClient(navigationClient) {
        this.navigationClient = navigationClient;
    }
    /**
     * Returns the configuration object
     */
    getConfiguration() {
        return this.config;
    }
    /**
     * Returns the performance client
     */
    getPerformanceClient() {
        return this.performanceClient;
    }
    /**
     * Returns the browser env indicator
     */
    isBrowserEnv() {
        return this.isBrowserEnvironment;
    }
    /**
     * Generates a correlation id for a request if none is provided.
     *
     * @protected
     * @param {?Partial<BaseAuthRequest>} [request]
     * @returns {string}
     */
    getRequestCorrelationId(request) {
        if (request?.correlationId) {
            return request.correlationId;
        }
        if (this.isBrowserEnvironment) {
            return createNewGuid();
        }
        /*
         * Included for fallback for non-browser environments,
         * and to ensure this method always returns a string.
         */
        return "";
    }
    // #endregion
    /**
     * Use when initiating the login process by redirecting the user's browser to the authorization endpoint. This function redirects the page, so
     * any code that follows this function will not execute.
     *
     * IMPORTANT: It is NOT recommended to have code that is dependent on the resolution of the Promise. This function will navigate away from the current
     * browser window. It currently returns a Promise in order to reflect the asynchronous nature of the code running in this function.
     *
     * @param request
     */
    async loginRedirect(request) {
        const correlationId = this.getRequestCorrelationId(request);
        this.logger.verbose("0lz9hf", correlationId);
        return this.acquireTokenRedirect({
            correlationId,
            ...(request || DEFAULT_REQUEST),
        });
    }
    /**
     * Use when initiating the login process via opening a popup window in the user's browser
     *
     * @param request
     *
     * @returns A promise that is fulfilled when this function has completed, or rejected if an error was raised.
     */
    loginPopup(request) {
        const correlationId = this.getRequestCorrelationId(request);
        this.logger.verbose("0qw7v5", correlationId);
        return this.acquireTokenPopup({
            correlationId,
            ...(request || DEFAULT_REQUEST),
        });
    }
    /**
     * Silently acquire an access token for a given set of scopes. Returns currently processing promise if parallel requests are made.
     *
     * @param {@link (SilentRequest:type)}
     * @returns {Promise.<AuthenticationResult>} - a promise that is fulfilled when this function has completed, or rejected if an error was raised. Returns the {@link AuthResponse} object
     */
    async acquireTokenSilent(request) {
        const correlationId = this.getRequestCorrelationId(request);
        const atsMeasurement = this.performanceClient.startMeasurement(AcquireTokenSilent, correlationId);
        atsMeasurement.add({
            cacheLookupPolicy: request.cacheLookupPolicy,
            scenarioId: request.scenarioId,
            ssoCapable: this.getCachedSsoCapable(),
        });
        preflightCheck(this.initialized, atsMeasurement, this.config, request);
        this.logger.verbose("0x1c4s", correlationId);
        const account = request.account || this.getActiveAccount();
        if (!account) {
            throw createBrowserAuthError(noAccountError);
        }
        return this.acquireTokenSilentDeduped(request, account, correlationId)
            .then((result) => {
            atsMeasurement.end({
                success: true,
                fromCache: result.fromCache,
                accessTokenSize: result.accessToken.length,
                idTokenSize: result.idToken.length,
            }, undefined, result.account);
            return {
                ...result,
                state: request.state,
                correlationId: correlationId, // Ensures PWB scenarios can correctly match request to response
            };
        })
            .catch((error) => {
            if (error instanceof AuthError) {
                // Ensures PWB scenarios can correctly match request to response
                error.setCorrelationId(correlationId);
            }
            atsMeasurement.end({
                success: false,
            }, error, account);
            throw error;
        });
    }
    /**
     * Checks if identical request is already in flight and returns reference to the existing promise or fires off a new one if this is the first
     * @param request
     * @param account
     * @param correlationId
     * @returns
     */
    async acquireTokenSilentDeduped(request, account, correlationId) {
        const thumbprint = getRequestThumbprint(this.config.auth.clientId, {
            ...request,
            authority: request.authority || this.config.auth.authority,
            correlationId: correlationId,
        }, account.homeAccountId);
        const silentRequestKey = JSON.stringify(thumbprint);
        const inProgressRequest = this.activeSilentTokenRequests.get(silentRequestKey);
        if (typeof inProgressRequest === "undefined") {
            this.logger.verbose("0fcjbk", correlationId);
            this.performanceClient.addFields({ deduped: false }, correlationId);
            const activeRequest = invokeAsync(this.acquireTokenSilentAsync.bind(this), AcquireTokenSilentAsync, this.logger, this.performanceClient, correlationId)({
                ...request,
                correlationId,
            }, account);
            this.activeSilentTokenRequests.set(silentRequestKey, activeRequest);
            return activeRequest.finally(() => {
                this.activeSilentTokenRequests.delete(silentRequestKey);
            });
        }
        else {
            this.logger.verbose("1yq7nb", correlationId);
            this.performanceClient.addFields({ deduped: true }, correlationId);
            return inProgressRequest;
        }
    }
    /**
     * Silently acquire an access token for a given set of scopes. Will use cached token if available, otherwise will attempt to acquire a new token from the network via refresh token.
     * @param {@link (SilentRequest:type)}
     * @param {@link (AccountInfo:type)}
     * @returns {Promise.<AuthenticationResult>} - a promise that is fulfilled when this function has completed, or rejected if an error was raised. Returns the {@link AuthResponse}
     */
    async acquireTokenSilentAsync(request, account) {
        const trackStateChange = (event) => this.trackStateChange(request.correlationId, event);
        this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_START, request.correlationId, InteractionType.Silent, request);
        if (request.correlationId) {
            this.performanceClient.incrementFields({ visibilityChangeCount: 0, onlineStatusChangeCount: 0 }, request.correlationId);
        }
        this.addStateChangeListeners(trackStateChange);
        const silentRequest = await invokeAsync(initializeSilentRequest, InitializeSilentRequest, this.logger, this.performanceClient, request.correlationId)(request, account, this.config, this.performanceClient, this.logger);
        const cacheLookupPolicy = request.cacheLookupPolicy || CacheLookupPolicy.Default;
        const result = this.acquireTokenSilentNoIframe(silentRequest, cacheLookupPolicy).catch(async (refreshTokenError) => {
            const shouldTryToResolveSilently = checkIfRefreshTokenErrorCanBeResolvedSilently(refreshTokenError, cacheLookupPolicy);
            if (shouldTryToResolveSilently) {
                const silentRefreshReason = `${refreshTokenError.errorCode}${refreshTokenError.subError
                    ? `|${refreshTokenError.subError}`
                    : ""}`;
                this.performanceClient.addFields({ silentRefreshReason }, request.correlationId);
                if (!this.activeIframeRequest) {
                    let _resolve;
                    // Always set the active request tracker immediately after checking it to prevent races
                    this.activeIframeRequest = [
                        new Promise((resolve) => {
                            _resolve = resolve;
                        }),
                        silentRequest.correlationId,
                    ];
                    this.logger.verbose("0rh08z", silentRequest.correlationId);
                    return invokeAsync(this.acquireTokenBySilentIframe.bind(this), AcquireTokenBySilentIframe, this.logger, this.performanceClient, silentRequest.correlationId)(silentRequest)
                        .then((iframeResult) => {
                        _resolve(true);
                        return iframeResult;
                    })
                        .catch((e) => {
                        _resolve(false);
                        throw e;
                    })
                        .finally(() => {
                        this.activeIframeRequest = undefined;
                    });
                }
                else if (cacheLookupPolicy !== CacheLookupPolicy.Skip) {
                    const [activePromise, activeCorrelationId] = this.activeIframeRequest;
                    this.logger.verbose("1w8fso", silentRequest.correlationId);
                    const awaitConcurrentIframeMeasure = this.performanceClient.startMeasurement(AwaitConcurrentIframe, silentRequest.correlationId);
                    awaitConcurrentIframeMeasure.add({
                        awaitIframeCorrelationId: activeCorrelationId,
                    });
                    const activePromiseResult = await activePromise;
                    awaitConcurrentIframeMeasure.end({
                        success: activePromiseResult,
                    });
                    if (activePromiseResult) {
                        this.logger.verbose("0ywzzi", silentRequest.correlationId);
                        // Retry cache lookup and/or RT exchange after iframe completes
                        return this.acquireTokenSilentNoIframe(silentRequest, cacheLookupPolicy);
                    }
                    else {
                        this.logger.info("17y14q", silentRequest.correlationId);
                        // If previous iframe request failed, it's unlikely to succeed this time. Throw original error.
                        throw refreshTokenError;
                    }
                }
                else {
                    // Cache policy set to skip and another iframe request is already in progress
                    this.logger.warning("1bd4p8", silentRequest.correlationId);
                    return invokeAsync(this.acquireTokenBySilentIframe.bind(this), AcquireTokenBySilentIframe, this.logger, this.performanceClient, silentRequest.correlationId)(silentRequest);
                }
            }
            else {
                // Error cannot be silently resolved or iframe renewal is not allowed, interaction required
                throw refreshTokenError;
            }
        });
        return result
            .then((response) => {
            this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_SUCCESS, request.correlationId, InteractionType.Silent, response);
            if (request.correlationId) {
                this.performanceClient.addFields({
                    fromCache: response.fromCache,
                    isNativeBroker: response.fromPlatformBroker,
                }, request.correlationId);
            }
            return response;
        })
            .catch((tokenRenewalError) => {
            this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_FAILURE, request.correlationId, InteractionType.Silent, null, tokenRenewalError);
            throw tokenRenewalError;
        })
            .finally(() => {
            this.removeStateChangeListeners(trackStateChange);
        });
    }
    /**
     * AcquireTokenSilent without the iframe fallback. This is used to enable the correct fallbacks in cases where there's a potential for multiple silent requests to be made in parallel and prevent those requests from making concurrent iframe requests.
     * @param silentRequest
     * @param cacheLookupPolicy
     * @returns
     */
    async acquireTokenSilentNoIframe(silentRequest, cacheLookupPolicy) {
        // if the cache policy is set to access_token only, we should not be hitting the native layer yet
        if (isPlatformAuthAllowed(this.config, this.logger, silentRequest.correlationId, this.platformAuthProvider, silentRequest.authenticationScheme) &&
            silentRequest.account.nativeAccountId) {
            this.logger.verbose("0sczo4", silentRequest.correlationId);
            this.performanceClient.addFields({ isPlatformBrokerRequest: true }, silentRequest.correlationId);
            return this.acquireTokenNative(silentRequest, ApiId.acquireTokenSilent_silentFlow, silentRequest.account.nativeAccountId, cacheLookupPolicy).catch(async (e) => {
                this.performanceClient.addFields({
                    brokerErrorName: e.name,
                    brokerErrorCode: e.errorCode,
                }, silentRequest.correlationId);
                // If native token acquisition fails for availability reasons fallback to web flow
                if (e instanceof NativeAuthError && isFatalNativeAuthError(e)) {
                    this.logger.verbose("07rkmb", silentRequest.correlationId);
                    this.platformAuthProvider = undefined; // Prevent future requests from continuing to attempt
                    // Cache will not contain tokens, given that previous WAM requests succeeded. Skip cache and RT renewal and go straight to iframe renewal
                    throw createClientAuthError(ClientAuthErrorCodes.tokenRefreshRequired);
                }
                throw e;
            });
        }
        else {
            this.logger.verbose("0ox81t", silentRequest.correlationId);
            // add logs to identify embedded cache retrieval
            if (cacheLookupPolicy === CacheLookupPolicy.AccessToken) {
                this.logger.verbose("0fvwxe", silentRequest.correlationId);
            }
            return invokeAsync(this.acquireTokenFromCache.bind(this), AcquireTokenFromCache, this.logger, this.performanceClient, silentRequest.correlationId)(silentRequest, cacheLookupPolicy).catch((cacheError) => {
                if (cacheLookupPolicy === CacheLookupPolicy.AccessToken) {
                    throw cacheError;
                }
                this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_NETWORK_START, silentRequest.correlationId, InteractionType.Silent, silentRequest);
                return invokeAsync(this.acquireTokenByRefreshToken.bind(this), AcquireTokenByRefreshToken, this.logger, this.performanceClient, silentRequest.correlationId)(silentRequest, cacheLookupPolicy);
            });
        }
    }
    /**
     * Pre-generates PKCE codes and stores it in local variable
     * @param correlationId
     */
    async preGeneratePkceCodes(correlationId) {
        this.logger.verbose("1x6uj6", correlationId);
        this.pkceCode = await invokeAsync(generatePkceCodes, GeneratePkceCodes, this.logger, this.performanceClient, correlationId)(this.performanceClient, this.logger, correlationId);
        return Promise.resolve();
    }
    /**
     * Provides pre-generated PKCE codes, if any
     * @param correlationId
     */
    getPreGeneratedPkceCodes(correlationId) {
        const res = this.pkceCode ? { ...this.pkceCode } : undefined;
        this.pkceCode = undefined;
        if (res) {
            this.logger.verbose("12js1o", correlationId);
        }
        else {
            this.logger.verbose("1oe9ci", correlationId);
        }
        this.performanceClient.addFields({ usePreGeneratedPkce: !!res }, correlationId);
        return res;
    }
    logMultipleInstances(performanceEvent, correlationId) {
        const clientId = this.config.auth.clientId;
        if (!window)
            return;
        // @ts-ignore
        window.msal = window.msal || {};
        // @ts-ignore
        window.msal.clientIds = window.msal.clientIds || [];
        // @ts-ignore
        const clientIds = window.msal.clientIds;
        if (clientIds.length > 0) {
            this.logger.verbose("1qtz3l", correlationId);
        }
        // @ts-ignore
        window.msal.clientIds.push(clientId);
        collectInstanceStats(clientId, performanceEvent, this.logger, correlationId);
    }
}
/**
 * Determines whether an error thrown by the refresh token endpoint can be resolved without interaction
 * @param refreshTokenError
 * @param silentRequest
 * @param cacheLookupPolicy
 * @returns
 */
function checkIfRefreshTokenErrorCanBeResolvedSilently(refreshTokenError, cacheLookupPolicy) {
    const noInteractionRequired = !(refreshTokenError instanceof InteractionRequiredAuthError &&
        // For refresh token errors, bad_token does not always require interaction (silently resolvable)
        refreshTokenError.subError !==
            InteractionRequiredAuthErrorCodes.badToken);
    // Errors that result when the refresh token needs to be replaced
    const refreshTokenRefreshRequired = refreshTokenError.errorCode === BrowserConstants.INVALID_GRANT_ERROR ||
        refreshTokenError.errorCode ===
            ClientAuthErrorCodes.tokenRefreshRequired;
    // Errors that may be resolved before falling back to interaction (through iframe renewal)
    const isSilentlyResolvable = (noInteractionRequired && refreshTokenRefreshRequired) ||
        refreshTokenError.errorCode ===
            InteractionRequiredAuthErrorCodes.noTokensFound ||
        refreshTokenError.errorCode ===
            InteractionRequiredAuthErrorCodes.refreshTokenExpired;
    // Only these policies allow for an iframe renewal attempt
    const tryIframeRenewal = iFrameRenewalPolicies.includes(cacheLookupPolicy);
    return isSilentlyResolvable && tryIframeRenewal;
}
 
export { StandardController };
//# sourceMappingURL=StandardController.mjs.map