Add extracted source directory and README navigation

This commit is contained in:
Shawn Bot
2026-03-31 14:56:06 +00:00
parent 6252bb6eb5
commit 91e01d755b
4757 changed files with 984951 additions and 0 deletions

View File

@@ -0,0 +1,526 @@
/*! @azure/msal-common v15.13.1 2025-10-29 */
'use strict';
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Enumeration of operations that are instrumented by have their performance measured by the PerformanceClient.
*
* @export
* @enum {number}
*/
const PerformanceEvents = {
/**
* acquireTokenByCode API (msal-browser and msal-node).
* Used to acquire tokens by trading an authorization code against the token endpoint.
*/
AcquireTokenByCode: "acquireTokenByCode",
/**
* acquireTokenByRefreshToken API (msal-browser and msal-node).
* Used to renew an access token using a refresh token against the token endpoint.
*/
AcquireTokenByRefreshToken: "acquireTokenByRefreshToken",
/**
* acquireTokenSilent API (msal-browser and msal-node).
* Used to silently acquire a new access token (from the cache or the network).
*/
AcquireTokenSilent: "acquireTokenSilent",
/**
* acquireTokenSilentAsync (msal-browser).
* Internal API for acquireTokenSilent.
*/
AcquireTokenSilentAsync: "acquireTokenSilentAsync",
/**
* acquireTokenPopup (msal-browser).
* Used to acquire a new access token interactively through pop ups
*/
AcquireTokenPopup: "acquireTokenPopup",
/**
* acquireTokenPreRedirect (msal-browser).
* First part of the redirect flow.
* Used to acquire a new access token interactively through redirects.
*/
AcquireTokenPreRedirect: "acquireTokenPreRedirect",
/**
* acquireTokenRedirect (msal-browser).
* Second part of the redirect flow.
* Used to acquire a new access token interactively through redirects.
*/
AcquireTokenRedirect: "acquireTokenRedirect",
/**
* getPublicKeyThumbprint API in CryptoOpts class (msal-browser).
* Used to generate a public/private keypair and generate a public key thumbprint for pop requests.
*/
CryptoOptsGetPublicKeyThumbprint: "cryptoOptsGetPublicKeyThumbprint",
/**
* signJwt API in CryptoOpts class (msal-browser).
* Used to signed a pop token.
*/
CryptoOptsSignJwt: "cryptoOptsSignJwt",
/**
* acquireToken API in the SilentCacheClient class (msal-browser).
* Used to read access tokens from the cache.
*/
SilentCacheClientAcquireToken: "silentCacheClientAcquireToken",
/**
* acquireToken API in the SilentIframeClient class (msal-browser).
* Used to acquire a new set of tokens from the authorize endpoint in a hidden iframe.
*/
SilentIframeClientAcquireToken: "silentIframeClientAcquireToken",
AwaitConcurrentIframe: "awaitConcurrentIframe",
/**
* acquireToken API in SilentRereshClient (msal-browser).
* Used to acquire a new set of tokens from the token endpoint using a refresh token.
*/
SilentRefreshClientAcquireToken: "silentRefreshClientAcquireToken",
/**
* ssoSilent API (msal-browser).
* Used to silently acquire an authorization code and set of tokens using a hidden iframe.
*/
SsoSilent: "ssoSilent",
/**
* getDiscoveredAuthority API in StandardInteractionClient class (msal-browser).
* Used to load authority metadata for a request.
*/
StandardInteractionClientGetDiscoveredAuthority: "standardInteractionClientGetDiscoveredAuthority",
/**
* acquireToken APIs in msal-browser.
* Used to make an /authorize endpoint call with native brokering enabled.
*/
FetchAccountIdWithNativeBroker: "fetchAccountIdWithNativeBroker",
/**
* acquireToken API in NativeInteractionClient class (msal-browser).
* Used to acquire a token from Native component when native brokering is enabled.
*/
NativeInteractionClientAcquireToken: "nativeInteractionClientAcquireToken",
/**
* Time spent creating default headers for requests to token endpoint
*/
BaseClientCreateTokenRequestHeaders: "baseClientCreateTokenRequestHeaders",
/**
* Time spent sending/waiting for the response of a request to the token endpoint
*/
NetworkClientSendPostRequestAsync: "networkClientSendPostRequestAsync",
RefreshTokenClientExecutePostToTokenEndpoint: "refreshTokenClientExecutePostToTokenEndpoint",
AuthorizationCodeClientExecutePostToTokenEndpoint: "authorizationCodeClientExecutePostToTokenEndpoint",
/**
* Used to measure the time taken for completing embedded-broker handshake (PW-Broker).
*/
BrokerHandhshake: "brokerHandshake",
/**
* acquireTokenByRefreshToken API in BrokerClientApplication (PW-Broker) .
*/
AcquireTokenByRefreshTokenInBroker: "acquireTokenByRefreshTokenInBroker",
/**
* Time taken for token acquisition by broker
*/
AcquireTokenByBroker: "acquireTokenByBroker",
/**
* Time spent on the network for refresh token acquisition
*/
RefreshTokenClientExecuteTokenRequest: "refreshTokenClientExecuteTokenRequest",
/**
* Time taken for acquiring refresh token , records RT size
*/
RefreshTokenClientAcquireToken: "refreshTokenClientAcquireToken",
/**
* Time taken for acquiring cached refresh token
*/
RefreshTokenClientAcquireTokenWithCachedRefreshToken: "refreshTokenClientAcquireTokenWithCachedRefreshToken",
/**
* acquireTokenByRefreshToken API in RefreshTokenClient (msal-common).
*/
RefreshTokenClientAcquireTokenByRefreshToken: "refreshTokenClientAcquireTokenByRefreshToken",
/**
* Helper function to create token request body in RefreshTokenClient (msal-common).
*/
RefreshTokenClientCreateTokenRequestBody: "refreshTokenClientCreateTokenRequestBody",
/**
* acquireTokenFromCache (msal-browser).
* Internal API for acquiring token from cache
*/
AcquireTokenFromCache: "acquireTokenFromCache",
SilentFlowClientAcquireCachedToken: "silentFlowClientAcquireCachedToken",
SilentFlowClientGenerateResultFromCacheRecord: "silentFlowClientGenerateResultFromCacheRecord",
/**
* acquireTokenBySilentIframe (msal-browser).
* Internal API for acquiring token by silent Iframe
*/
AcquireTokenBySilentIframe: "acquireTokenBySilentIframe",
/**
* Internal API for initializing base request in BaseInteractionClient (msal-browser)
*/
InitializeBaseRequest: "initializeBaseRequest",
/**
* Internal API for initializing silent request in SilentCacheClient (msal-browser)
*/
InitializeSilentRequest: "initializeSilentRequest",
InitializeClientApplication: "initializeClientApplication",
InitializeCache: "initializeCache",
/**
* Helper function in SilentIframeClient class (msal-browser).
*/
SilentIframeClientTokenHelper: "silentIframeClientTokenHelper",
/**
* SilentHandler
*/
SilentHandlerInitiateAuthRequest: "silentHandlerInitiateAuthRequest",
SilentHandlerMonitorIframeForHash: "silentHandlerMonitorIframeForHash",
SilentHandlerLoadFrame: "silentHandlerLoadFrame",
SilentHandlerLoadFrameSync: "silentHandlerLoadFrameSync",
/**
* Helper functions in StandardInteractionClient class (msal-browser)
*/
StandardInteractionClientCreateAuthCodeClient: "standardInteractionClientCreateAuthCodeClient",
StandardInteractionClientGetClientConfiguration: "standardInteractionClientGetClientConfiguration",
StandardInteractionClientInitializeAuthorizationRequest: "standardInteractionClientInitializeAuthorizationRequest",
/**
* getAuthCodeUrl API (msal-browser and msal-node).
*/
GetAuthCodeUrl: "getAuthCodeUrl",
GetStandardParams: "getStandardParams",
/**
* Functions from InteractionHandler (msal-browser)
*/
HandleCodeResponseFromServer: "handleCodeResponseFromServer",
HandleCodeResponse: "handleCodeResponse",
HandleResponseEar: "handleResponseEar",
HandleResponsePlatformBroker: "handleResponsePlatformBroker",
HandleResponseCode: "handleResponseCode",
UpdateTokenEndpointAuthority: "updateTokenEndpointAuthority",
/**
* APIs in Authorization Code Client (msal-common)
*/
AuthClientAcquireToken: "authClientAcquireToken",
AuthClientExecuteTokenRequest: "authClientExecuteTokenRequest",
AuthClientCreateTokenRequestBody: "authClientCreateTokenRequestBody",
/**
* Generate functions in PopTokenGenerator (msal-common)
*/
PopTokenGenerateCnf: "popTokenGenerateCnf",
PopTokenGenerateKid: "popTokenGenerateKid",
/**
* handleServerTokenResponse API in ResponseHandler (msal-common)
*/
HandleServerTokenResponse: "handleServerTokenResponse",
DeserializeResponse: "deserializeResponse",
/**
* Authority functions
*/
AuthorityFactoryCreateDiscoveredInstance: "authorityFactoryCreateDiscoveredInstance",
AuthorityResolveEndpointsAsync: "authorityResolveEndpointsAsync",
AuthorityResolveEndpointsFromLocalSources: "authorityResolveEndpointsFromLocalSources",
AuthorityGetCloudDiscoveryMetadataFromNetwork: "authorityGetCloudDiscoveryMetadataFromNetwork",
AuthorityUpdateCloudDiscoveryMetadata: "authorityUpdateCloudDiscoveryMetadata",
AuthorityGetEndpointMetadataFromNetwork: "authorityGetEndpointMetadataFromNetwork",
AuthorityUpdateEndpointMetadata: "authorityUpdateEndpointMetadata",
AuthorityUpdateMetadataWithRegionalInformation: "authorityUpdateMetadataWithRegionalInformation",
/**
* Region Discovery functions
*/
RegionDiscoveryDetectRegion: "regionDiscoveryDetectRegion",
RegionDiscoveryGetRegionFromIMDS: "regionDiscoveryGetRegionFromIMDS",
RegionDiscoveryGetCurrentVersion: "regionDiscoveryGetCurrentVersion",
AcquireTokenByCodeAsync: "acquireTokenByCodeAsync",
GetEndpointMetadataFromNetwork: "getEndpointMetadataFromNetwork",
GetCloudDiscoveryMetadataFromNetworkMeasurement: "getCloudDiscoveryMetadataFromNetworkMeasurement",
HandleRedirectPromiseMeasurement: "handleRedirectPromise",
HandleNativeRedirectPromiseMeasurement: "handleNativeRedirectPromise",
UpdateCloudDiscoveryMetadataMeasurement: "updateCloudDiscoveryMetadataMeasurement",
UsernamePasswordClientAcquireToken: "usernamePasswordClientAcquireToken",
NativeMessageHandlerHandshake: "nativeMessageHandlerHandshake",
NativeGenerateAuthResult: "nativeGenerateAuthResult",
RemoveHiddenIframe: "removeHiddenIframe",
/**
* Cache operations
*/
ClearTokensAndKeysWithClaims: "clearTokensAndKeysWithClaims",
CacheManagerGetRefreshToken: "cacheManagerGetRefreshToken",
ImportExistingCache: "importExistingCache",
SetUserData: "setUserData",
LocalStorageUpdated: "localStorageUpdated",
/**
* Crypto Operations
*/
GeneratePkceCodes: "generatePkceCodes",
GenerateCodeVerifier: "generateCodeVerifier",
GenerateCodeChallengeFromVerifier: "generateCodeChallengeFromVerifier",
Sha256Digest: "sha256Digest",
GetRandomValues: "getRandomValues",
GenerateHKDF: "generateHKDF",
GenerateBaseKey: "generateBaseKey",
Base64Decode: "base64Decode",
UrlEncodeArr: "urlEncodeArr",
Encrypt: "encrypt",
Decrypt: "decrypt",
GenerateEarKey: "generateEarKey",
DecryptEarResponse: "decryptEarResponse",
};
const PerformanceEventAbbreviations = new Map([
[PerformanceEvents.AcquireTokenByCode, "ATByCode"],
[PerformanceEvents.AcquireTokenByRefreshToken, "ATByRT"],
[PerformanceEvents.AcquireTokenSilent, "ATS"],
[PerformanceEvents.AcquireTokenSilentAsync, "ATSAsync"],
[PerformanceEvents.AcquireTokenPopup, "ATPopup"],
[PerformanceEvents.AcquireTokenRedirect, "ATRedirect"],
[
PerformanceEvents.CryptoOptsGetPublicKeyThumbprint,
"CryptoGetPKThumb",
],
[PerformanceEvents.CryptoOptsSignJwt, "CryptoSignJwt"],
[PerformanceEvents.SilentCacheClientAcquireToken, "SltCacheClientAT"],
[PerformanceEvents.SilentIframeClientAcquireToken, "SltIframeClientAT"],
[PerformanceEvents.SilentRefreshClientAcquireToken, "SltRClientAT"],
[PerformanceEvents.SsoSilent, "SsoSlt"],
[
PerformanceEvents.StandardInteractionClientGetDiscoveredAuthority,
"StdIntClientGetDiscAuth",
],
[
PerformanceEvents.FetchAccountIdWithNativeBroker,
"FetchAccIdWithNtvBroker",
],
[
PerformanceEvents.NativeInteractionClientAcquireToken,
"NtvIntClientAT",
],
[
PerformanceEvents.BaseClientCreateTokenRequestHeaders,
"BaseClientCreateTReqHead",
],
[
PerformanceEvents.NetworkClientSendPostRequestAsync,
"NetClientSendPost",
],
[
PerformanceEvents.RefreshTokenClientExecutePostToTokenEndpoint,
"RTClientExecPost",
],
[
PerformanceEvents.AuthorizationCodeClientExecutePostToTokenEndpoint,
"AuthCodeClientExecPost",
],
[PerformanceEvents.BrokerHandhshake, "BrokerHandshake"],
[
PerformanceEvents.AcquireTokenByRefreshTokenInBroker,
"ATByRTInBroker",
],
[PerformanceEvents.AcquireTokenByBroker, "ATByBroker"],
[
PerformanceEvents.RefreshTokenClientExecuteTokenRequest,
"RTClientExecTReq",
],
[PerformanceEvents.RefreshTokenClientAcquireToken, "RTClientAT"],
[
PerformanceEvents.RefreshTokenClientAcquireTokenWithCachedRefreshToken,
"RTClientATWithCachedRT",
],
[
PerformanceEvents.RefreshTokenClientAcquireTokenByRefreshToken,
"RTClientATByRT",
],
[
PerformanceEvents.RefreshTokenClientCreateTokenRequestBody,
"RTClientCreateTReqBody",
],
[PerformanceEvents.AcquireTokenFromCache, "ATFromCache"],
[
PerformanceEvents.SilentFlowClientAcquireCachedToken,
"SltFlowClientATCached",
],
[
PerformanceEvents.SilentFlowClientGenerateResultFromCacheRecord,
"SltFlowClientGenResFromCache",
],
[PerformanceEvents.AcquireTokenBySilentIframe, "ATBySltIframe"],
[PerformanceEvents.InitializeBaseRequest, "InitBaseReq"],
[PerformanceEvents.InitializeSilentRequest, "InitSltReq"],
[
PerformanceEvents.InitializeClientApplication,
"InitClientApplication",
],
[PerformanceEvents.InitializeCache, "InitCache"],
[PerformanceEvents.ImportExistingCache, "importCache"],
[PerformanceEvents.SetUserData, "setUserData"],
[PerformanceEvents.LocalStorageUpdated, "localStorageUpdated"],
[PerformanceEvents.SilentIframeClientTokenHelper, "SIClientTHelper"],
[
PerformanceEvents.SilentHandlerInitiateAuthRequest,
"SHandlerInitAuthReq",
],
[
PerformanceEvents.SilentHandlerMonitorIframeForHash,
"SltHandlerMonitorIframeForHash",
],
[PerformanceEvents.SilentHandlerLoadFrame, "SHandlerLoadFrame"],
[PerformanceEvents.SilentHandlerLoadFrameSync, "SHandlerLoadFrameSync"],
[
PerformanceEvents.StandardInteractionClientCreateAuthCodeClient,
"StdIntClientCreateAuthCodeClient",
],
[
PerformanceEvents.StandardInteractionClientGetClientConfiguration,
"StdIntClientGetClientConf",
],
[
PerformanceEvents.StandardInteractionClientInitializeAuthorizationRequest,
"StdIntClientInitAuthReq",
],
[PerformanceEvents.GetAuthCodeUrl, "GetAuthCodeUrl"],
[
PerformanceEvents.HandleCodeResponseFromServer,
"HandleCodeResFromServer",
],
[PerformanceEvents.HandleCodeResponse, "HandleCodeResp"],
[PerformanceEvents.HandleResponseEar, "HandleRespEar"],
[PerformanceEvents.HandleResponseCode, "HandleRespCode"],
[
PerformanceEvents.HandleResponsePlatformBroker,
"HandleRespPlatBroker",
],
[PerformanceEvents.UpdateTokenEndpointAuthority, "UpdTEndpointAuth"],
[PerformanceEvents.AuthClientAcquireToken, "AuthClientAT"],
[PerformanceEvents.AuthClientExecuteTokenRequest, "AuthClientExecTReq"],
[
PerformanceEvents.AuthClientCreateTokenRequestBody,
"AuthClientCreateTReqBody",
],
[PerformanceEvents.PopTokenGenerateCnf, "PopTGenCnf"],
[PerformanceEvents.PopTokenGenerateKid, "PopTGenKid"],
[PerformanceEvents.HandleServerTokenResponse, "HandleServerTRes"],
[PerformanceEvents.DeserializeResponse, "DeserializeRes"],
[
PerformanceEvents.AuthorityFactoryCreateDiscoveredInstance,
"AuthFactCreateDiscInst",
],
[
PerformanceEvents.AuthorityResolveEndpointsAsync,
"AuthResolveEndpointsAsync",
],
[
PerformanceEvents.AuthorityResolveEndpointsFromLocalSources,
"AuthResolveEndpointsFromLocal",
],
[
PerformanceEvents.AuthorityGetCloudDiscoveryMetadataFromNetwork,
"AuthGetCDMetaFromNet",
],
[
PerformanceEvents.AuthorityUpdateCloudDiscoveryMetadata,
"AuthUpdCDMeta",
],
[
PerformanceEvents.AuthorityGetEndpointMetadataFromNetwork,
"AuthUpdCDMetaFromNet",
],
[
PerformanceEvents.AuthorityUpdateEndpointMetadata,
"AuthUpdEndpointMeta",
],
[
PerformanceEvents.AuthorityUpdateMetadataWithRegionalInformation,
"AuthUpdMetaWithRegInfo",
],
[PerformanceEvents.RegionDiscoveryDetectRegion, "RegDiscDetectReg"],
[
PerformanceEvents.RegionDiscoveryGetRegionFromIMDS,
"RegDiscGetRegFromIMDS",
],
[
PerformanceEvents.RegionDiscoveryGetCurrentVersion,
"RegDiscGetCurrentVer",
],
[PerformanceEvents.AcquireTokenByCodeAsync, "ATByCodeAsync"],
[
PerformanceEvents.GetEndpointMetadataFromNetwork,
"GetEndpointMetaFromNet",
],
[
PerformanceEvents.GetCloudDiscoveryMetadataFromNetworkMeasurement,
"GetCDMetaFromNet",
],
[
PerformanceEvents.HandleRedirectPromiseMeasurement,
"HandleRedirectPromise",
],
[
PerformanceEvents.HandleNativeRedirectPromiseMeasurement,
"HandleNtvRedirectPromise",
],
[
PerformanceEvents.UpdateCloudDiscoveryMetadataMeasurement,
"UpdateCDMeta",
],
[
PerformanceEvents.UsernamePasswordClientAcquireToken,
"UserPassClientAT",
],
[
PerformanceEvents.NativeMessageHandlerHandshake,
"NtvMsgHandlerHandshake",
],
[PerformanceEvents.NativeGenerateAuthResult, "NtvGenAuthRes"],
[PerformanceEvents.RemoveHiddenIframe, "RemoveHiddenIframe"],
[
PerformanceEvents.ClearTokensAndKeysWithClaims,
"ClearTAndKeysWithClaims",
],
[PerformanceEvents.CacheManagerGetRefreshToken, "CacheManagerGetRT"],
[PerformanceEvents.GeneratePkceCodes, "GenPkceCodes"],
[PerformanceEvents.GenerateCodeVerifier, "GenCodeVerifier"],
[
PerformanceEvents.GenerateCodeChallengeFromVerifier,
"GenCodeChallengeFromVerifier",
],
[PerformanceEvents.Sha256Digest, "Sha256Digest"],
[PerformanceEvents.GetRandomValues, "GetRandomValues"],
[PerformanceEvents.GenerateHKDF, "genHKDF"],
[PerformanceEvents.GenerateBaseKey, "genBaseKey"],
[PerformanceEvents.Base64Decode, "b64Decode"],
[PerformanceEvents.UrlEncodeArr, "urlEncArr"],
[PerformanceEvents.Encrypt, "encrypt"],
[PerformanceEvents.Decrypt, "decrypt"],
[PerformanceEvents.GenerateEarKey, "genEarKey"],
[PerformanceEvents.DecryptEarResponse, "decryptEarResp"],
]);
/**
* State of the performance event.
*
* @export
* @enum {number}
*/
const PerformanceEventStatus = {
NotStarted: 0,
InProgress: 1,
Completed: 2,
};
const IntFields = new Set([
"accessTokenSize",
"durationMs",
"idTokenSize",
"matsSilentStatus",
"matsHttpStatus",
"refreshTokenSize",
"queuedTimeMs",
"startTimeMs",
"status",
"multiMatchedAT",
"multiMatchedID",
"multiMatchedRT",
"unencryptedCacheCount",
"encryptedCacheExpiredCount",
"oldAccountCount",
"oldAccessCount",
"oldIdCount",
"oldRefreshCount",
"currAccountCount",
"currAccessCount",
"currIdCount",
"currRefreshCount",
"expiredCacheRemovedCount",
"upgradedCacheCount",
]);
export { IntFields, PerformanceEventAbbreviations, PerformanceEventStatus, PerformanceEvents };
//# sourceMappingURL=PerformanceEvent.mjs.map

