Commit iniziale

This commit is contained in:
Paolo A
2025-02-18 22:59:07 +00:00
commit 4bbf35cefb
6879 changed files with 623784 additions and 0 deletions

View File

@@ -0,0 +1,58 @@
import { PerformanceEvent } from "./PerformanceEvent.js";
import { IPerformanceMeasurement } from "./IPerformanceMeasurement.js";
export type PerformanceCallbackFunction = (events: PerformanceEvent[]) => void;
export type InProgressPerformanceEvent = {
end: (event?: Partial<PerformanceEvent>, error?: unknown) => PerformanceEvent | null;
discard: () => void;
add: (fields: {
[key: string]: {} | undefined;
}) => void;
increment: (fields: {
[key: string]: number | undefined;
}) => void;
event: PerformanceEvent;
/**
* @deprecated This attribute will be removed in the next major version
*/
measurement: IPerformanceMeasurement;
};
export interface IPerformanceClient {
startMeasurement(measureName: string, correlationId?: string): InProgressPerformanceEvent;
endMeasurement(event: PerformanceEvent): PerformanceEvent | null;
discardMeasurements(correlationId: string): void;
addFields(fields: {
[key: string]: {} | undefined;
}, correlationId: string): void;
incrementFields(fields: {
[key: string]: number | undefined;
}, correlationId: string): void;
removePerformanceCallback(callbackId: string): boolean;
addPerformanceCallback(callback: PerformanceCallbackFunction): string;
emitEvents(events: PerformanceEvent[], correlationId: string): void;
/**
* @deprecated This method will be removed in the next major version
*/
startPerformanceMeasurement(measureName: string, correlationId: string): IPerformanceMeasurement;
generateId(): string;
calculateQueuedTime(preQueueTime: number, currentTime: number): number;
addQueueMeasurement(eventName: string, correlationId?: string, queueTime?: number, manuallyCompleted?: boolean): void;
setPreQueueTime(eventName: string, correlationId?: string): void;
}
/**
* Queue measurement type
*/
export type QueueMeasurement = {
/**
* Name of performance event
*/
eventName: string;
/**
* Time spent in JS queue
*/
queueTime: number;
/**
* Incomplete pre-queue events are instrumentation bugs that should be fixed.
*/
manuallyCompleted?: boolean;
};
//# sourceMappingURL=IPerformanceClient.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"IPerformanceClient.d.ts","sourceRoot":"","sources":["../../../src/telemetry/performance/IPerformanceClient.ts"],"names":[],"m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IAAI,CAAC;IACR,yBAAyB,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC;IACvD,sBAAsB,CAAC,QAAQ,EAAE,2BAA2B,GAAG,MAAM,CAAC;IACtE,UAAU,CAAC,MAAM,EAAE,gBAAgB,EAAE,EAAE,aAAa,EAAE,MAAM,GAAG,IAAI,CAAC;IACpE;;OAEG;IACH,2BAA2B,CACvB,WAAW,EAAE,MAAM,EACnB,aAAa,EAAE,MAAM,GACtB,uBAAuB,CAAC;IAC3B,UAAU,IAAI,MAAM,CAAC;IACrB,mBAAmB,CAAC,YAAY,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,GAAG,MAAM,CAAC;IACvE,mBAAmB,CACf,SAAS,EAAE,MAAM,EACjB,aAAa,CAAC,EAAE,MAAM,EACtB,SAAS,CAAC,EAAE,MAAM,EAClB,iBAAiB,CAAC,EAAE,OAAO,GAC5B,IAAI,CAAC;IACR,eAAe,CAAC,SAAS,EAAE,MAAM,EAAE,aAAa,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CACpE;AAED;;GAEG;AACH,MAAM,MAAM,gBAAgB,GAAG;IAC3B;;OAEG;IACH,SAAS,EAAE,MAAM,CAAC;IAElB;;OAEG;IACH,SAAS,EAAE,MAAM,CAAC;IAElB;;OAEG;IACH,iBAAiB,CAAC,EAAE,OAAO,CAAC;CAC/B,CAAC"}

View File

@@ -0,0 +1,6 @@
export interface IPerformanceMeasurement {
startMeasurement(): void;
endMeasurement(): void;
flushMeasurement(): number | null;
}
//# sourceMappingURL=IPerformanceMeasurement.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"IPerformanceMeasurement.d.ts","sourceRoot":"","sources":["../../../src/telemetry/performance/IPerformanceMeasurement.ts"],"names":[],"mappings":"AAKA,MAAM,WAAW,uBAAuB;IACpC,gBAAgB,IAAI,IAAI,CAAC;IACzB,cAAc,IAAI,IAAI,CAAC;IACvB,gBAAgB,IAAI,MAAM,GAAG,IAAI,CAAC;CACrC"}

View File

