/*! @azure/msal-browser v5.0.1 2026-01-16 */
'use strict';
import { ServerTelemetryManager, UrlString, Authority, invokeAsync, AuthorityFactory, createClientConfigurationError, ClientConfigurationErrorCodes } from '@azure/msal-common/browser';
import { AuthorityFactoryCreateDiscoveredInstance } from '../telemetry/BrowserPerformanceEvents.mjs';
import { version } from '../packageMetadata.mjs';
import { BrowserConstants } from '../utils/BrowserConstants.mjs';
import { getCurrentUri } from '../utils/BrowserUtils.mjs';

/*
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License.
 */
class BaseInteractionClient {
    constructor(config, storageImpl, browserCrypto, logger, eventHandler, navigationClient, performanceClient, correlationId, platformAuthProvider) {
        this.config = config;
        this.browserStorage = storageImpl;
        this.browserCrypto = browserCrypto;
        this.networkClient = this.config.system.networkClient;
        this.eventHandler = eventHandler;
        this.navigationClient = navigationClient;
        this.platformAuthProvider = platformAuthProvider;
        this.correlationId = correlationId;
        this.logger = logger.clone(BrowserConstants.MSAL_SKU, version);
        this.performanceClient = performanceClient;
    }
}
/**
 * Use to get the redirect URI configured in MSAL or construct one from the current page.
 * @param requestRedirectUri - Redirect URI from the request or undefined if not configured
 * @param clientConfigRedirectUri - Redirect URI from the client configuration or undefined if not configured
 * @param logger - Logger instance from the calling client
 * @param correlationId
 * @returns Absolute redirect URL constructed from the provided URI, config, or current page
 */
function getRedirectUri(requestRedirectUri, clientConfigRedirectUri, logger, correlationId) {
    logger.verbose("0bd1la", correlationId);
    const redirectUri = requestRedirectUri || clientConfigRedirectUri || "";
    return UrlString.getAbsoluteUrl(redirectUri, getCurrentUri());
}
/**
 * Initializes and returns a ServerTelemetryManager with the provided telemetry configuration.
 * @param apiId - The API identifier for telemetry tracking
 * @param clientId - The client application identifier
 * @param correlationId - Unique identifier for correlating requests
 * @param browserStorage - Browser cache manager instance for storing telemetry data
 * @param logger - Optional logger instance for verbose logging
 * @param forceRefresh - Optional flag to force refresh of telemetry data
 * @returns Configured ServerTelemetryManager instance
 */
function initializeServerTelemetryManager(apiId, clientId, correlationId, browserStorage, logger, forceRefresh) {
    logger.verbose("1p12tq", correlationId);
    const telemetryPayload = {
        clientId: clientId,
        correlationId: correlationId,
        apiId: apiId,
        forceRefresh: forceRefresh || false,
        wrapperSKU: browserStorage.getWrapperMetadata()[0],
        wrapperVer: browserStorage.getWrapperMetadata()[1],
    };
    return new ServerTelemetryManager(telemetryPayload, browserStorage);
}
/**
 * Used to get a discovered version of the default authority.
 * @param params - Configuration object containing authority and cloud options
 * @param params.requestAuthority - Optional specific authority URL to use
 * @param params.requestAzureCloudOptions - Optional Azure cloud configuration options
 * @param params.requestExtraQueryParameters - Optional additional query parameters
 * @param params.account - Optional account info for instance-aware scenarios
 * @param config - Browser configuration containing auth settings
 * @param correlationId - Unique identifier for correlating requests
 * @param performanceClient - Performance monitoring client instance
 * @param browserStorage - Browser cache manager instance
 * @param logger - Logger instance for tracking operations
 * @returns Promise that resolves to a discovered Authority instance
 */
async function getDiscoveredAuthority(config, correlationId, performanceClient, browserStorage, logger, requestAuthority, requestAzureCloudOptions, requestExtraQueryParameters, account) {
    const instanceAwareEQ = requestExtraQueryParameters &&
        requestExtraQueryParameters.hasOwnProperty("instance_aware")
        ? requestExtraQueryParameters["instance_aware"]
        : undefined;
    const authorityOptions = {
        protocolMode: config.system.protocolMode,
        OIDCOptions: config.auth.OIDCOptions,
        knownAuthorities: config.auth.knownAuthorities,
        cloudDiscoveryMetadata: config.auth.cloudDiscoveryMetadata,
        authorityMetadata: config.auth.authorityMetadata,
    };
    // build authority string based on auth params, precedence - azureCloudInstance + tenant >> authority
    const resolvedAuthority = requestAuthority || config.auth.authority;
    const resolvedInstanceAware = instanceAwareEQ?.length
        ? instanceAwareEQ === "true"
        : config.auth.instanceAware;
    const userAuthority = account && resolvedInstanceAware
        ? config.auth.authority.replace(UrlString.getDomainFromUrl(resolvedAuthority), account.environment)
        : resolvedAuthority;
    // fall back to the authority from config
    const builtAuthority = Authority.generateAuthority(userAuthority, requestAzureCloudOptions || config.auth.azureCloudOptions);
    const discoveredAuthority = await invokeAsync(AuthorityFactory.createDiscoveredInstance, AuthorityFactoryCreateDiscoveredInstance, logger, performanceClient, correlationId)(builtAuthority, config.system.networkClient, browserStorage, authorityOptions, logger, correlationId, performanceClient);
    if (account && !discoveredAuthority.isAlias(account.environment)) {
        throw createClientConfigurationError(ClientConfigurationErrorCodes.authorityMismatch);
    }
    return discoveredAuthority;
}
/**
 * Clears cache and account information during logout.
 *
 * If an account is provided, removes the account from cache and, if it is the active account, sets the active account to null.
 * If no account is provided, clears all accounts and tokens from cache.
 *
 * @param browserStorage - The browser cache manager instance used to manage cache.
 * @param browserCrypto - The crypto interface for cache operations.
 * @param logger - Logger instance for logging operations.
 * @param correlationId - Correlation ID for the logout operation.
 * @param account - (Optional) The account to clear from cache. If not provided, all accounts are cleared.
 * @returns A promise that resolves when the cache has been cleared.
 */
async function clearCacheOnLogout(browserStorage, browserCrypto, logger, correlationId, account) {
    if (account) {
        // Clear given account.
        try {
            browserStorage.removeAccount(account, correlationId);
            logger.verbose("0s4z6h", correlationId);
        }
        catch (error) {
            logger.error("0mgg1d", correlationId);
        }
    }
    else {
        try {
            logger.verbose("0zj631", correlationId);
            // Clear all accounts and tokens
            browserStorage.clear(correlationId);
            // Clear any stray keys from IndexedDB
            await browserCrypto.clearKeystore(correlationId);
        }
        catch (e) {
            logger.error("12ih0c", correlationId);
        }
    }
}

export { BaseInteractionClient, clearCacheOnLogout, getDiscoveredAuthority, getRedirectUri, initializeServerTelemetryManager };
//# sourceMappingURL=BaseInteractionClient.mjs.map