View File

@@ -0,0 +1,83 @@
/*! @azure/msal-common v15.13.1 2025-10-29 */
'use strict';
import { PerformanceEventStatus } from './PerformanceEvent.mjs';
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
class StubPerformanceMeasurement {
startMeasurement() {
return;
}
endMeasurement() {
return;
}
flushMeasurement() {
return null;
}
}
class StubPerformanceClient {
generateId() {
return "callback-id";
}
startMeasurement(measureName, correlationId) {
return {
end: () => null,
discard: () => { },
add: () => { },
increment: () => { },
event: {
eventId: this.generateId(),
status: PerformanceEventStatus.InProgress,
authority: "",
libraryName: "",
libraryVersion: "",
clientId: "",
name: measureName,
startTimeMs: Date.now(),
correlationId: correlationId || "",
},
measurement: new StubPerformanceMeasurement(),
};
}
startPerformanceMeasurement() {
return new StubPerformanceMeasurement();
}
calculateQueuedTime() {
return 0;
}
addQueueMeasurement() {
return;
}
setPreQueueTime() {
return;
}
endMeasurement() {
return null;
}
discardMeasurements() {
return;
}
removePerformanceCallback() {
return true;
}
addPerformanceCallback() {
return "";
}
emitEvents() {
return;
}
addFields() {
return;
}
incrementFields() {
return;
}
cacheEventByCorrelationId() {
return;
}
}
export { StubPerformanceClient, StubPerformanceMeasurement };
//# sourceMappingURL=StubPerformanceClient.mjs.map