@@ -0,0 +1,243 @@
import { ApplicationTelemetry } from "../../config/ClientConfiguration.js";
import { Logger } from "../../logger/Logger.js";
import { InProgressPerformanceEvent, IPerformanceClient, PerformanceCallbackFunction, QueueMeasurement } from "./IPerformanceClient.js";
import { PerformanceEvent, PerformanceEventContext, PerformanceEvents, PerformanceEventStackedContext } from "./PerformanceEvent.js";
import { IPerformanceMeasurement } from "./IPerformanceMeasurement.js";
export interface PreQueueEvent {
name: PerformanceEvents;
time: number;
}
/**
* Starts context by adding payload to the stack
* @param event {PerformanceEvent}
* @param abbreviations {Map<string, string>} event name abbreviations
* @param stack {?PerformanceEventStackedContext[]} stack
*/
export declare function startContext(event: PerformanceEvent, abbreviations: Map<string, string>, stack?: PerformanceEventStackedContext[]): void;
/**
* Ends context by removing payload from the stack and returning parent or self, if stack is empty, payload
*
* @param event {PerformanceEvent}
* @param abbreviations {Map<string, string>} event name abbreviations
* @param stack {?PerformanceEventStackedContext[]} stack
* @param error {?unknown} error
*/
export declare function endContext(event: PerformanceEvent, abbreviations: Map<string, string>, stack?: PerformanceEventStackedContext[], error?: unknown): PerformanceEventContext | undefined;
/**
* Adds error name and stack trace to the telemetry event
* @param error {Error}
* @param logger {Logger}
* @param event {PerformanceEvent}
* @param stackMaxSize {number} max error stack size to capture
*/
export declare function addError(error: unknown, logger: Logger, event: PerformanceEvent, stackMaxSize?: number): void;
/**
* Compacts error stack into array by fetching N first entries
* @param stack {string} error stack
* @param stackMaxSize {number} max error stack size to capture
* @returns {string[]}
*/
export declare function compactStack(stack: string, stackMaxSize: number): string[];
/**
* Compacts error stack line by shortening file path
* Example: https://localhost/msal-common/src/authority/Authority.js:100:1 -> Authority.js:100:1
* @param line {string} stack line
* @returns {string}
*/
export declare function compactStackLine(line: string): string;
export declare abstract class PerformanceClient implements IPerformanceClient {
protected authority: string;
protected libraryName: string;
protected libraryVersion: string;
protected applicationTelemetry: ApplicationTelemetry;
protected clientId: string;
protected logger: Logger;
protected callbacks: Map<string, PerformanceCallbackFunction>;
/**
* Multiple events with the same correlation id.
* @protected
* @type {Map<string, PerformanceEvent>}
*/
protected eventsByCorrelationId: Map<string, PerformanceEvent>;
/**
* Map of pre-queue times by correlation Id
*
* @protected
* @type {Map<string, PreQueueEvent>}
*/
protected preQueueTimeByCorrelationId: Map<string, PreQueueEvent>;
/**
* Map of queue measurements by correlation Id
*
* @protected
* @type {Map<string, Array<QueueMeasurement>>}
*/
protected queueMeasurements: Map<string, Array<QueueMeasurement>>;
protected intFields: Set<string>;
/**
* Map of stacked events by correlation id.
*
* @protected
*/
protected eventStack: Map<string, PerformanceEventStackedContext[]>;
/**
* Event name abbreviations
*
* @protected
*/
protected abbreviations: Map<string, string>;
/**
* Creates an instance of PerformanceClient,
* an abstract class containing core performance telemetry logic.
*
* @constructor
* @param {string} clientId Client ID of the application
* @param {string} authority Authority used by the application
* @param {Logger} logger Logger used by the application
* @param {string} libraryName Name of the library
* @param {string} libraryVersion Version of the library
* @param {ApplicationTelemetry} applicationTelemetry application name and version
* @param {Set<String>} intFields integer fields to be truncated
* @param {Map<string, string>} abbreviations event name abbreviations
*/
constructor(clientId: string, authority: string, logger: Logger, libraryName: string, libraryVersion: string, applicationTelemetry: ApplicationTelemetry, intFields?: Set<string>, abbreviations?: Map<string, string>);
/**
* Generates and returns a unique id, typically a guid.
*
* @abstract
* @returns {string}
*/
abstract generateId(): string;
/**
* Starts and returns an platform-specific implementation of IPerformanceMeasurement.
* Note: this function can be changed to abstract at the next major version bump.
*
* @param {string} measureName
* @param {string} correlationId
* @returns {IPerformanceMeasurement}
* @deprecated This method will be removed in the next major version
*/
startPerformanceMeasurement(measureName: string, // eslint-disable-line @typescript-eslint/no-unused-vars
correlationId: string): IPerformanceMeasurement;
/**
* Sets pre-queue time by correlation Id
*
* @abstract
* @param {PerformanceEvents} eventName
* @param {string} correlationId
* @returns
*/
abstract setPreQueueTime(eventName: PerformanceEvents, correlationId?: string): void;
/**
* Gets map of pre-queue times by correlation Id
*
* @param {PerformanceEvents} eventName
* @param {string} correlationId
* @returns {number}
*/
getPreQueueTime(eventName: string, correlationId: string): number | void;
/**
* Calculates the difference between current time and time when function was queued.
* Note: It is possible to have 0 as the queue time if the current time and the queued time was the same.
*
* @param {number} preQueueTime
* @param {number} currentTime
* @returns {number}
*/
calculateQueuedTime(preQueueTime: number, currentTime: number): number;
/**
* Adds queue measurement time to QueueMeasurements array for given correlation ID.
*
* @param {PerformanceEvents} eventName
* @param {?string} correlationId
* @param {?number} queueTime
* @param {?boolean} manuallyCompleted - indicator for manually completed queue measurements
* @returns
*/
addQueueMeasurement(eventName: string, correlationId?: string, queueTime?: number, manuallyCompleted?: boolean): void;
/**
* Starts measuring performance for a given operation. Returns a function that should be used to end the measurement.
*
* @param {PerformanceEvents} measureName
* @param {?string} [correlationId]
* @returns {InProgressPerformanceEvent}
*/
startMeasurement(measureName: string, correlationId?: string): InProgressPerformanceEvent;
/**
* Stops measuring the performance for an operation. Should only be called directly by PerformanceClient classes,
* as consumers should instead use the function returned by startMeasurement.
* Adds a new field named as "[event name]DurationMs" for sub-measurements, completes and emits an event
* otherwise.
*
* @param {PerformanceEvent} event
* @param {unknown} error
* @returns {(PerformanceEvent | null)}
*/
endMeasurement(event: PerformanceEvent, error?: unknown): PerformanceEvent | null;
/**
* Saves extra information to be emitted when the measurements are flushed
* @param fields
* @param correlationId
*/
addFields(fields: {
[key: string]: {} | undefined;
}, correlationId: string): void;
/**
* Increment counters to be emitted when the measurements are flushed
* @param fields {string[]}
* @param correlationId {string} correlation identifier
*/
incrementFields(fields: {
[key: string]: number | undefined;
}, correlationId: string): void;
/**
* Upserts event into event cache.
* First key is the correlation id, second key is the event id.
* Allows for events to be grouped by correlation id,
* and to easily allow for properties on them to be updated.
*
* @private
* @param {PerformanceEvent} event
*/
protected cacheEventByCorrelationId(event: PerformanceEvent): void;
private getQueueInfo;
/**
* Removes measurements and aux data for a given correlation id.
*
* @param {string} correlationId
*/
discardMeasurements(correlationId: string): void;
/**
* Registers a callback function to receive performance events.
*
* @param {PerformanceCallbackFunction} callback
* @returns {string}
*/
addPerformanceCallback(callback: PerformanceCallbackFunction): string;
/**
* Removes a callback registered with addPerformanceCallback.
*
* @param {string} callbackId
* @returns {boolean}
*/
removePerformanceCallback(callbackId: string): boolean;
/**
* Emits events to all registered callbacks.
*
* @param {PerformanceEvent[]} events
* @param {?string} [correlationId]
*/
emitEvents(events: PerformanceEvent[], correlationId: string): void;
/**
* Enforce truncation of integral fields in performance event.
* @param {PerformanceEvent} event performance event to update.
*/
private truncateIntegralFields;
/**
* Returns event duration in milliseconds
* @param startTimeMs {number}
* @returns {number}
*/
private getDurationMs;
}
//# sourceMappingURL=PerformanceClient.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"PerformanceClient.d.ts","sourceRoot":"","sources":["../../../src/telemetry/performance/PerformanceClient.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,oBAAoB,EAAE,MAAM,qCAAqC,CAAC;AAC3E,OAAO,EAAE,MAAM,EAAE,MAAM,wBAAwB,CAAC;AAChD,OAAO,EACH,0BAA0B,EAC1B,kBAAkB,EAClB,2BAA2B,EAC3B,gBAAgB,EACnB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAEH,gBAAgB,EAEhB,uBAAuB,EACvB,iBAAiB,EACjB,8BAA8B,EAEjC,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,uBAAuB,EAAE,MAAM,8BAA8B,CAAC;AAOvE,MAAM,WAAW,aAAa;IAC1B,IAAI,EAAE,iBAAiB,CAAC;IACxB,IAAI,EAAE,MAAM,CAAC;CAChB;AAED;;;;;GAKG;AACH,wBAAgB,YAAY,CACxB,KAAK,EAAE,gBAAgB,EACvB,aAAa,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,EAClC,KAAK,CAAC,EAAE,8BAA8B,EAAE,GACzC,IAAI,CAQN;AAED;;;;;;;GAOG;AACH,wBAAgB,UAAU,CACtB,KAAK,EAAE,gBAAgB,EAC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;IACH,cAAc,CACV,KAAK,EAAE,gBAAgB,EACvB,KAAK,CAAC,EAAE,OAAO,GAChB,gBAAgB,GAAG,IAAI;IA6F1B;;;;OAIG;IACH,SAAS,CACL,MAAM,EAAE;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,EAAE,GAAG,SAAS,CAAA;KAAE,EACzC,aAAa,EAAE,MAAM,GACtB,IAAI;IAgBP;;;;OAIG;IACH,eAAe,CACX,MAAM,EAAE;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAAA;KAAE,EAC7C,aAAa,EAAE,MAAM,GACtB,IAAI;IAoBP;;;;;;;;OAQG;IACH,SAAS,CAAC,yBAAyB,CAAC,KAAK,EAAE,gBAAgB,GAAG,IAAI;IAuBlE,OAAO,CAAC,YAAY;IA6BpB;;;;OAIG;IACH,mBAAmB,CAAC,aAAa,EAAE,MAAM,GAAG,IAAI;IA0BhD;;;;;OAKG;IACH,sBAAsB,CAAC,QAAQ,EAAE,2BAA2B,GAAG,MAAM;IAmBrE;;;;;OAKG;IACH,yBAAyB,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO;IAgBtD;;;;;OAKG;IACH,UAAU,CAAC,MAAM,EAAE,gBAAgB,EAAE,EAAE,aAAa,EAAE,MAAM,GAAG,IAAI;IAiBnE;;;OAGG;IACH,OAAO,CAAC,sBAAsB;IAQ9B;;;;OAIG;IACH,OAAO,CAAC,aAAa;CAKxB"}

View File