View File

@@ -0,0 +1,268 @@
/*! @azure/msal-common v15.13.1 2025-10-29 */
'use strict';
import { CacheOutcome, Constants, SERVER_TELEM_CONSTANTS, Separators } from '../../utils/Constants.mjs';
import { AuthError } from '../../error/AuthError.mjs';
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
const skuGroupSeparator = ",";
const skuValueSeparator = "|";
function makeExtraSkuString(params) {
const { skus, libraryName, libraryVersion, extensionName, extensionVersion, } = params;
const skuMap = new Map([
[0, [libraryName, libraryVersion]],
[2, [extensionName, extensionVersion]],
]);
let skuArr = [];
if (skus?.length) {
skuArr = skus.split(skuGroupSeparator);
// Ignore invalid input sku param
if (skuArr.length < 4) {
return skus;
}
}
else {
skuArr = Array.from({ length: 4 }, () => skuValueSeparator);
}
skuMap.forEach((value, key) => {
if (value.length === 2 && value[0]?.length && value[1]?.length) {
setSku({
skuArr,
index: key,
skuName: value[0],
skuVersion: value[1],
});
}
});
return skuArr.join(skuGroupSeparator);
}
function setSku(params) {
const { skuArr, index, skuName, skuVersion } = params;
if (index >= skuArr.length) {
return;
}
skuArr[index] = [skuName, skuVersion].join(skuValueSeparator);
}
/** @internal */
class ServerTelemetryManager {
constructor(telemetryRequest, cacheManager) {
this.cacheOutcome = CacheOutcome.NOT_APPLICABLE;
this.cacheManager = cacheManager;
this.apiId = telemetryRequest.apiId;
this.correlationId = telemetryRequest.correlationId;
this.wrapperSKU = telemetryRequest.wrapperSKU || Constants.EMPTY_STRING;
this.wrapperVer = telemetryRequest.wrapperVer || Constants.EMPTY_STRING;
this.telemetryCacheKey =
SERVER_TELEM_CONSTANTS.CACHE_KEY +
Separators.CACHE_KEY_SEPARATOR +
telemetryRequest.clientId;
}
/**
* API to add MSER Telemetry to request
*/
generateCurrentRequestHeaderValue() {
const request = `${this.apiId}${SERVER_TELEM_CONSTANTS.VALUE_SEPARATOR}${this.cacheOutcome}`;
const platformFieldsArr = [this.wrapperSKU, this.wrapperVer];
const nativeBrokerErrorCode = this.getNativeBrokerErrorCode();
if (nativeBrokerErrorCode?.length) {
platformFieldsArr.push(`broker_error=${nativeBrokerErrorCode}`);
}
const platformFields = platformFieldsArr.join(SERVER_TELEM_CONSTANTS.VALUE_SEPARATOR);
const regionDiscoveryFields = this.getRegionDiscoveryFields();
const requestWithRegionDiscoveryFields = [
request,
regionDiscoveryFields,
].join(SERVER_TELEM_CONSTANTS.VALUE_SEPARATOR);
return [
SERVER_TELEM_CONSTANTS.SCHEMA_VERSION,
requestWithRegionDiscoveryFields,
platformFields,
].join(SERVER_TELEM_CONSTANTS.CATEGORY_SEPARATOR);
}
/**
* API to add MSER Telemetry for the last failed request
*/
generateLastRequestHeaderValue() {
const lastRequests = this.getLastRequests();
const maxErrors = ServerTelemetryManager.maxErrorsToSend(lastRequests);
const failedRequests = lastRequests.failedRequests
.slice(0, 2 * maxErrors)
.join(SERVER_TELEM_CONSTANTS.VALUE_SEPARATOR);
const errors = lastRequests.errors
.slice(0, maxErrors)
.join(SERVER_TELEM_CONSTANTS.VALUE_SEPARATOR);
const errorCount = lastRequests.errors.length;
// Indicate whether this header contains all data or partial data
const overflow = maxErrors < errorCount
? SERVER_TELEM_CONSTANTS.OVERFLOW_TRUE
: SERVER_TELEM_CONSTANTS.OVERFLOW_FALSE;
const platformFields = [errorCount, overflow].join(SERVER_TELEM_CONSTANTS.VALUE_SEPARATOR);
return [
SERVER_TELEM_CONSTANTS.SCHEMA_VERSION,
lastRequests.cacheHits,
failedRequests,
errors,
platformFields,
].join(SERVER_TELEM_CONSTANTS.CATEGORY_SEPARATOR);
}
/**
* API to cache token failures for MSER data capture
* @param error
*/
cacheFailedRequest(error) {
const lastRequests = this.getLastRequests();
if (lastRequests.errors.length >=
SERVER_TELEM_CONSTANTS.MAX_CACHED_ERRORS) {
// Remove a cached error to make room, first in first out
lastRequests.failedRequests.shift(); // apiId
lastRequests.failedRequests.shift(); // correlationId
lastRequests.errors.shift();
}
lastRequests.failedRequests.push(this.apiId, this.correlationId);
if (error instanceof Error && !!error && error.toString()) {
if (error instanceof AuthError) {
if (error.subError) {
lastRequests.errors.push(error.subError);
}
else if (error.errorCode) {
lastRequests.errors.push(error.errorCode);
}
else {
lastRequests.errors.push(error.toString());
}
}
else {
lastRequests.errors.push(error.toString());
}
}
else {
lastRequests.errors.push(SERVER_TELEM_CONSTANTS.UNKNOWN_ERROR);
}
this.cacheManager.setServerTelemetry(this.telemetryCacheKey, lastRequests, this.correlationId);
return;
}
/**
* Update server telemetry cache entry by incrementing cache hit counter
*/
incrementCacheHits() {
const lastRequests = this.getLastRequests();
lastRequests.cacheHits += 1;
this.cacheManager.setServerTelemetry(this.telemetryCacheKey, lastRequests, this.correlationId);
return lastRequests.cacheHits;
}
/**
* Get the server telemetry entity from cache or initialize a new one
*/
getLastRequests() {
const initialValue = {
failedRequests: [],
errors: [],
cacheHits: 0,
};
const lastRequests = this.cacheManager.getServerTelemetry(this.telemetryCacheKey);
return lastRequests || initialValue;
}
/**
* Remove server telemetry cache entry
*/
clearTelemetryCache() {
const lastRequests = this.getLastRequests();
const numErrorsFlushed = ServerTelemetryManager.maxErrorsToSend(lastRequests);
const errorCount = lastRequests.errors.length;
if (numErrorsFlushed === errorCount) {
// All errors were sent on last request, clear Telemetry cache
this.cacheManager.removeItem(this.telemetryCacheKey, this.correlationId);
}
else {
// Partial data was flushed to server, construct a new telemetry cache item with errors that were not flushed
const serverTelemEntity = {
failedRequests: lastRequests.failedRequests.slice(numErrorsFlushed * 2),
errors: lastRequests.errors.slice(numErrorsFlushed),
cacheHits: 0,
};
this.cacheManager.setServerTelemetry(this.telemetryCacheKey, serverTelemEntity, this.correlationId);
}
}
/**
* Returns the maximum number of errors that can be flushed to the server in the next network request
* @param serverTelemetryEntity
*/
static maxErrorsToSend(serverTelemetryEntity) {
let i;
let maxErrors = 0;
let dataSize = 0;
const errorCount = serverTelemetryEntity.errors.length;
for (i = 0; i < errorCount; i++) {
// failedRequests parameter contains pairs of apiId and correlationId, multiply index by 2 to preserve pairs
const apiId = serverTelemetryEntity.failedRequests[2 * i] ||
Constants.EMPTY_STRING;
const correlationId = serverTelemetryEntity.failedRequests[2 * i + 1] ||
Constants.EMPTY_STRING;
const errorCode = serverTelemetryEntity.errors[i] || Constants.EMPTY_STRING;
// Count number of characters that would be added to header, each character is 1 byte. Add 3 at the end to account for separators
dataSize +=
apiId.toString().length +
correlationId.toString().length +
errorCode.length +
3;
if (dataSize < SERVER_TELEM_CONSTANTS.MAX_LAST_HEADER_BYTES) {
// Adding this entry to the header would still keep header size below the limit
maxErrors += 1;
}
else {
break;
}
}
return maxErrors;
}
/**
* Get the region discovery fields
*
* @returns string
*/
getRegionDiscoveryFields() {
const regionDiscoveryFields = [];
regionDiscoveryFields.push(this.regionUsed || Constants.EMPTY_STRING);
regionDiscoveryFields.push(this.regionSource || Constants.EMPTY_STRING);
regionDiscoveryFields.push(this.regionOutcome || Constants.EMPTY_STRING);
return regionDiscoveryFields.join(",");
}
/**
* Update the region discovery metadata
*
* @param regionDiscoveryMetadata
* @returns void
*/
updateRegionDiscoveryMetadata(regionDiscoveryMetadata) {
this.regionUsed = regionDiscoveryMetadata.region_used;
this.regionSource = regionDiscoveryMetadata.region_source;
this.regionOutcome = regionDiscoveryMetadata.region_outcome;
}
/**
* Set cache outcome
*/
setCacheOutcome(cacheOutcome) {
this.cacheOutcome = cacheOutcome;
}
setNativeBrokerErrorCode(errorCode) {
const lastRequests = this.getLastRequests();
lastRequests.nativeBrokerErrorCode = errorCode;
this.cacheManager.setServerTelemetry(this.telemetryCacheKey, lastRequests, this.correlationId);
}
getNativeBrokerErrorCode() {
return this.getLastRequests().nativeBrokerErrorCode;
}
clearNativeBrokerErrorCode() {
const lastRequests = this.getLastRequests();
delete lastRequests.nativeBrokerErrorCode;
this.cacheManager.setServerTelemetry(this.telemetryCacheKey, lastRequests, this.correlationId);
}
static makeExtraSkuString(params) {
return makeExtraSkuString(params);
}
}
export { ServerTelemetryManager };
//# sourceMappingURL=ServerTelemetryManager.mjs.map