@@ -0,0 +1,618 @@
/*! @azure/msal-common v15.1.1 2025-02-05 */
'use strict';
import { IntFields, PerformanceEventAbbreviations, PerformanceEventStatus } from './PerformanceEvent.mjs';
import { StubPerformanceMeasurement } from './StubPerformanceClient.mjs';
import { AuthError } from '../../error/AuthError.mjs';
import { CacheError } from '../../error/CacheError.mjs';
import { ServerError } from '../../error/ServerError.mjs';
import { InteractionRequiredAuthError } from '../../error/InteractionRequiredAuthError.mjs';
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Starts context by adding payload to the stack
* @param event {PerformanceEvent}
* @param abbreviations {Map<string, string>} event name abbreviations
* @param stack {?PerformanceEventStackedContext[]} stack
*/
function startContext(event, abbreviations, stack) {
if (!stack) {
return;
}
stack.push({
name: abbreviations.get(event.name) || event.name,
});
}
/**
* Ends context by removing payload from the stack and returning parent or self, if stack is empty, payload
*
* @param event {PerformanceEvent}
* @param abbreviations {Map<string, string>} event name abbreviations
* @param stack {?PerformanceEventStackedContext[]} stack
* @param error {?unknown} error
*/
function endContext(event, abbreviations, stack, error) {
if (!stack?.length) {
return;
}
const peek = (stack) => {
return stack.length ? stack[stack.length - 1] : undefined;
};
const abbrEventName = abbreviations.get(event.name) || event.name;
const top = peek(stack);
if (top?.name !== abbrEventName) {
return;
}
const current = stack?.pop();
if (!current) {
return;
}
const errorCode = error instanceof AuthError
? error.errorCode
: error instanceof Error
? error.name
: undefined;
const subErr = error instanceof AuthError ? error.subError : undefined;
if (errorCode && current.childErr !== errorCode) {
current.err = errorCode;
if (subErr) {
current.subErr = subErr;
}
}
delete current.name;
delete current.childErr;
const context = {
...current,
dur: event.durationMs,
};
if (!event.success) {
context.fail = 1;
}
const parent = peek(stack);
if (!parent) {
return { [abbrEventName]: context };
}
if (errorCode) {
parent.childErr = errorCode;
}
let childName;
if (!parent[abbrEventName]) {
childName = abbrEventName;
}
else {
const siblings = Object.keys(parent).filter((key) => key.startsWith(abbrEventName)).length;
childName = `${abbrEventName}_${siblings + 1}`;
}
parent[childName] = context;
return parent;
}
/**
* Adds error name and stack trace to the telemetry event
* @param error {Error}
* @param logger {Logger}
* @param event {PerformanceEvent}
* @param stackMaxSize {number} max error stack size to capture
*/
function addError(error, logger, event, stackMaxSize = 5) {
if (!(error instanceof Error)) {
logger.trace("PerformanceClient.addErrorStack: Input error is not instance of Error", event.correlationId);
return;
}
else if (error instanceof AuthError) {
event.errorCode = error.errorCode;
event.subErrorCode = error.subError;
if (error instanceof ServerError ||
error instanceof InteractionRequiredAuthError) {
event.serverErrorNo = error.errorNo;
}
return;
}
else if (error instanceof CacheError) {
event.errorCode = error.errorCode;
return;
}
else if (event.errorStack?.length) {
logger.trace("PerformanceClient.addErrorStack: Stack already exist", event.correlationId);
return;
}
else if (!error.stack?.length) {
logger.trace("PerformanceClient.addErrorStack: Input stack is empty", event.correlationId);
return;
}
if (error.stack) {
event.errorStack = compactStack(error.stack, stackMaxSize);
}
event.errorName = error.name;
}
/**
* Compacts error stack into array by fetching N first entries
* @param stack {string} error stack
* @param stackMaxSize {number} max error stack size to capture
* @returns {string[]}
*/
function compactStack(stack, stackMaxSize) {
if (stackMaxSize < 0) {
return [];
}
const stackArr = stack.split("\n") || [];
const res = [];
// Check for a handful of known, common runtime errors and log them (with redaction where applicable).
const firstLine = stackArr[0];
if (firstLine.startsWith("TypeError: Cannot read property") ||
firstLine.startsWith("TypeError: Cannot read properties of") ||
firstLine.startsWith("TypeError: Cannot set property") ||
firstLine.startsWith("TypeError: Cannot set properties of") ||
firstLine.endsWith("is not a function")) {
// These types of errors are not at risk of leaking PII. They will indicate unavailable APIs
res.push(compactStackLine(firstLine));
}
else if (firstLine.startsWith("SyntaxError") ||
firstLine.startsWith("TypeError")) {
// Prevent unintentional leaking of arbitrary info by redacting contents between both single and double quotes
res.push(compactStackLine(
// Example: SyntaxError: Unexpected token 'e', "test" is not valid JSON -> SyntaxError: Unexpected token <redacted>, <redacted> is not valid JSON
firstLine.replace(/['].*[']|["].*["]/g, "<redacted>")));
}
// Get top N stack lines
for (let ix = 1; ix < stackArr.length; ix++) {
if (res.length >= stackMaxSize) {
break;
}
const line = stackArr[ix];
res.push(compactStackLine(line));
}
return res;
}
/**
* Compacts error stack line by shortening file path
* Example: https://localhost/msal-common/src/authority/Authority.js:100:1 -> Authority.js:100:1
* @param line {string} stack line
* @returns {string}
*/
function compactStackLine(line) {
const filePathIx = line.lastIndexOf(" ") + 1;
if (filePathIx < 1) {
return line;
}
const filePath = line.substring(filePathIx);
let fileNameIx = filePath.lastIndexOf("/");
fileNameIx = fileNameIx < 0 ? filePath.lastIndexOf("\\") : fileNameIx;
if (fileNameIx >= 0) {
return (line.substring(0, filePathIx) +
"(" +
filePath.substring(fileNameIx + 1) +
(filePath.charAt(filePath.length - 1) === ")" ? "" : ")")).trimStart();
}
return line.trimStart();
}
class PerformanceClient {
/**
* Creates an instance of PerformanceClient,
* an abstract class containing core performance telemetry logic.
*
* @constructor
* @param {string} clientId Client ID of the application
* @param {string} authority Authority used by the application
* @param {Logger} logger Logger used by the application
* @param {string} libraryName Name of the library
* @param {string} libraryVersion Version of the library
* @param {ApplicationTelemetry} applicationTelemetry application name and version
* @param {Set<String>} intFields integer fields to be truncated
* @param {Map<string, string>} abbreviations event name abbreviations
*/
constructor(clientId, authority, logger, libraryName, libraryVersion, applicationTelemetry, intFields, abbreviations) {
this.authority = authority;
this.libraryName = libraryName;
this.libraryVersion = libraryVersion;
this.applicationTelemetry = applicationTelemetry;
this.clientId = clientId;
this.logger = logger;
this.callbacks = new Map();
this.eventsByCorrelationId = new Map();
this.eventStack = new Map();
this.queueMeasurements = new Map();
this.preQueueTimeByCorrelationId = new Map();
this.intFields = intFields || new Set();
for (const item of IntFields) {
this.intFields.add(item);
}
this.abbreviations = abbreviations || new Map();
for (const [key, value] of PerformanceEventAbbreviations) {
this.abbreviations.set(key, value);
}
}
/**
* Starts and returns an platform-specific implementation of IPerformanceMeasurement.
* Note: this function can be changed to abstract at the next major version bump.
*
* @param {string} measureName
* @param {string} correlationId
* @returns {IPerformanceMeasurement}
* @deprecated This method will be removed in the next major version
*/
startPerformanceMeasurement(measureName, // eslint-disable-line @typescript-eslint/no-unused-vars
correlationId // eslint-disable-line @typescript-eslint/no-unused-vars
) {
return {};
}
/**
* Gets map of pre-queue times by correlation Id
*
* @param {PerformanceEvents} eventName
* @param {string} correlationId
* @returns {number}
*/
getPreQueueTime(eventName, correlationId) {
const preQueueEvent = this.preQueueTimeByCorrelationId.get(correlationId);
if (!preQueueEvent) {
this.logger.trace(`PerformanceClient.getPreQueueTime: no pre-queue times found for correlationId: ${correlationId}, unable to add queue measurement`);
return;
}
else if (preQueueEvent.name !== eventName) {
this.logger.trace(`PerformanceClient.getPreQueueTime: no pre-queue time found for ${eventName}, unable to add queue measurement`);
return;
}
return preQueueEvent.time;
}
/**
* Calculates the difference between current time and time when function was queued.
* Note: It is possible to have 0 as the queue time if the current time and the queued time was the same.
*
* @param {number} preQueueTime
* @param {number} currentTime
* @returns {number}
*/
calculateQueuedTime(preQueueTime, currentTime) {
if (preQueueTime < 1) {
this.logger.trace(`PerformanceClient: preQueueTime should be a positive integer and not ${preQueueTime}`);
return 0;
}
if (currentTime < 1) {
this.logger.trace(`PerformanceClient: currentTime should be a positive integer and not ${currentTime}`);
return 0;
}
if (currentTime < preQueueTime) {
this.logger.trace("PerformanceClient: currentTime is less than preQueueTime, check how time is being retrieved");
return 0;
}
return currentTime - preQueueTime;
}
/**
* Adds queue measurement time to QueueMeasurements array for given correlation ID.
*
* @param {PerformanceEvents} eventName
* @param {?string} correlationId
* @param {?number} queueTime
* @param {?boolean} manuallyCompleted - indicator for manually completed queue measurements
* @returns
*/
addQueueMeasurement(eventName, correlationId, queueTime, manuallyCompleted) {
if (!correlationId) {
this.logger.trace(`PerformanceClient.addQueueMeasurement: correlationId not provided for ${eventName}, cannot add queue measurement`);
return;
}
if (queueTime === 0) {
// Possible for there to be no queue time after calculation
this.logger.trace(`PerformanceClient.addQueueMeasurement: queue time provided for ${eventName} is ${queueTime}`);
}
else if (!queueTime) {
this.logger.trace(`PerformanceClient.addQueueMeasurement: no queue time provided for ${eventName}`);
return;
}
const queueMeasurement = {
eventName,
// Always default queue time to 0 for manually completed (improperly instrumented)
queueTime: manuallyCompleted ? 0 : queueTime,
manuallyCompleted,
};
// Adds to existing correlation Id if present in queueMeasurements
const existingMeasurements = this.queueMeasurements.get(correlationId);
if (existingMeasurements) {
existingMeasurements.push(queueMeasurement);
this.queueMeasurements.set(correlationId, existingMeasurements);
}
else {
// Sets new correlation Id if not present in queueMeasurements
this.logger.trace(`PerformanceClient.addQueueMeasurement: adding correlationId ${correlationId} to queue measurements`);
const measurementArray = [queueMeasurement];
this.queueMeasurements.set(correlationId, measurementArray);
}
// Delete processed pre-queue event.
this.preQueueTimeByCorrelationId.delete(correlationId);
}
/**
* Starts measuring performance for a given operation. Returns a function that should be used to end the measurement.
*
* @param {PerformanceEvents} measureName
* @param {?string} [correlationId]
* @returns {InProgressPerformanceEvent}
*/
startMeasurement(measureName, correlationId) {
// Generate a placeholder correlation if the request does not provide one
const eventCorrelationId = correlationId || this.generateId();
if (!correlationId) {
this.logger.info(`PerformanceClient: No correlation id provided for ${measureName}, generating`, eventCorrelationId);
}
this.logger.trace(`PerformanceClient: Performance measurement started for ${measureName}`, eventCorrelationId);
const inProgressEvent = {
eventId: this.generateId(),
status: PerformanceEventStatus.InProgress,
authority: this.authority,
libraryName: this.libraryName,
libraryVersion: this.libraryVersion,
clientId: this.clientId,
name: measureName,
startTimeMs: Date.now(),
correlationId: eventCorrelationId,
appName: this.applicationTelemetry?.appName,
appVersion: this.applicationTelemetry?.appVersion,
};
// Store in progress events so they can be discarded if not ended properly
this.cacheEventByCorrelationId(inProgressEvent);
startContext(inProgressEvent, this.abbreviations, this.eventStack.get(eventCorrelationId));
// Return the event and functions the caller can use to properly end/flush the measurement
return {
end: (event, error) => {
return this.endMeasurement({
// Initial set of event properties
...inProgressEvent,
// Properties set when event ends
...event,
}, error);
},
discard: () => {
return this.discardMeasurements(inProgressEvent.correlationId);
},
add: (fields) => {
return this.addFields(fields, inProgressEvent.correlationId);
},
increment: (fields) => {
return this.incrementFields(fields, inProgressEvent.correlationId);
},
event: inProgressEvent,
measurement: new StubPerformanceMeasurement(),
};
}
/**
* Stops measuring the performance for an operation. Should only be called directly by PerformanceClient classes,
* as consumers should instead use the function returned by startMeasurement.
* Adds a new field named as "[event name]DurationMs" for sub-measurements, completes and emits an event
* otherwise.
*
* @param {PerformanceEvent} event
* @param {unknown} error
* @returns {(PerformanceEvent | null)}
*/
endMeasurement(event, error) {
const rootEvent = this.eventsByCorrelationId.get(event.correlationId);
if (!rootEvent) {
this.logger.trace(`PerformanceClient: Measurement not found for ${event.eventId}`, event.correlationId);
return null;
}
const isRoot = event.eventId === rootEvent.eventId;
let queueInfo = {
totalQueueTime: 0,
totalQueueCount: 0,
manuallyCompletedCount: 0,
};
event.durationMs = Math.round(event.durationMs || this.getDurationMs(event.startTimeMs));
const context = JSON.stringify(endContext(event, this.abbreviations, this.eventStack.get(rootEvent.correlationId), error));
if (isRoot) {
queueInfo = this.getQueueInfo(event.correlationId);
this.discardMeasurements(rootEvent.correlationId);
}
else {
rootEvent.incompleteSubMeasurements?.delete(event.eventId);
}
this.logger.trace(`PerformanceClient: Performance measurement ended for ${event.name}: ${event.durationMs} ms`, event.correlationId);
if (error) {
addError(error, this.logger, rootEvent);
}
// Add sub-measurement attribute to root event.
if (!isRoot) {
rootEvent[event.name + "DurationMs"] = Math.floor(event.durationMs);
return { ...rootEvent };
}
if (isRoot &&
!error &&
(rootEvent.errorCode || rootEvent.subErrorCode)) {
this.logger.trace(`PerformanceClient: Remove error and sub-error codes for root event ${event.name} as intermediate error was successfully handled`, event.correlationId);
rootEvent.errorCode = undefined;
rootEvent.subErrorCode = undefined;
}
let finalEvent = { ...rootEvent, ...event };
let incompleteSubsCount = 0;
// Incomplete sub-measurements are discarded. They are likely an instrumentation bug that should be fixed.
finalEvent.incompleteSubMeasurements?.forEach((subMeasurement) => {
this.logger.trace(`PerformanceClient: Incomplete submeasurement ${subMeasurement.name} found for ${event.name}`, finalEvent.correlationId);
incompleteSubsCount++;
});
finalEvent.incompleteSubMeasurements = undefined;
finalEvent = {
...finalEvent,
queuedTimeMs: queueInfo.totalQueueTime,
queuedCount: queueInfo.totalQueueCount,
queuedManuallyCompletedCount: queueInfo.manuallyCompletedCount,
status: PerformanceEventStatus.Completed,
incompleteSubsCount,
context,
};
this.truncateIntegralFields(finalEvent);
this.emitEvents([finalEvent], event.correlationId);
return finalEvent;
}
/**
* Saves extra information to be emitted when the measurements are flushed
* @param fields
* @param correlationId
*/
addFields(fields, correlationId) {
this.logger.trace("PerformanceClient: Updating static fields");
const event = this.eventsByCorrelationId.get(correlationId);
if (event) {
this.eventsByCorrelationId.set(correlationId, {
...event,
...fields,
});
}
else {
this.logger.trace("PerformanceClient: Event not found for", correlationId);
}
}
/**
* Increment counters to be emitted when the measurements are flushed
* @param fields {string[]}
* @param correlationId {string} correlation identifier
*/
incrementFields(fields, correlationId) {
this.logger.trace("PerformanceClient: Updating counters");
const event = this.eventsByCorrelationId.get(correlationId);
if (event) {
for (const counter in fields) {
if (!event.hasOwnProperty(counter)) {
event[counter] = 0;
}
else if (isNaN(Number(event[counter]))) {
return;
}
event[counter] += fields[counter];
}
}
else {
this.logger.trace("PerformanceClient: Event not found for", correlationId);
}
}
/**
* Upserts event into event cache.
* First key is the correlation id, second key is the event id.
* Allows for events to be grouped by correlation id,
* and to easily allow for properties on them to be updated.
*
* @private
* @param {PerformanceEvent} event
*/
cacheEventByCorrelationId(event) {
const rootEvent = this.eventsByCorrelationId.get(event.correlationId);
if (rootEvent) {
this.logger.trace(`PerformanceClient: Performance measurement for ${event.name} added/updated`, event.correlationId);
rootEvent.incompleteSubMeasurements =
rootEvent.incompleteSubMeasurements || new Map();
rootEvent.incompleteSubMeasurements.set(event.eventId, {
name: event.name,
startTimeMs: event.startTimeMs,
});
}
else {
this.logger.trace(`PerformanceClient: Performance measurement for ${event.name} started`, event.correlationId);
this.eventsByCorrelationId.set(event.correlationId, { ...event });
this.eventStack.set(event.correlationId, []);
}
}
getQueueInfo(correlationId) {
const queueMeasurementForCorrelationId = this.queueMeasurements.get(correlationId);
if (!queueMeasurementForCorrelationId) {
this.logger.trace(`PerformanceClient: no queue measurements found for for correlationId: ${correlationId}`);
}
let totalQueueTime = 0;
let totalQueueCount = 0;
let manuallyCompletedCount = 0;
queueMeasurementForCorrelationId?.forEach((measurement) => {
totalQueueTime += measurement.queueTime;
totalQueueCount++;
manuallyCompletedCount += measurement.manuallyCompleted ? 1 : 0;
});
return {
totalQueueTime,
totalQueueCount,
manuallyCompletedCount,
};
}
/**
* Removes measurements and aux data for a given correlation id.
*
* @param {string} correlationId
*/
discardMeasurements(correlationId) {
this.logger.trace("PerformanceClient: Performance measurements discarded", correlationId);
this.eventsByCorrelationId.delete(correlationId);
this.logger.trace("PerformanceClient: QueueMeasurements discarded", correlationId);
this.queueMeasurements.delete(correlationId);
this.logger.trace("PerformanceClient: Pre-queue times discarded", correlationId);
this.preQueueTimeByCorrelationId.delete(correlationId);
this.logger.trace("PerformanceClient: Event stack discarded", correlationId);
this.eventStack.delete(correlationId);
}
/**
* Registers a callback function to receive performance events.
*
* @param {PerformanceCallbackFunction} callback
* @returns {string}
*/
addPerformanceCallback(callback) {
for (const [id, cb] of this.callbacks) {
if (cb.toString() === callback.toString()) {
this.logger.warning(`PerformanceClient: Performance callback is already registered with id: ${id}`);
return id;
}
}
const callbackId = this.generateId();
this.callbacks.set(callbackId, callback);
this.logger.verbose(`PerformanceClient: Performance callback registered with id: ${callbackId}`);
return callbackId;
}
/**
* Removes a callback registered with addPerformanceCallback.
*
* @param {string} callbackId
* @returns {boolean}
*/
removePerformanceCallback(callbackId) {
const result = this.callbacks.delete(callbackId);
if (result) {
this.logger.verbose(`PerformanceClient: Performance callback ${callbackId} removed.`);
}
else {
this.logger.verbose(`PerformanceClient: Performance callback ${callbackId} not removed.`);
}
return result;
}
/**
* Emits events to all registered callbacks.
*
* @param {PerformanceEvent[]} events
* @param {?string} [correlationId]
*/
emitEvents(events, correlationId) {
this.logger.verbose("PerformanceClient: Emitting performance events", correlationId);
this.callbacks.forEach((callback, callbackId) => {
this.logger.trace(`PerformanceClient: Emitting event to callback ${callbackId}`, correlationId);
callback.apply(null, [events]);
});
}
/**
* Enforce truncation of integral fields in performance event.
* @param {PerformanceEvent} event performance event to update.
*/
truncateIntegralFields(event) {
this.intFields.forEach((key) => {
if (key in event && typeof event[key] === "number") {
event[key] = Math.floor(event[key]);
}
});
}
/**
* Returns event duration in milliseconds
* @param startTimeMs {number}
* @returns {number}
*/
getDurationMs(startTimeMs) {
const durationMs = Date.now() - startTimeMs;
// Handle clock skew
return durationMs < 0 ? durationMs : 0;
}
}
export { PerformanceClient, addError, compactStack, compactStackLine, endContext, startContext };
//# sourceMappingURL=PerformanceClient.mjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,540 @@
/**
* Enumeration of operations that are instrumented by have their performance measured by the PerformanceClient.
*
* @export
* @enum {number}
*/
export declare const PerformanceEvents: {
/**
* acquireTokenByCode API (msal-browser and msal-node).
* Used to acquire tokens by trading an authorization code against the token endpoint.
*/
readonly AcquireTokenByCode: "acquireTokenByCode";
/**
* acquireTokenByRefreshToken API (msal-browser and msal-node).
* Used to renew an access token using a refresh token against the token endpoint.
*/
readonly AcquireTokenByRefreshToken: "acquireTokenByRefreshToken";
/**
* acquireTokenSilent API (msal-browser and msal-node).
* Used to silently acquire a new access token (from the cache or the network).
*/
readonly AcquireTokenSilent: "acquireTokenSilent";
/**
* acquireTokenSilentAsync (msal-browser).
* Internal API for acquireTokenSilent.
*/
readonly AcquireTokenSilentAsync: "acquireTokenSilentAsync";
/**
* acquireTokenPopup (msal-browser).
* Used to acquire a new access token interactively through pop ups
*/
readonly AcquireTokenPopup: "acquireTokenPopup";
/**
* acquireTokenPreRedirect (msal-browser).
* First part of the redirect flow.
* Used to acquire a new access token interactively through redirects.
*/
readonly AcquireTokenPreRedirect: "acquireTokenPreRedirect";
/**
* acquireTokenRedirect (msal-browser).
* Second part of the redirect flow.
* Used to acquire a new access token interactively through redirects.
*/
readonly 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.
*/
readonly CryptoOptsGetPublicKeyThumbprint: "cryptoOptsGetPublicKeyThumbprint";
/**
* signJwt API in CryptoOpts class (msal-browser).
* Used to signed a pop token.
*/
readonly CryptoOptsSignJwt: "cryptoOptsSignJwt";
/**
* acquireToken API in the SilentCacheClient class (msal-browser).
* Used to read access tokens from the cache.
*/
readonly 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.
*/
readonly SilentIframeClientAcquireToken: "silentIframeClientAcquireToken";
readonly AwaitConcurrentIframe: "awaitConcurrentIframe";
/**
* acquireToken API in SilentRereshClient (msal-browser).
* Used to acquire a new set of tokens from the token endpoint using a refresh token.
*/
readonly SilentRefreshClientAcquireToken: "silentRefreshClientAcquireToken";
/**
* ssoSilent API (msal-browser).
* Used to silently acquire an authorization code and set of tokens using a hidden iframe.
*/
readonly SsoSilent: "ssoSilent";
/**
* getDiscoveredAuthority API in StandardInteractionClient class (msal-browser).
* Used to load authority metadata for a request.
*/
readonly StandardInteractionClientGetDiscoveredAuthority: "standardInteractionClientGetDiscoveredAuthority";
/**
* acquireToken APIs in msal-browser.
* Used to make an /authorize endpoint call with native brokering enabled.
*/
readonly FetchAccountIdWithNativeBroker: "fetchAccountIdWithNativeBroker";
/**
* acquireToken API in NativeInteractionClient class (msal-browser).
* Used to acquire a token from Native component when native brokering is enabled.
*/
readonly NativeInteractionClientAcquireToken: "nativeInteractionClientAcquireToken";
/**
* Time spent creating default headers for requests to token endpoint
*/
readonly BaseClientCreateTokenRequestHeaders: "baseClientCreateTokenRequestHeaders";
/**
* Time spent sending/waiting for the response of a request to the token endpoint
*/
readonly NetworkClientSendPostRequestAsync: "networkClientSendPostRequestAsync";
readonly RefreshTokenClientExecutePostToTokenEndpoint: "refreshTokenClientExecutePostToTokenEndpoint";
readonly AuthorizationCodeClientExecutePostToTokenEndpoint: "authorizationCodeClientExecutePostToTokenEndpoint";
/**
* Used to measure the time taken for completing embedded-broker handshake (PW-Broker).
*/
readonly BrokerHandhshake: "brokerHandshake";
/**
* acquireTokenByRefreshToken API in BrokerClientApplication (PW-Broker) .
*/
readonly AcquireTokenByRefreshTokenInBroker: "acquireTokenByRefreshTokenInBroker";
/**
* Time taken for token acquisition by broker
*/
readonly AcquireTokenByBroker: "acquireTokenByBroker";
/**
* Time spent on the network for refresh token acquisition
*/
readonly RefreshTokenClientExecuteTokenRequest: "refreshTokenClientExecuteTokenRequest";
/**
* Time taken for acquiring refresh token , records RT size
*/
readonly RefreshTokenClientAcquireToken: "refreshTokenClientAcquireToken";
/**
* Time taken for acquiring cached refresh token
*/
readonly RefreshTokenClientAcquireTokenWithCachedRefreshToken: "refreshTokenClientAcquireTokenWithCachedRefreshToken";
/**
* acquireTokenByRefreshToken API in RefreshTokenClient (msal-common).
*/
readonly RefreshTokenClientAcquireTokenByRefreshToken: "refreshTokenClientAcquireTokenByRefreshToken";
/**
* Helper function to create token request body in RefreshTokenClient (msal-common).
*/
readonly RefreshTokenClientCreateTokenRequestBody: "refreshTokenClientCreateTokenRequestBody";
/**
* acquireTokenFromCache (msal-browser).
* Internal API for acquiring token from cache
*/
readonly AcquireTokenFromCache: "acquireTokenFromCache";
readonly SilentFlowClientAcquireCachedToken: "silentFlowClientAcquireCachedToken";
readonly SilentFlowClientGenerateResultFromCacheRecord: "silentFlowClientGenerateResultFromCacheRecord";
/**
* acquireTokenBySilentIframe (msal-browser).
* Internal API for acquiring token by silent Iframe
*/
readonly AcquireTokenBySilentIframe: "acquireTokenBySilentIframe";
/**
* Internal API for initializing base request in BaseInteractionClient (msal-browser)
*/
readonly InitializeBaseRequest: "initializeBaseRequest";
/**
* Internal API for initializing silent request in SilentCacheClient (msal-browser)
*/
readonly InitializeSilentRequest: "initializeSilentRequest";
readonly InitializeClientApplication: "initializeClientApplication";
readonly InitializeCache: "initializeCache";
/**
* Helper function in SilentIframeClient class (msal-browser).
*/
readonly SilentIframeClientTokenHelper: "silentIframeClientTokenHelper";
/**
* SilentHandler
*/
readonly SilentHandlerInitiateAuthRequest: "silentHandlerInitiateAuthRequest";
readonly SilentHandlerMonitorIframeForHash: "silentHandlerMonitorIframeForHash";
readonly SilentHandlerLoadFrame: "silentHandlerLoadFrame";
readonly SilentHandlerLoadFrameSync: "silentHandlerLoadFrameSync";
/**
* Helper functions in StandardInteractionClient class (msal-browser)
*/
readonly StandardInteractionClientCreateAuthCodeClient: "standardInteractionClientCreateAuthCodeClient";
readonly StandardInteractionClientGetClientConfiguration: "standardInteractionClientGetClientConfiguration";
readonly StandardInteractionClientInitializeAuthorizationRequest: "standardInteractionClientInitializeAuthorizationRequest";
readonly StandardInteractionClientInitializeAuthorizationCodeRequest: "standardInteractionClientInitializeAuthorizationCodeRequest";
/**
* getAuthCodeUrl API (msal-browser and msal-node).
*/
readonly GetAuthCodeUrl: "getAuthCodeUrl";
/**
* Functions from InteractionHandler (msal-browser)
*/
readonly HandleCodeResponseFromServer: "handleCodeResponseFromServer";
readonly HandleCodeResponse: "handleCodeResponse";
readonly UpdateTokenEndpointAuthority: "updateTokenEndpointAuthority";
/**
* APIs in Authorization Code Client (msal-common)
*/
readonly AuthClientAcquireToken: "authClientAcquireToken";
readonly AuthClientExecuteTokenRequest: "authClientExecuteTokenRequest";
readonly AuthClientCreateTokenRequestBody: "authClientCreateTokenRequestBody";
readonly AuthClientCreateQueryString: "authClientCreateQueryString";
/**
* Generate functions in PopTokenGenerator (msal-common)
*/
readonly PopTokenGenerateCnf: "popTokenGenerateCnf";
readonly PopTokenGenerateKid: "popTokenGenerateKid";
/**
* handleServerTokenResponse API in ResponseHandler (msal-common)
*/
readonly HandleServerTokenResponse: "handleServerTokenResponse";
readonly DeserializeResponse: "deserializeResponse";
/**
* Authority functions
*/
readonly AuthorityFactoryCreateDiscoveredInstance: "authorityFactoryCreateDiscoveredInstance";
readonly AuthorityResolveEndpointsAsync: "authorityResolveEndpointsAsync";
readonly AuthorityResolveEndpointsFromLocalSources: "authorityResolveEndpointsFromLocalSources";
readonly AuthorityGetCloudDiscoveryMetadataFromNetwork: "authorityGetCloudDiscoveryMetadataFromNetwork";
readonly AuthorityUpdateCloudDiscoveryMetadata: "authorityUpdateCloudDiscoveryMetadata";
readonly AuthorityGetEndpointMetadataFromNetwork: "authorityGetEndpointMetadataFromNetwork";
readonly AuthorityUpdateEndpointMetadata: "authorityUpdateEndpointMetadata";
readonly AuthorityUpdateMetadataWithRegionalInformation: "authorityUpdateMetadataWithRegionalInformation";
/**
* Region Discovery functions
*/
readonly RegionDiscoveryDetectRegion: "regionDiscoveryDetectRegion";
readonly RegionDiscoveryGetRegionFromIMDS: "regionDiscoveryGetRegionFromIMDS";
readonly RegionDiscoveryGetCurrentVersion: "regionDiscoveryGetCurrentVersion";
readonly AcquireTokenByCodeAsync: "acquireTokenByCodeAsync";
readonly GetEndpointMetadataFromNetwork: "getEndpointMetadataFromNetwork";
readonly GetCloudDiscoveryMetadataFromNetworkMeasurement: "getCloudDiscoveryMetadataFromNetworkMeasurement";
readonly HandleRedirectPromiseMeasurement: "handleRedirectPromise";
readonly HandleNativeRedirectPromiseMeasurement: "handleNativeRedirectPromise";
readonly UpdateCloudDiscoveryMetadataMeasurement: "updateCloudDiscoveryMetadataMeasurement";
readonly UsernamePasswordClientAcquireToken: "usernamePasswordClientAcquireToken";
readonly NativeMessageHandlerHandshake: "nativeMessageHandlerHandshake";
readonly NativeGenerateAuthResult: "nativeGenerateAuthResult";
readonly RemoveHiddenIframe: "removeHiddenIframe";
/**
* Cache operations
*/
readonly ClearTokensAndKeysWithClaims: "clearTokensAndKeysWithClaims";
readonly CacheManagerGetRefreshToken: "cacheManagerGetRefreshToken";
readonly ImportExistingCache: "importExistingCache";
readonly SetUserData: "setUserData";
readonly LocalStorageUpdated: "localStorageUpdated";
/**
* Crypto Operations
*/
readonly GeneratePkceCodes: "generatePkceCodes";
readonly GenerateCodeVerifier: "generateCodeVerifier";
readonly GenerateCodeChallengeFromVerifier: "generateCodeChallengeFromVerifier";
readonly Sha256Digest: "sha256Digest";
readonly GetRandomValues: "getRandomValues";
readonly GenerateHKDF: "generateHKDF";
readonly GenerateBaseKey: "generateBaseKey";
readonly Base64Decode: "base64Decode";
readonly UrlEncodeArr: "urlEncodeArr";
readonly Encrypt: "encrypt";
readonly Decrypt: "decrypt";
};
export type PerformanceEvents = (typeof PerformanceEvents)[keyof typeof PerformanceEvents];
export declare const PerformanceEventAbbreviations: ReadonlyMap<string, string>;
/**
* State of the performance event.
*
* @export
* @enum {number}
*/
export declare const PerformanceEventStatus: {
readonly NotStarted: 0;
readonly InProgress: 1;
readonly Completed: 2;
};
export type PerformanceEventStatus = (typeof PerformanceEventStatus)[keyof typeof PerformanceEventStatus];
export type SubMeasurement = {
name: string;
startTimeMs: number;
};
/**
* Performance measurement taken by the library, including metadata about the request and application.
*
* @export
* @typedef {PerformanceEvent}
*/
export type PerformanceEvent = {
/**
* Unique id for the event
*
* @type {string}
*/
eventId: string;
/**
* State of the perforance measure.
*
* @type {PerformanceEventStatus}
*/
status: PerformanceEventStatus;
/**
* Login authority used for the request
*
* @type {string}
*/
authority: string;
/**
* Client id for the application
*
* @type {string}
*/
clientId: string;
/**
* Correlation ID used for the request
*
* @type {string}
*/
correlationId: string;
/**
* End-to-end duration in milliseconds.
* @date 3/22/2022 - 3:40:05 PM
*
* @type {number}
*/
durationMs?: number;
/**
* Visibility of the page when the event completed.
* Read from: https://developer.mozilla.org/docs/Web/API/Page_Visibility_API
*
* @type {?(string | null)}
*/
endPageVisibility?: string | null;
/**
* Whether the result was retrieved from the cache.
*
* @type {(boolean | null)}
*/
fromCache?: boolean | null;
/**
* Event name (usually in the form of classNameFunctionName)
*
* @type {string}
*/
name: string;
/**
* Visibility of the page when the event completed.
* Read from: https://developer.mozilla.org/docs/Web/API/Page_Visibility_API
*
* @type {?(string | null)}
*/
startPageVisibility?: string | null;
/**
* Unix millisecond timestamp when the event was initiated.
*
* @type {number}
*/
startTimeMs: number;
/**
* Whether or the operation completed successfully.
*
* @type {(boolean | null)}
*/
success?: boolean | null;
/**
* Add specific error code in case of failure
*
* @type {string}
*/
errorCode?: string;
/**
* Add specific sub error code in case of failure
*
* @type {string}
*/
subErrorCode?: string;
/**
* Server error number
*/
serverErrorNo?: string;
/**
* Name of the library used for the operation.
*
* @type {string}
*/
libraryName: string;
/**
* Version of the library used for the operation.
*
* @type {string}
*/
libraryVersion: string;
/**
* Whether the response is from a native component (e.g., WAM)
*
* @type {?boolean}
*/
isNativeBroker?: boolean;
/**
* Request ID returned from the response
*
* @type {?string}
*/
requestId?: string;
/**
* Cache lookup policy
*
* @type {?number}
*/
cacheLookupPolicy?: number | undefined;
/**
* Cache Outcome
* @type {?number}
*/
cacheOutcome?: number;
/**
* Amount of time spent in the JS queue in milliseconds.
*
* @type {?number}
*/
queuedTimeMs?: number;
/**
* Sub-measurements for internal use. To be deleted before flushing.
*/
incompleteSubMeasurements?: Map<string, SubMeasurement>;
visibilityChangeCount?: number;
incompleteSubsCount?: number;
/**
* CorrelationId of the in progress iframe request that was awaited
*/
awaitIframeCorrelationId?: string;
/**
* Amount of times queued in the JS event queue.
*
* @type {?number}
*/
queuedCount?: number;
/**
* Amount of manually completed queue events.
*
* @type {?number}
*/
queuedManuallyCompletedCount?: number;
/**
* Size of the id token
*
* @type {number}
*/
idTokenSize?: number;
/**
*
* Size of the access token
*
* @type {number}
*/
accessTokenSize?: number;
/**
*
* Size of the refresh token
*
* @type {number}
*/
refreshTokenSize?: number | undefined;
/**
* Application name as specified by the app.
*
* @type {?string}
*/
appName?: string;
/**
* Application version as specified by the app.
*
* @type {?string}
*/
appVersion?: string;
/**
* The following are fields that may be emitted in native broker scenarios
*/
extensionId?: string;
extensionVersion?: string;
matsBrokerVersion?: string;
matsAccountJoinOnStart?: string;
matsAccountJoinOnEnd?: string;
matsDeviceJoin?: string;
matsPromptBehavior?: string;
matsApiErrorCode?: number;
matsUiVisible?: boolean;
matsSilentCode?: number;
matsSilentBiSubCode?: number;
matsSilentMessage?: string;
matsSilentStatus?: number;
matsHttpStatus?: number;
matsHttpEventCount?: number;
/**
* Http POST metadata
*/
httpVerToken?: string;
httpStatus?: number;
contentTypeHeader?: string;
contentLengthHeader?: string;
/**
* Platform broker fields
*/
allowPlatformBroker?: boolean;
extensionInstalled?: boolean;
extensionHandshakeTimeoutMs?: number;
extensionHandshakeTimedOut?: boolean;
/**
* Nested App Auth Fields
*/
nestedAppAuthRequest?: boolean;
/**
* Multiple matched access/id/refresh tokens in the cache
*/
multiMatchedAT?: number;
multiMatchedID?: number;
multiMatchedRT?: number;
errorName?: string;
errorStack?: string[];
context?: string;
cacheRtCount?: number;
cacheIdCount?: number;
cacheAtCount?: number;
scenarioId?: string;
accountType?: "AAD" | "MSA" | "B2C";
/**
* Server error that triggers a request retry
*
* @type {string}
*/
retryError?: string;
embeddedClientId?: string;
embeddedRedirectUri?: string;
isAsyncPopup?: boolean;
rtExpiresOnMs?: number;
sidFromClaims?: boolean;
sidFromRequest?: boolean;
loginHintFromRequest?: boolean;
loginHintFromUpn?: boolean;
loginHintFromClaim?: boolean;
domainHintFromRequest?: boolean;
prompt?: string;
};
export type PerformanceEventContext = {
dur?: number;
err?: string;
subErr?: string;
fail?: number;
};
export type PerformanceEventStackedContext = PerformanceEventContext & {
name?: string;
childErr?: string;
};
export declare const IntFields: ReadonlySet<string>;
//# sourceMappingURL=PerformanceEvent.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"PerformanceEvent.d.ts","sourceRoot":"","sources":["../../../src/telemetry/performance/PerformanceEvent.ts"],"names":[],"mappings":"AAKA;;;;;GAKG;AACH,eAAO,MAAM,iBAAiB;IAC1B;;;OAGG;;IAGH;;;OAGG;;IAGH;;;OAGG;;IAGH;;;OAGG;;IAGH;;;OAGG;;IAGH;;;;OAIG;;IAGH;;;;OAIG;;IAGH;;;OAGG;;IAGH;;;OAGG;;IAGH;;;OAGG;;IAGH;;;OAGG;;;IAIH;;;OAGG;;IAGH;;;OAGG;;IAGH;;;OAGG;;IAIH;;;OAGG;;IAGH;;;OAGG;;IAEH;;OAEG;;IAEH;;OAEG;;;;IAMH;;OAEG;;IA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+1,512 @@
/*! @azure/msal-common v15.1.1 2025-02-05 */
'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",
StandardInteractionClientInitializeAuthorizationCodeRequest: "standardInteractionClientInitializeAuthorizationCodeRequest",
/**
* getAuthCodeUrl API (msal-browser and msal-node).
*/
GetAuthCodeUrl: "getAuthCodeUrl",
/**
* Functions from InteractionHandler (msal-browser)
*/
HandleCodeResponseFromServer: "handleCodeResponseFromServer",
HandleCodeResponse: "handleCodeResponse",
UpdateTokenEndpointAuthority: "updateTokenEndpointAuthority",
/**
* APIs in Authorization Code Client (msal-common)
*/
AuthClientAcquireToken: "authClientAcquireToken",
AuthClientExecuteTokenRequest: "authClientExecuteTokenRequest",
AuthClientCreateTokenRequestBody: "authClientCreateTokenRequestBody",
AuthClientCreateQueryString: "authClientCreateQueryString",
/**
* 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",
};
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.StandardInteractionClientInitializeAuthorizationCodeRequest,
"StdIntClientInitAuthCodeReq",
],
[PerformanceEvents.GetAuthCodeUrl, "GetAuthCodeUrl"],
[
PerformanceEvents.HandleCodeResponseFromServer,
"HandleCodeResFromServer",
],
[PerformanceEvents.HandleCodeResponse, "HandleCodeResp"],
[PerformanceEvents.UpdateTokenEndpointAuthority, "UpdTEndpointAuth"],
[PerformanceEvents.AuthClientAcquireToken, "AuthClientAT"],
[PerformanceEvents.AuthClientExecuteTokenRequest, "AuthClientExecTReq"],
[
PerformanceEvents.AuthClientCreateTokenRequestBody,
"AuthClientCreateTReqBody",
],
[
PerformanceEvents.AuthClientCreateQueryString,
"AuthClientCreateQueryStr",
],
[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"],
]);
/**
* 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",
]);
export { IntFields, PerformanceEventAbbreviations, PerformanceEventStatus, PerformanceEvents };
//# sourceMappingURL=PerformanceEvent.mjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,25 @@
import { IPerformanceClient, InProgressPerformanceEvent } from "./IPerformanceClient.js";
import { IPerformanceMeasurement } from "./IPerformanceMeasurement.js";
import { PerformanceEvent } from "./PerformanceEvent.js";
export declare class StubPerformanceMeasurement implements IPerformanceMeasurement {
startMeasurement(): void;
endMeasurement(): void;
flushMeasurement(): number | null;
}
export declare class StubPerformanceClient implements IPerformanceClient {
generateId(): string;
startMeasurement(measureName: string, correlationId?: string | undefined): InProgressPerformanceEvent;
startPerformanceMeasurement(): IPerformanceMeasurement;
calculateQueuedTime(): number;
addQueueMeasurement(): void;
setPreQueueTime(): void;
endMeasurement(): PerformanceEvent | null;
discardMeasurements(): void;
removePerformanceCallback(): boolean;
addPerformanceCallback(): string;
emitEvents(): void;
addFields(): void;
incrementFields(): void;
cacheEventByCorrelationId(): void;
}
//# sourceMappingURL=StubPerformanceClient.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"StubPerformanceClient.d.ts","sourceRoot":"","sources":["../../../src/telemetry/performance/StubPerformanceClient.ts"],"names":[],"mappings":"AAKA,OAAO,EACH,kBAAkB,EAClB,0BAA0B,EAC7B,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,uBAAuB,EAAE,MAAM,8BAA8B,CAAC;AACvE,OAAO,EACH,gBAAgB,EAEnB,MAAM,uBAAuB,CAAC;AAE/B,qBAAa,0BAA2B,YAAW,uBAAuB;IACtE,gBAAgB,IAAI,IAAI;IAGxB,cAAc,IAAI,IAAI;IAGtB,gBAAgB,IAAI,MAAM,GAAG,IAAI;CAGpC;AAED,qBAAa,qBAAsB,YAAW,kBAAkB;IAC5D,UAAU,IAAI,MAAM;IAIpB,gBAAgB,CACZ,WAAW,EAAE,MAAM,EACnB,aAAa,CAAC,EAAE,MAAM,GAAG,SAAS,GACnC,0BAA0B;IAqB7B,2BAA2B,IAAI,uBAAuB;IAGtD,mBAAmB,IAAI,MAAM;IAI7B,mBAAmB,IAAI,IAAI;IAI3B,eAAe,IAAI,IAAI;IAIvB,cAAc,IAAI,gBAAgB,GAAG,IAAI;IAIzC,mBAAmB,IAAI,IAAI;IAI3B,yBAAyB,IAAI,OAAO;IAIpC,sBAAsB,IAAI,MAAM;IAIhC,UAAU,IAAI,IAAI;IAIlB,SAAS,IAAI,IAAI;IAIjB,eAAe,IAAI,IAAI;IAIvB,yBAAyB,IAAI,IAAI;CAGpC"}

View File

@@ -0,0 +1,83 @@
/*! @azure/msal-common v15.1.1 2025-02-05 */
'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 @@
{"version":3,"file":"StubPerformanceClient.mjs","sources":["../../../src/telemetry/performance/StubPerformanceClient.ts"],"sourcesContent":[null],"names":[],"mappings":";;;;AAAA;;;AAGG;MAYU,0BAA0B,CAAA;IACnC,gBAAgB,GAAA;QACZ,OAAO;KACV;IACD,cAAc,GAAA;QACV,OAAO;KACV;IACD,gBAAgB,GAAA;AACZ,QAAA,OAAO,IAAI,CAAC;KACf;AACJ,CAAA;MAEY,qBAAqB,CAAA;IAC9B,UAAU,GAAA;AACN,QAAA,OAAO,aAAa,CAAC;KACxB;IAED,gBAAgB,CACZ,WAAmB,EACnB,aAAkC,EAAA;QAElC,OAAO;AACH,YAAA,GAAG,EAAE,MAAM,IAAI;AACf,YAAA,OAAO,EAAE,MAAK,GAAG;AACjB,YAAA,GAAG,EAAE,MAAK,GAAG;AACb,YAAA,SAAS,EAAE,MAAK,GAAG;AACnB,YAAA,KAAK,EAAE;AACH,gBAAA,OAAO,EAAE,IAAI,CAAC,UAAU,EAAE;gBAC1B,MAAM,EAAE,sBAAsB,CAAC,UAAU;AACzC,gBAAA,SAAS,EAAE,EAAE;AACb,gBAAA,WAAW,EAAE,EAAE;AACf,gBAAA,cAAc,EAAE,EAAE;AAClB,gBAAA,QAAQ,EAAE,EAAE;AACZ,gBAAA,IAAI,EAAE,WAAW;AACjB,gBAAA,WAAW,EAAE,IAAI,CAAC,GAAG,EAAE;gBACvB,aAAa,EAAE,aAAa,IAAI,EAAE;AACrC,aAAA;YACD,WAAW,EAAE,IAAI,0BAA0B,EAAE;SAChD,CAAC;KACL;IAED,2BAA2B,GAAA;QACvB,OAAO,IAAI,0BAA0B,EAAE,CAAC;KAC3C;IACD,mBAAmB,GAAA;AACf,QAAA,OAAO,CAAC,CAAC;KACZ;IAED,mBAAmB,GAAA;QACf,OAAO;KACV;IAED,eAAe,GAAA;QACX,OAAO;KACV;IAED,cAAc,GAAA;AACV,QAAA,OAAO,IAAI,CAAC;KACf;IAED,mBAAmB,GAAA;QACf,OAAO;KACV;IAED,yBAAyB,GAAA;AACrB,QAAA,OAAO,IAAI,CAAC;KACf;IAED,sBAAsB,GAAA;AAClB,QAAA,OAAO,EAAE,CAAC;KACb;IAED,UAAU,GAAA;QACN,OAAO;KACV;IAED,SAAS,GAAA;QACL,OAAO;KACV;IAED,eAAe,GAAA;QACX,OAAO;KACV;IAED,yBAAyB,GAAA;QACrB,OAAO;KACV;AACJ;;;;"}

View File

@@ -0,0 +1,79 @@
import { CacheOutcome } from "../../utils/Constants.js";
import { CacheManager } from "../../cache/CacheManager.js";
import { ServerTelemetryRequest } from "./ServerTelemetryRequest.js";
import { ServerTelemetryEntity } from "../../cache/entities/ServerTelemetryEntity.js";
import { RegionDiscoveryMetadata } from "../../authority/RegionDiscoveryMetadata.js";
type SkuParams = {
libraryName?: string;
libraryVersion?: string;
extensionName?: string;
extensionVersion?: string;
skus?: string;
};
/** @internal */
export declare class ServerTelemetryManager {
private cacheManager;
private apiId;
private correlationId;
private telemetryCacheKey;
private wrapperSKU;
private wrapperVer;
private regionUsed;
private regionSource;
private regionOutcome;
private cacheOutcome;
constructor(telemetryRequest: ServerTelemetryRequest, cacheManager: CacheManager);
/**
* API to add MSER Telemetry to request
*/
generateCurrentRequestHeaderValue(): string;
/**
* API to add MSER Telemetry for the last failed request
*/
generateLastRequestHeaderValue(): string;
/**
* API to cache token failures for MSER data capture
* @param error
*/
cacheFailedRequest(error: unknown): void;
/**
* Update server telemetry cache entry by incrementing cache hit counter
*/
incrementCacheHits(): number;
/**
* Get the server telemetry entity from cache or initialize a new one
*/
getLastRequests(): ServerTelemetryEntity;
/**
* Remove server telemetry cache entry
*/
clearTelemetryCache(): void;
/**
* Returns the maximum number of errors that can be flushed to the server in the next network request
* @param serverTelemetryEntity
*/
static maxErrorsToSend(serverTelemetryEntity: ServerTelemetryEntity): number;
/**
* Get the region discovery fields
*
* @returns string
*/
getRegionDiscoveryFields(): string;
/**
* Update the region discovery metadata
*
* @param regionDiscoveryMetadata
* @returns void
*/
updateRegionDiscoveryMetadata(regionDiscoveryMetadata: RegionDiscoveryMetadata): void;
/**
* Set cache outcome
*/
setCacheOutcome(cacheOutcome: CacheOutcome): void;
setNativeBrokerErrorCode(errorCode: string): void;
getNativeBrokerErrorCode(): string | undefined;
clearNativeBrokerErrorCode(): void;
static makeExtraSkuString(params: SkuParams): string;
}
export {};
//# sourceMappingURL=ServerTelemetryManager.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"ServerTelemetryManager.d.ts","sourceRoot":"","sources":["../../../src/telemetry/server/ServerTelemetryManager.ts"],"names":[],"mappings":"AAKA,OAAO,EAGH,YAAY,EAIf,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAE3D,OAAO,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAC;AACrE,OAAO,EAAE,qBAAqB,EAAE,MAAM,+CA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AC,SAAS,EAAE,MAAM,GAAG,IAAI;IASjD,wBAAwB,IAAI,MAAM,GAAG,SAAS;IAI9C,0BAA0B,IAAI,IAAI;IASlC,MAAM,CAAC,kBAAkB,CAAC,MAAM,EAAE,SAAS,GAAG,MAAM;CAGvD"}

View File

@@ -0,0 +1,268 @@
/*! @azure/msal-common v15.1.1 2025-02-05 */
'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);
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);
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);
}
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);
}
}
/**
* 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);
}
getNativeBrokerErrorCode() {
return this.getLastRequests().nativeBrokerErrorCode;
}
clearNativeBrokerErrorCode() {
const lastRequests = this.getLastRequests();
delete lastRequests.nativeBrokerErrorCode;
this.cacheManager.setServerTelemetry(this.telemetryCacheKey, lastRequests);
}
static makeExtraSkuString(params) {
return makeExtraSkuString(params);
}
}
export { ServerTelemetryManager };
//# sourceMappingURL=ServerTelemetryManager.mjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,9 @@
export type ServerTelemetryRequest = {
clientId: string;
apiId: number;
correlationId: string;
forceRefresh?: boolean;
wrapperSKU?: string;
wrapperVer?: string;
};
//# sourceMappingURL=ServerTelemetryRequest.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"ServerTelemetryRequest.d.ts","sourceRoot":"","sources":["../../../src/telemetry/server/ServerTelemetryRequest.ts"],"names":[],"mappings":"AAKA,MAAM,MAAM,sBAAsB,GAAG;IACjC,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,MAAM,CAAC;IACd,aAAa,EAAE,MAAM,CAAC;IACtB,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,UAAU,CAAC,EAAE,MAAM,CAAC;CACvB,CAAC"}